namespace XFEEDToolBox.Core.Navigation; /// Application-side local flight policy. Only observed game transitions advance a leg. public sealed class SystemFlightNavigator { public const double DockingContactDistance=7500; private DateTimeOffset lastDockRequest=DateTimeOffset.MinValue,lastAssistRequest=DateTimeOffset.MinValue,lastEntryRequest=DateTimeOffset.MinValue,lastDropRequest=DateTimeOffset.MinValue; private DateTimeOffset? nativeLandingSince; private bool nativeLandingObserved; private DateTimeOffset lastThrusterBoost=DateTimeOffset.MinValue; private DateTimeOffset? assistAlignedSince; private bool softwareCruise; private bool softwareLanding; private bool cruiseBraking,cruiseAligned; private bool bypassingObstruction; private bool cruiseObserved,glideObserved,descentStarted; private ulong pathRevision; private int pathIndex; public SystemFlightDecision Decide(SystemFlightFrame frame,SystemNavigationTarget target,DateTimeOffset now) { target.Validate(); if(!frame.InGame)return Stop("游戏尚未处于驾驶场景,已交还控制。"); if(frame.PlayerOverride)return Stop("原生接口报告玩家接管,已交还飞船控制。"); if(frame.ExternalThreat)return Stop("已检测到外部威胁,已停止导航并交还控制。"); if(frame.SystemAddress!=target.SystemAddress||frame.SelectedTarget is not {} selected||!target.SameIdentity(selected)) return Stop("游戏目标或所在星系已改变,已停止导航。"); if(!Valid(frame,now))return Wait("正在重新读取目标与飞行数据。"); if(frame.Mode==LocalFlightMode.Docked) return frame.DockedMarketId==target.MarketId&&target.NeedsDocking ?new(SystemNavigationPhase.Completed,$"已停靠 {target.Name}",null,null,SystemNavigationAction.ReleaseFlightAxes) :Stop("飞船已停靠其他站点,已停止导航。"); if(frame.Mode is LocalFlightMode.Unknown or LocalFlightMode.Transition)return Wait("等待飞行模式切换完成。"); var componentThermalControl=frame.Mode==LocalFlightMode.Supercruise&&frame.OriginalScoThermalControlVerified &&!frame.Assists.Supercruise&&frame.SupercruiseAssist is not (NativeAssistState.Requested or NativeAssistState.Aligning or NativeAssistState.Engaged) &&frame.OriginalScoThermalControlExpiresAt is {} thermalExpiry&&now<=thermalExpiry&&thermalExpiry<=now.AddMilliseconds(200); if(frame.HeatPercent is >=100||frame.HeatPercent is >90&&!componentThermalControl) return new(SystemNavigationPhase.Waiting,"正在减速降温。",frame.ClearDirection,0); var direction=(frame.TargetPosition-frame.Position).Unit(); // A far-side destination must first be reached in supercruise. Flying // around an entire planet at normal-space speed cannot clear that leg. if(frame.Mode==LocalFlightMode.Normal&&!cruiseObserved&&!glideObserved&&!descentStarted&&frame.TargetDistance>Math.Max(20000,frame.MaximumNormalSpeed*120)) { var departure=direction; if(frame.TargetObscured) { if(frame.ClearDirection is not {Finite:true,Length:>.9} clear)return Wait("正在寻找安全的超巡离场方向。"); departure=clear.Unit(); } var aligned=Vector3d.AngleDegrees(frame.Forward,departure)<=5; var action=SystemNavigationAction.None; if(aligned&&frame.FsdReady&&now-lastEntryRequest>=TimeSpan.FromSeconds(3)){lastEntryRequest=now;action=SystemNavigationAction.EnterSupercruise;} return new(SystemNavigationPhase.EnteringSupercruise,aligned?frame.FsdReady?"正在进入超巡。":"正在飞离质量锁定范围。":"正在对齐超巡离场方向。",departure,aligned?1:0,action); } if(frame.TargetObscured) { if(frame.ClearDirection is not {} clear||!clear.Finite||clear.Length<.9||Math.Abs(Vector3d.Dot(clear.Unit(),direction))>.02||frame.CollisionCourse) return new(SystemNavigationPhase.Waiting,"目标被遮挡,正在重新寻找可通行方向。",null,0,SystemNavigationAction.CancelOwnedAssists); bypassingObstruction=true;assistAlignedSince=null;lastAssistRequest=DateTimeOffset.MinValue;cruiseAligned=false; var aligned=Vector3d.AngleDegrees(frame.Forward,clear)<=5; return new(SystemNavigationPhase.Aligning,aligned?"正在全速绕开遮挡目标的天体。":"正在对齐无障碍的侧向绕行方向。",clear.Unit(),aligned?1:0,SystemNavigationAction.CancelOwnedAssists); } if(bypassingObstruction) { bypassingObstruction=false;assistAlignedSince=null;lastAssistRequest=DateTimeOffset.MinValue;softwareCruise=false;cruiseAligned=false; return new(SystemNavigationPhase.Aligning,"目标遮挡已解除,正在归零节流并重新对齐。",direction,0); } if(frame.Mode is LocalFlightMode.Supercruise or LocalFlightMode.OrbitalCruise)cruiseObserved=true; if(target.IsSurface&&frame.Mode is LocalFlightMode.Supercruise or LocalFlightMode.OrbitalCruise or LocalFlightMode.Glide) return Planetary(frame,target,now); if(frame.Mode==LocalFlightMode.Glide)return Stop("非地表航段出现滑翔状态,已交还飞船控制。"); if(frame.Mode is LocalFlightMode.Supercruise or LocalFlightMode.OrbitalCruise) return Cruise(frame,direction,now); if(target.NeedsDocking)return Station(frame,target,direction,now); if(target.IsSurface) { if(frame.Planet is not {} planet||!PlanetValid(planet,target))return Wait("正在重新读取地表位置。"); var radial=(frame.Position-planet.Centre).Unit(); if(planet.GroundDistance<250&&frame.Speed<5&&planet.Altitude<=planet.Limits.GlideExitAltitude) return new(SystemNavigationPhase.Completed,$"已到达 {target.Name} 上空",null,0,SystemNavigationAction.ReleaseFlightAxes); return new(SystemNavigationPhase.NormalApproach,"正在飞往地表目标上空。",SurfaceApproachGeometry.LevelDirection(planet,frame.Position,frame.Forward), NormalThrottle(frame,planet.GroundDistance,0)){UpDirection=radial}; } if(frame.TargetDistance<1000&&frame.Speed<10) return new(SystemNavigationPhase.Completed,$"已抵达 {target.Name}",null,0,SystemNavigationAction.ReleaseFlightAxes); return new(SystemNavigationPhase.NormalApproach,"正在接近目标。",direction,NormalThrottle(frame,frame.TargetDistance,500)); } private SystemFlightDecision Cruise(SystemFlightFrame frame,Vector3d direction,DateTimeOffset now) { var unavailable=!frame.Assists.Supercruise||frame.SupercruiseAssist is NativeAssistState.Unavailable or NativeAssistState.Disabled or NativeAssistState.Failed; if(unavailable) { softwareCruise=true;assistAlignedSince=null; } if(frame.Assists.Supercruise&&frame.SupercruiseAssist==NativeAssistState.Engaged) return new(SystemNavigationPhase.Supercruise,"飞船超巡辅助已接管,正在前往目标。",null,null,SystemNavigationAction.ReleaseFlightAxes); if(frame.Assists.Supercruise&&!softwareCruise&&frame.SupercruiseAssist==NativeAssistState.Requested) { assistAlignedSince??=now; if(now-assistAlignedSince<=TimeSpan.FromSeconds(20)) return new(SystemNavigationPhase.Aligning,"等待游戏确认超巡辅助接管。",null,null,SystemNavigationAction.ReleaseFlightAxes); softwareCruise=true; return new(SystemNavigationPhase.Supercruise,"辅助未接管,正在由工具箱控制超巡进近。",direction,CruiseThrottle(frame),SystemNavigationAction.CancelOwnedAssists); } // SafeDisengage is an original game predicate, never inferred from distance alone. if(frame.SafeDisengage&&frame.SafeDropDistance>0&&frame.SafeDropSpeed>0&&frame.TargetDistance<=frame.SafeDropDistance&&frame.Speed<=frame.SafeDropSpeed) { var action=SystemNavigationAction.None; if(now-lastDropRequest>=TimeSpan.FromSeconds(2)){lastDropRequest=now;action=SystemNavigationAction.SafeDisengage;} return new(SystemNavigationPhase.Supercruise,"正在安全脱离超巡。",direction,0,action|(unavailable?SystemNavigationAction.CancelOwnedAssists:0)); } var error=Vector3d.AngleDegrees(frame.Forward,direction); var tolerance=Math.Clamp(frame.AssistAlignmentDegrees,1,10); if(frame.SupercruiseAssist==NativeAssistState.Failed)softwareCruise=true; if(frame.Assists.Supercruise&&!softwareCruise&&frame.SupercruiseAssist!=NativeAssistState.Unavailable) { var action=SystemNavigationAction.None; if(error>tolerance)assistAlignedSince=null;else assistAlignedSince??=now; if(assistAlignedSince is {} since&&now-since>TimeSpan.FromSeconds(20)) { softwareCruise=true; return new(SystemNavigationPhase.Supercruise,"辅助未接管,正在由工具箱控制超巡进近。",direction,CruiseThrottle(frame),SystemNavigationAction.CancelOwnedAssists); } if(error<=tolerance&&now-lastAssistRequest>=TimeSpan.FromSeconds(1)) {lastAssistRequest=now;action=SystemNavigationAction.EnableSupercruiseAssist;} // The original activation sets its initial desired throttle once. // Yield from that request onward, including enabled-but-not-engaged // observations, so the fitted computer can engage without a lease // continually overriding its throttle or steering. return error>tolerance ?new(SystemNavigationPhase.Aligning,"正在对齐超巡目标。",direction,0) :new(SystemNavigationPhase.Aligning,"等待游戏确认超巡辅助接管。",null,null,action|SystemNavigationAction.ReleaseFlightAxes); } if(error>10)cruiseAligned=false;else if(error<=tolerance)cruiseAligned=true; return new(SystemNavigationPhase.Supercruise,cruiseAligned?"正在由工具箱控制超巡进近。":"正在对齐超巡目标。",direction,cruiseAligned?CruiseThrottle(frame):0, unavailable?SystemNavigationAction.CancelOwnedAssists:SystemNavigationAction.None); } private SystemFlightDecision Planetary(SystemFlightFrame frame,SystemNavigationTarget target,DateTimeOffset now) { if(frame.Planet is not {} planet||!PlanetValid(planet,target))return Wait("正在重新读取行星进近参数。"); var limits=planet.Limits;var radial=(frame.Position-planet.Centre).Unit(); if(frame.Mode==LocalFlightMode.Glide) { glideObserved=descentStarted=true; var tooSteep=planet.DescentAngleDegrees>=limits.MaximumGlideAngleDegrees-3; return new(SystemNavigationPhase.Glide,tooSteep?"正在减小下降角,保持滑翔。":"正在滑翔接近地表目标。", tooSteep?SurfaceApproachGeometry.LevelDirection(planet,frame.Position,frame.Forward):SurfaceApproachGeometry.ShallowApproach(planet,frame.Position,frame.Forward), null,SystemNavigationAction.CancelOwnedAssists){UpDirection=radial}; } var entry=SurfaceApproachGeometry.EntryPoint(planet,frame.Position); var entryRange=(entry-frame.Position).Length; var entryArc=SurfaceApproachGeometry.SurfaceRange(frame.Position,entry,planet.Centre,limits.Radius); var mayDescend=entryArcallowed||planet.DescentAngleDegrees>=limits.MaximumGlideAngleDegrees-3) return new(SystemNavigationPhase.OrbitalApproach,"正在重力井内减速并修正下降角。",SurfaceApproachGeometry.LevelDirection(planet,frame.Position,frame.Forward),0,SystemNavigationAction.CancelOwnedAssists){UpDirection=radial}; return new(SystemNavigationPhase.OrbitalApproach,"正在以受控速度和角度进入滑翔。",SurfaceApproachGeometry.ShallowApproach(planet,frame.Position,frame.Forward), Govern(frame.Speed,allowed,.5),SystemNavigationAction.CancelOwnedAssists){UpDirection=radial}; } // A far-side site must be approached around the planet; never point through its centre. var delta=entry-frame.Position; var crossesPlanet=SurfaceApproachGeometry.IntersectsPlanet(frame.Position,entry,planet.Centre,limits.Radius+limits.GlideEntryAltitude); var direction=crossesPlanet ?SurfaceApproachGeometry.LevelDirection(planet,frame.Position,frame.Forward):delta.Unit(); var throttle=Govern(frame.Speed,Math.Min(maximum,Math.Max(limits.MaximumGlideSpeed,entryRange/8)),.75); return new(SystemNavigationPhase.OrbitalApproach,"正在前往地表目标的轨道进近点。",direction,throttle,SystemNavigationAction.CancelOwnedAssists){UpDirection=radial}; } private SystemFlightDecision Station(SystemFlightFrame frame,SystemNavigationTarget target,Vector3d direction,DateTimeOffset now) { if(!frame.Assists.AutoDock||frame.DockingAssist is NativeAssistState.Unavailable or NativeAssistState.Disabled or NativeAssistState.Failed) {softwareLanding=true;nativeLandingSince=null;nativeLandingObserved=false;} var clearance=frame.Clearance; if(clearance?.Allows(target,now)!=true) { nativeLandingSince=null;nativeLandingObserved=false;pathIndex=0;pathRevision=0; if(frame.TargetDistance>DockingContactDistance) { var boost=SystemNavigationAction.None; if(!softwareLanding&&frame.ThrusterBoostAvailable&&!frame.LandingGearDown&&Vector3d.AngleDegrees(frame.Forward,direction)<=5 &&now-lastThrusterBoost>=TimeSpan.FromSeconds(5)) {lastThrusterBoost=now;boost=SystemNavigationAction.BoostThrusters;} return new(SystemNavigationPhase.NormalApproach,"正在以固定全节流接近 7.5 km 空管范围。",direction, !softwareLanding?1:NormalThrottle(frame,frame.TargetDistance,6500),boost); } if(clearance is {Permission:DockingPermission.Denied,Retryable:false}&&clearance.MarketId==target.MarketId) return Stop("空间站拒绝停靠:"+clearance.Reason); // A close supercruise drop can start inside ATC range. Zero and // request clearance in this same decision; the native request // commits ordinary zero input before calling ATC on its owning thread. var action=SystemNavigationAction.None; if(now-lastDockRequest>=TimeSpan.FromSeconds(10)) {lastDockRequest=now;action=SystemNavigationAction.RequestDocking;} return new(action==SystemNavigationAction.None?SystemNavigationPhase.AwaitingClearance:SystemNavigationPhase.RequestingDocking, action==SystemNavigationAction.None?"正在等待目标空间站的空管许可。":"正在呼叫目标空间站空管。",direction,0,action); } if(frame.Assists.AutoDock&&!softwareLanding) { nativeLandingSince??=now; if(frame.DockingAssist==NativeAssistState.Engaged) { nativeLandingObserved=true;nativeLandingSince=now; return new(SystemNavigationPhase.NativeLanding,$"自动降落已接管,停机坪 {clearance!.Pad}。",null,null,SystemNavigationAction.ReleaseFlightAxes); } if(!nativeLandingObserved&&DockingHandoffPolicy.RecoveryRequired(frame.TargetDistance,nativeLandingSince.Value,now)) return new(SystemNavigationPhase.Stopped,DockingHandoffPolicy.RecoveryMessage(frame.TargetDistance),null,null,SystemNavigationAction.ExitForFailedHandoff); if(now-nativeLandingSince>TimeSpan.FromSeconds(30))return Stop("飞船自动降落未能接管,已交还控制。"); if(nativeLandingObserved) return new(SystemNavigationPhase.NativeLanding,"正在等待游戏确认停靠完成。",null,null,SystemNavigationAction.ReleaseFlightAxes); if(frame.DockingAssistEnabled&&Math.Abs(frame.Throttle)<=.001) // The original input has reached zero. A continuously renewed // zero-axis lease can itself prevent the landing duty starting. return new(SystemNavigationPhase.NativeLanding,"等待游戏确认自动降落接管。",null,null,SystemNavigationAction.ReleaseFlightAxes); // Release our reversible axis overlay BEFORE the original zero // input event. Otherwise its restore can resurrect the SCA's .75 // baseline, and an overlaid zero is mistaken for a durable zero. // The original event owns throttle; a real grant remains required. return new(SystemNavigationPhase.NativeLanding,Math.Abs(frame.Throttle)>.01?"已获停靠许可,正在将节流阀归零。":"等待游戏确认自动降落接管。",null,0, SystemNavigationAction.EnableDockingAssist|SystemNavigationAction.ReleaseFlightAxes); } var landing=FollowDockingPath(frame,target,now); // The old AI duty can survive a module power/health transition. Its // cancellation must be acknowledged before the driver applies our // approach inputs, including while the real pad path is being read. return landing with{Actions=landing.Actions|SystemNavigationAction.CancelOwnedAssists}; } private SystemFlightDecision FollowDockingPath(SystemFlightFrame frame,SystemNavigationTarget target,DateTimeOffset now) { var path=frame.DockingPath; if(path is null||path.MarketId!=target.MarketId||path.Pad!=frame.Clearance!.Pad||path.Revision==0||path.Points.Count==0||path.Points.Count>1024 ||path.ObservedAt>now||now-path.ObservedAt>TimeSpan.FromMilliseconds(500)||!double.IsFinite(path.ShipClearanceRadius)||path.ShipClearanceRadius<=0) return new(SystemNavigationPhase.Waiting,"正在读取空间站进场路径和获准停机坪。",null,0){Translation=Vector3d.Zero}; if(pathRevision!=path.Revision){pathRevision=path.Revision;pathIndex=0;} var point=path.Points[Math.Min(pathIndex,path.Points.Count-1)]; if(!Valid(point)||frame.CollisionCourse)return new(SystemNavigationPhase.Waiting,"正在避让进场交通并重新核对路径。",null,0){Translation=Vector3d.Zero}; var delta=point.Position-frame.Position;var relative=frame.Velocity-point.Velocity; var error=Vector3d.AngleDegrees(frame.Forward,point.Forward); if(delta.Length.05?delta.Unit()*speed:Vector3d.Zero; var acceleration=(desired-relative)*.8; if(acceleration.Length>frame.TranslationAcceleration)acceleration=acceleration.Unit()*frame.TranslationAcceleration; var input=acceleration*(1/frame.TranslationAcceleration); return new(SystemNavigationPhase.ApplicationLanding,$"正在沿空间站进场路径降落,停机坪 {path.Pad}。",point.Forward,0, point.DeployGear&&!frame.LandingGearDown?SystemNavigationAction.DeployLandingGear:SystemNavigationAction.None) {UpDirection=point.Up,Translation=input}; } private static bool Valid(DockingPathPoint point)=>point.Position.Finite&&point.Velocity.Finite&&point.Forward.Finite&&point.Forward.Length>.9&&point.Up.Finite&&point.Up.Length>.9 &&Math.Abs(Vector3d.Dot(point.Forward.Unit(),point.Up.Unit()))<.02&&double.IsFinite(point.MaximumSpeed)&&point.MaximumSpeed>0&&point.MaximumSpeed<=100 &&double.IsFinite(point.ArrivalRadius)&&point.ArrivalRadius>0; private static bool PlanetValid(PlanetApproachFrame planet,SystemNavigationTarget target)=>planet.BodyAddress==target.PlanetAddress&&planet.Limits.Valid &&planet.Centre.Finite&&planet.SurfaceDestination.Finite&&planet.SurfaceNormal.Finite&&planet.North.Finite &&double.IsFinite(planet.Altitude)&&planet.Altitude>=0&&double.IsFinite(planet.GroundDistance)&&planet.GroundDistance>=0&&double.IsFinite(planet.DescentAngleDegrees); private static bool Valid(SystemFlightFrame frame,DateTimeOffset now)=>frame.GeometryVerified&&frame.Sequence>0&&frame.ShipEntity>0&&frame.ReferenceWorld>0 &&frame.ObservedAt<=now&&now-frame.ObservedAt<=TimeSpan.FromMilliseconds(300)&&frame.Position.Finite&&frame.Velocity.Finite&&frame.Forward.Finite&&frame.Up.Finite &&frame.Forward.Length>.9&&frame.Up.Length>.9&&Math.Abs(Vector3d.Dot(frame.Forward.Unit(),frame.Up.Unit()))<.02&&frame.TargetPosition.Finite&&frame.TargetVelocity.Finite &&new[]{frame.TargetDistance,frame.Speed,frame.Throttle,frame.MaximumNormalSpeed,frame.MaximumCruiseSpeed,frame.BrakingAcceleration,frame.TranslationAcceleration,frame.LegalApproachSpeed,frame.AssistAlignmentDegrees}.All(double.IsFinite) &&frame.TargetDistance>=0&&frame.Speed>=0&&frame.Throttle is >=-1 and <=1&&frame.MaximumNormalSpeed>0&&frame.MaximumCruiseSpeed>0&&frame.BrakingAcceleration>0&&frame.TranslationAcceleration>0&&frame.LegalApproachSpeed>0; private double CruiseThrottle(SystemFlightFrame frame) { if(!frame.CruiseParametersVerified||!double.IsFinite(frame.CruiseApproachSeconds)||frame.CruiseApproachSeconds<=0 ||!double.IsFinite(frame.CruiseApproachThrottle)||frame.CruiseApproachThrottle is <=0 or >1)return 0; // The game already enforces its sampled speed limit. Do not issue a // zero-throttle pulse for crossing it; active approach braking uses // the verified target arrival window instead. var allowed=Math.Max(frame.SafeDropSpeed*.8,frame.TargetDistance/frame.CruiseApproachSeconds); // Throttle is a position in the original speed controller. Hold its // configured approach setting; normal game deceleration handles the // speed curve. Separate brake/release thresholds prevent switching // between zero and approach throttle on adjacent velocity samples. if(frame.Speed>allowed*1.1)cruiseBraking=true; else if(frame.SpeedGovern(frame.Speed,Math.Min(Math.Min(frame.LegalApproachSpeed,100),Math.Sqrt(2*frame.BrakingAcceleration*Math.Max(0,distance-holdDistance))*.5),.5); private static double Govern(double speed,double allowed,double ceiling)=>allowed<=0||speed>=allowed?0:speed>allowed*.8?Math.Min(.25,ceiling):ceiling; private static SystemFlightDecision Wait(string message)=>new(SystemNavigationPhase.Waiting,message,null,null,SystemNavigationAction.ReleaseFlightAxes); private static SystemFlightDecision Stop(string message)=>new(SystemNavigationPhase.Stopped,message,null,null,SystemNavigationAction.ReleaseFlightAxes|SystemNavigationAction.CancelOwnedAssists); }