namespace XFEEDToolBox.Core.Navigation; public enum FsdPhase { Idle,Charging,Charged,Jumping,Cooldown } public sealed record FlightFrame { public long Sequence { get; init; } public DateTimeOffset ObservedAt { get; init; } public string GameSha256 { get; init; }=""; public string LoadoutFingerprint { get; init; }=""; public bool GeometryVerified { get; init; } public bool InSupercruise { get; init; } public bool PlayerOverride { get; init; } public Vector3d Position { get; init; } public Vector3d Forward { get; init; } public Vector3d Up { get; init; } public Vector3d? AngularVelocityDegrees { get; init; } public Vector3d TargetPosition { get; init; } public long SystemAddress { get; init; } public long TargetSystemAddress { get; init; } public double SpeedMetresPerSecond { get; init; } public double SpeedFraction { get; init; } public int? EnginePips { get; init; } public double? ObservedThrottleCommand { get; init; } public double? HeatPercent { get; init; } public double? FuelMain { get; init; } public double? FuelRequiredForJump { get; init; } public double? FuelNeededToNextRefuel { get; init; } public double? MinimumFuelToNextRefuel { get; init; } public bool ScoopPowered { get; init; } public bool ScoopActive { get; init; } public bool AdaptiveFlightControl { get; init; } public bool NativeHeatWarning { get; init; } public bool ThermalDangerExplained { get; init; } public bool RefuellingToFull { get; init; } public double? FuelTankCapacity { get; init; } public double? ScoopRate { get; init; } public double? ScoopMaximumRate { get; init; } public double? ScoopFullRateRadius { get; init; } public double? ScoopEfficiency { get; init; } public double? AngularSpeedDegreesPerSecond { get; init; } public double? PreferredOrbitRadius { get; init; } public bool OutwardDepartureRequired { get; init; } public bool? NativeAllowsCharging { get; init; } public double? NativeFullChargePeak { get; init; } public StarEnvelope? CurrentStar { get; init; } public IReadOnlyList Obstacles { get; init; }=[]; public FsdPhase Fsd { get; init; } public bool CanBeginCharge { get; init; } // A verified native driver can hold a charged FSD without committing a jump. // Merely withholding PermitJump in this controller does not establish that property in the game. public bool JumpCommitInterlockVerified { get; init; } public double? ChargeSecondsRemaining { get; init; } public double AlignmentRateLowerDegreesPerSecond { get; init; } public double? ManoeuvreSecondsUpper { get; init; } public double? RefuelSecondsUpper { get; init; } public double? PlannedMinimumStarDistance { get; init; } public double? PlannedMaximumStarDistance { get; init; } } public sealed record FlightDecision(string State,Vector3d? Direction,double Throttle,bool BeginCharging,bool CancelCharging,bool PermitJump,double? PredictedPeakHeat,string Reason) { public bool EnterSupercruise { get; init; } public bool CoolingRecovery { get; init; } public Vector3d? UpDirection { get; init; } } /// Pure controller. Decisions are not game commands; a separately verified native driver must apply them. public sealed class FlightNavigator { private DateTimeOffset? alignedSince; private long lastSequence; private long lastTarget; private DateTimeOffset? lastObservation; private long orbitBody,orbitTarget,orbitSystem; private Vector3d? orbitPlane; private readonly ScoopThermalController scoopThermal=new(); private bool chargeRecovery; public FlightDecision Decide(FlightFrame frame,NavWaypoint next,ShipThermalCalibration? heatModel,DateTimeOffset now) { FlightDecision Hold(string reason){alignedSince=null;return new("等待有效遥测",null,0,false,frame.Fsd is FsdPhase.Charging or FsdPhase.Charged,false,null,reason);} if(frame.Sequence<=lastSequence||now-frame.ObservedAt>TimeSpan.FromMilliseconds(300)||frame.ObservedAt>now.AddMilliseconds(100))return Hold("姿态、热量或位置数据超时/乱序,停止控制并取消充能。"); if(lastTarget!=next.SystemAddress){alignedSince=null;chargeRecovery=false;} else if(lastObservation is {} previous&&frame.ObservedAt-previous>TimeSpan.FromMilliseconds(300))alignedSince=null; lastTarget=next.SystemAddress;lastObservation=frame.ObservedAt; lastSequence=frame.Sequence; if(frame.PlayerOverride){alignedSince=null;return new("玩家接管",null,0,false,true,false,null,"检测到玩家主动操作,释放自动控制。");} if(frame.Fsd==FsdPhase.Jumping){alignedSince=null;return new("跃迁中",null,0,false,false,false,null,"等待实际抵达事件。");} if(!frame.GeometryVerified||!frame.Position.Finite||!frame.Forward.Finite||!frame.Up.Finite||!frame.TargetPosition.Finite||frame.Forward.Length<.9||frame.Up.Length<.9||frame.CurrentStar is not {} star||!star.Centre.Finite||!double.IsFinite(star.ExclusionRadius)||star.ExclusionRadius<=0)return Hold("必须读取并校验姿态、米制位置与恒星排除区,不能凭日志猜测。"); if(frame.TargetSystemAddress!=next.SystemAddress)return Hold("游戏锁定的目的地与下一跳不一致。"); if(!frame.JumpCommitInterlockVerified)return Hold("底层的充满等待与跃迁放行控制尚未校验,不能并行充能。"); if(frame.HeatPercent is not {} heat||!double.IsFinite(heat)||heat<0)return Hold("尚未读取连续热量百分比。"); if(frame.FuelMain is not {} fuel||frame.FuelRequiredForJump is not {} jumpFuel||frame.FuelNeededToNextRefuel is not {} reserve||!double.IsFinite(fuel)||!double.IsFinite(jumpFuel)||!double.IsFinite(reserve)||fuel<0||jumpFuel<=0||reserves.BodyId).ToArray(); if(all.Any(s=>!s.Centre.Finite||!double.IsFinite(s.ExclusionRadius)||s.ExclusionRadius<=0))return Hold("附近天体包络不完整。"); var inside=all.FirstOrDefault(s=>(frame.Position-s.Centre).Length<=s.SafeRadius); if(inside is not null) { var escape=frame.Position-inside.Centre; if(escape.Length<1)return Hold("飞船与附近天体的位置重合,不能计算脱离方向。"); alignedSince=null;return new("脱离排除区",escape.Unit(),.25,false,true,false,null,"优先向外脱离,禁止高能跃迁充能。"); } if(heat>=97&&!frame.AdaptiveFlightControl){alignedSince=null;return new("散热脱离",radial.Unit(),.7,false,true,false,heat,"热量接近上限,先离开恒星并散热。");} if(frame.AdaptiveFlightControl)return DecideAdaptive(frame,heatModel,now,star,radial,target,all,Orbit); var needFuel=fuel0&&ScoopRules.CanRefuel(star.StarClass); if(needFuel&&(!frame.ScoopPowered||!canScoop))return Hold(frame.ScoopPowered?"当前恒星不能采集氢燃料,无法安全完成燃油预算。":"未检测到已启用油勺,当前燃油不能覆盖补给预算。"); var blocker=all.Where(s=>FlightGeometry.Obscures(s,frame.Position,frame.TargetPosition)).OrderBy(s=>(frame.Position-s.Centre).Length).FirstOrDefault(); Vector3d direction;string motion; if(needFuel||(blocker?.BodyId==star.BodyId&&frame.ScoopPowered&&canScoop)) { try{direction=frame.PreferredOrbitRadius is {} radius?Orbit(radius):FlightGeometry.OrbitDirection(star,frame.Position,frame.TargetPosition,frame.Up);} catch(InvalidOperationException e){return Hold(e.Message);} motion=needFuel?"绕星补给":"绕星避让并采集"; } else if(blocker is not null){direction=FlightGeometry.FastClearDirection(blocker,frame.Position,frame.TargetPosition,frame.Up);motion="最短侧向避让";} else{direction=target.Unit();motion="对准下一跳";} var outward=Vector3d.Dot(radial,target)>=0; if((frame.OutwardDepartureRequired||frame.PreferredOrbitRadius is >0)&&(needFuel||blocker is not null||frame.OutwardDepartureRequired&&!outward)) { var activeFsd=frame.Fsd is FsdPhase.Charging or FsdPhase.Charged; if(heat>=88){alignedSince=null;return new("散热脱离",radial.Unit(),.7,false,activeFsd,false,heat,"绕行热量达到提前脱离阈值,先向外散热。");} if(!outward&&blocker is null&&!needFuel) {direction=Orbit(Math.Max(radial.Length,star.SafeRadius*1.03));motion="绕行至安全离场角";} var motionForecast=ThermalPredictor.Predict(heatModel is null?null:heatModel with{ChargingGainUpperPerSecond=0,ChargedHoldGainUpperPerSecond=0},frame.GameSha256,frame.LoadoutFingerprint,star.BodyId,heat,radial.Length,radial.Length,0,8,now); if(!motionForecast.Known)return Hold(motionForecast.Reason); if(!motionForecast.AllowsCharging){alignedSince=null;return new("散热脱离",radial.Unit(),.7,false,activeFsd,false,motionForecast.PeakPercent,"预计绕行期间热量超限,先向外散热。");} var cruiseThrottle=needFuel?(frame.ScoopActive?.2:.55):.6; alignedSince=null;return new(motion,direction,cruiseThrottle,false,activeFsd,false,motionForecast.PeakPercent, needFuel?(frame.ScoopActive?"保持在排除区之外采集氢燃料;补足保守航段预算后继续。":"正在接近可采集燃料的区域,并持续核对热量与安全距离。"): "保持在排除区之外解除遮挡,绕行期间持续核对实际热量。"); } if(frame.NativeAllowsCharging==false) { alignedSince=null;return new("先脱离再充能",radial.Unit(),.8,false,frame.Fsd is FsdPhase.Charging or FsdPhase.Charged,false,frame.NativeFullChargePeak, frame.NativeFullChargePeak is {} nativePeak?$"原生热源和散热预测上界 {nativePeak:F1}%,先向外脱离高温区。":"原生热模型尚未就绪,先保持向外脱离,禁止高能跃迁充能。"); } if(frame.AlignmentRateLowerDegreesPerSecond<=0||!double.IsFinite(frame.AlignmentRateLowerDegreesPerSecond)||frame.ManoeuvreSecondsUpper is not {} manoeuvre||!double.IsFinite(manoeuvre)||manoeuvre<0||frame.PlannedMinimumStarDistance is not {} minimum||frame.PlannedMaximumStarDistance is not {} maximum)return Hold("缺少转向耗时或飞行距离包络,无法覆盖充满后等待对齐的产热。"); if(needFuel) { if(frame.RefuelSecondsUpper is not {} refuel||!double.IsFinite(refuel)||refuel<0)return Hold("补给耗时尚未确认,不能预测等待补给和对齐期间的总产热。"); manoeuvre=Math.Max(manoeuvre,refuel); } if(minimum>radial.Length||maximum0,FsdPhase.Charging=>frame.ChargeSecondsRemaining??double.NaN,_=>heatModel?.ChargeDurationUpperSeconds??double.NaN}; // FSD may charge in parallel with an avoidance manoeuvre. Its charged holding period still generates heat. var holdSeconds=Math.Max(0,manoeuvre+alignSeconds-charging)+.5; var forecast=ThermalPredictor.Predict(heatModel,frame.GameSha256,frame.LoadoutFingerprint,star.BodyId,heat,minimum,maximum,charging,holdSeconds,now); var active=frame.Fsd is FsdPhase.Charging or FsdPhase.Charged; if(!forecast.Known)return Hold(forecast.Reason); if(!forecast.AllowsCharging) { alignedSince=null; return new("先脱离再充能",radial.Unit(),.8,false,active,false,forecast.PeakPercent,forecast.Reason); } var fuelReady=fuel>=reserve&&fuel>=jumpFuel; // Align near completion, after clearance; do not abandon an active obstacle avoidance or required scoop. if(blocker is null&&!needFuel&&(!active||charging<=alignSeconds+1))direction=target.Unit(); if(frame.OutwardDepartureRequired&&blocker is null&&!needFuel&&charging>alignSeconds+1&&Vector3d.Dot(radial,frame.Forward)>0&&error>1) direction=frame.Forward.Unit(); var aligned=error<=1&&blocker is null&&!needFuel; if(aligned)alignedSince??=now;else alignedSince=null; var commit=frame.Fsd==FsdPhase.Charged&&alignedSince is {} since&&now-since>=TimeSpan.FromMilliseconds(300)&&fuelReady; var begin=frame.Fsd==FsdPhase.Idle&&frame.CanBeginCharge&&fuelReady&&(!frame.OutwardDepartureRequired||Vector3d.Dot(radial,frame.Forward)>=0); var throttle=commit||(begin||frame.Fsd==FsdPhase.Charging)&&blocker is null&&!needFuel?1:frame.Fsd==FsdPhase.Charged&&blocker is null&&!needFuel?0:needFuel ? .2 : .75; return new(commit?"允许跃迁":frame.Fsd==FsdPhase.Charged?$"{motion} · 充满等待":active?$"{motion} · 并行充能":begin?$"{motion} · 开始充能":motion,direction,throttle,begin,false,commit,forecast.PeakPercent, commit?"充能完成、目标已对齐、无遮挡且燃油与热量检查通过,节流阀升至 100%。":$"{forecast.Reason} 对齐误差 {error:F1}°;实际跃迁前再次核对。"); } private FlightDecision DecideAdaptive(FlightFrame frame,ShipThermalCalibration? model,DateTimeOffset now,StarEnvelope star,Vector3d radial,Vector3d target,StarEnvelope[] bodies,Func orbit) { var heat=frame.HeatPercent!.Value; var coast=ThermalPredictor.Predict(model is null?null:model with{ChargingGainUpperPerSecond=0,ChargedHoldGainUpperPerSecond=0}, frame.GameSha256,frame.LoadoutFingerprint,star.BodyId,heat,radial.Length,radial.Length,0,5,now); var adjustment=scoopThermal.Observe(frame,coast.Known?coast.PeakPercent:null); var needFuel=!adjustment.CanSkipFullTank&&frame.FuelMainFlightGeometry.Obscures(b,frame.Position,frame.TargetPosition)).MinBy(b=>(frame.Position-b.Centre).Length); FlightDecision Move(string state,Vector3d direction,string reason,double? peak=null)=>new(state,direction,1,false,active,false,peak,reason); if(adjustment.MovingOutward) { alignedSince=null;chargeRecovery|=active; var outward=radial.Unit(); var coolingDirection=orbit(Math.Max(star.SafeRadius*1.02,Math.Max(adjustment.Radius,radial.Length))); // A tiny change to the orbit radius can produce an almost tangent // aim. Give the turn a definite outward component while heating; // stop this correction on the first non-rising temperature sample. if(Vector3d.Dot(coolingDirection,outward)<.24) coolingDirection=(FlightGeometry.Perpendicular(outward,coolingDirection)+outward*.25).Unit(); var coolingThrottle=Vector3d.Dot(frame.Forward,outward)>.03&&Vector3d.AngleDegrees(frame.Forward,coolingDirection)<35?.4:0; return Move("小幅外移稳定温度",coolingDirection,"温度正在升高:先转向切线外侧;机头仍朝向恒星时保持零节流,停止升温后就近保持轨道。",coast.PeakPercent) with {Throttle=coolingThrottle,CoolingRecovery=true,UpDirection=FlightGeometry.Perpendicular(coolingDirection,star.Centre-frame.Position)}; } if(needFuel&&(!frame.ScoopPowered||!ScoopRules.CanRefuel(star.StarClass))) return new("补给不可用",null,0,false,active,false,null,frame.ScoopPowered?"当前恒星不能采集氢燃料,无法完成燃油预算。":"未检测到启用的油勺,无法补给燃油。"); if(adjustment.CanSkipFullTank&&(heat>=90||frame.NativeAllowsCharging!=true||frame.NativeFullChargePeak is not <=95)) { alignedSince=null; var coolingDirection=orbit(adjustment.MovingOutward?adjustment.Radius:Math.Max(adjustment.Radius,radial.Length)); return Move("就近稳定温度后继续航线",coolingDirection,"高温中断吸油;现有燃油已覆盖下一补给恒星。保持附近轨道,待充能热量检查通过后直接跃迁。",coast.PeakPercent) with {Throttle=Vector3d.Dot(frame.Forward,radial)<0?0:Math.Clamp((75-Vector3d.AngleDegrees(frame.Forward,coolingDirection))/90,0,.4),UpDirection=FlightGeometry.Perpendicular(coolingDirection,star.Centre-frame.Position)}; } if(needFuel||blocker is not null) { alignedSince=null; var forecast=ThermalPredictor.Predict(model is null?null:model with{ChargingGainUpperPerSecond=0,ChargedHoldGainUpperPerSecond=0}, frame.GameSha256,frame.LoadoutFingerprint,star.BodyId,heat,radial.Length,radial.Length,0,5,now); Vector3d orbitDirection; if(needFuel||blocker!.BodyId==star.BodyId) orbitDirection=orbit(adjustment.Interrupted?Math.Max(adjustment.Radius,star.SafeRadius*1.02):needFuel?frame.PreferredOrbitRadius??radial.Length:Math.Max(radial.Length,star.SafeRadius*1.02)); else orbitDirection=FlightGeometry.FastClearDirection(blocker,frame.Position,frame.TargetPosition,frame.Up); var power=frame.ScoopRate is {} rate&&frame.ScoopMaximumRate is >0?$"吸油功率 {rate/frame.ScoopMaximumRate:P0},":""; var thermalLimited=frame.ScoopFullRateRadius is {} fullRate&&frame.PreferredOrbitRadius>fullRate; var orbitError=Vector3d.AngleDegrees(frame.Forward,orbitDirection); var orbitThrottle=adjustment.Interrupted&&Vector3d.Dot(frame.Forward,radial)<0?0:Math.Clamp((75-orbitError)/45,0,1); return Move(adjustment.MovingOutward?"小幅外移稳定吸油温度":needFuel?"接近高功率吸油区并补满":"沿最短圆弧解除遮挡",orbitDirection, adjustment.MovingOutward?"小幅增加轨道半径;温度停止上升后立即停止外移。":needFuel?$"{power}{(thermalLimited?"受热量限制,已扩大环绕半径。":"按已计算的满功率半径接近。") }当前 {frame.FuelMain:F2} / {frame.FuelNeededToNextRefuel:F2} t。":"持续核对目标视线,解除遮挡且热量允许时立即充能。",forecast.PeakPercent) with {Throttle=adjustment.MovingOutward?Math.Min(.4,orbitThrottle):orbitThrottle,UpDirection=FlightGeometry.Perpendicular(orbitDirection,star.Centre-frame.Position)}; } var error=Vector3d.AngleDegrees(frame.Forward,target); // With no detour or refill to perform, cooling and heat-model sampling // are waiting tasks, not reasons to keep the arrival heading. Brake // translation and use that time to turn to the already visible target. if(frame.Fsd==FsdPhase.Cooldown) { alignedSince=null; return new("冷却期间立即对齐下一跳",target.Unit(),0,false,false,false,null, $"目标无遮挡、燃油就绪;立即转向,对齐误差 {error:F1}°,等待 FSD 冷却结束后充能。"); } var lower=frame.AlignmentRateLowerDegreesPerSecond; if(!double.IsFinite(lower)||lower<=0||model is null) return Move("对齐并同步充能热模型",target.Unit(),"立即对齐无遮挡的下一跳,同时等待连续产热和散热采样。") with{Throttle=0}; var charging=frame.Fsd switch{FsdPhase.Charged=>0,FsdPhase.Charging=>frame.ChargeSecondsRemaining??double.NaN,_=>model.ChargeDurationUpperSeconds}; var align=error/lower+.35; var inwardTarget=frame.OutwardDepartureRequired&&Vector3d.Dot(radial,target)<0; // A visible inward target can charge while departing tangentially/outward; // brake and align near completion so charging does not fly into the hot band. var hold=inwardTarget?align+.5:Math.Max(0,align-charging)+.5; var forecastCharge=ThermalPredictor.Predict(model,frame.GameSha256,frame.LoadoutFingerprint,star.BodyId,heat, frame.PlannedMinimumStarDistance??radial.Length,frame.PlannedMaximumStarDistance??radial.Length,charging,hold,now,100,5); if(frame.NativeAllowsCharging!=true||!forecastCharge.Known||!forecastCharge.AllowsCharging||inwardTarget&&heat>=90) { chargeRecovery|=active; alignedSince=null; return Move("散热离场并重新核对",Vector3d.Dot(radial,target)>=0?target.Unit():radial.Unit(),forecastCharge.Reason,forecastCharge.PeakPercent); } // A newly observed heat source can tighten the forecast after charge // starts. Once cancelled, require a real cooling margin rather than // repeatedly restarting at the same 95% boundary every few frames. if(chargeRecovery&&(active||forecastCharge.PeakPercent>90||frame.NativeFullChargePeak is not <=90)) return Move("恢复充能温度余量",Vector3d.Dot(radial,target)>=0?target.Unit():radial.Unit(),"充能取消后先恢复热量预测余量,避免反复启停。",forecastCharge.PeakPercent) with{CoolingRecovery=true}; chargeRecovery=false; var direction=target.Unit(); var begin=frame.Fsd==FsdPhase.Idle&&frame.CanBeginCharge; // Use a tolerance inside the verified one-degree native commit guard; // exact centre alignment is unnecessary. The original game still // decides jump eligibility after this application's interlock opens. var aligned=error<=.95&&(frame.AngularSpeedDegreesPerSecond??double.PositiveInfinity)<=2; if(aligned)alignedSince??=now;else alignedSince=null; var commit=frame.Fsd==FsdPhase.Charged&&alignedSince is {} since&&now-since>=TimeSpan.FromMilliseconds(80); var throttle=commit||begin?1:frame.Fsd==FsdPhase.Charged||inwardTarget&&active?0:1; return new(commit?"允许跃迁":begin?"立即充能并准备对齐":active?"充能并快速对齐":frame.Fsd==FsdPhase.Cooldown?"抵达后立即对齐":"快速对齐下一跳", direction,throttle,begin,false,commit,forecastCharge.PeakPercent, $"{forecastCharge.Reason} 对齐误差 {error:F1}°;目标无遮挡、燃油就绪。{(frame.Fsd==FsdPhase.Cooldown?"等待游戏自身的 FSD 冷却,同时转向。":"")}"); } }