using System.Globalization;
using System.Security.Cryptography;
using System.Text.Json;
using XFEEDToolBox.Core.Models;
namespace XFEEDToolBox.Core.Navigation;
/// <summary>Combines owned-ship native geometry/heat with actual Journal loadout, fuel and route observations.</summary>
public sealed class NativeFrameProjector(string build)
{
private string? fingerprint;
private long world;
private long primaryBody;
private double? orbitRadius;
private bool scoopAnchored;
private DateTimeOffset bandSearchAt;
private double? previousFuel;
private DateTimeOffset? previousFuelAt;
private double? scoopRate;
private ScoopBandTracker scoopBand=new();
private bool fillingTank;
private readonly ThermalDangerTracker thermalDanger=new();
private static Vector3d V(JsonElement e,string key){var a=e.GetProperty(key);return new(a[0].GetDouble(),a[1].GetDouble(),a[2].GetDouble());}
private static bool B(JsonElement e,string key)=>e.TryGetProperty(key,out var value)&&value.ValueKind==JsonValueKind.True;
public FlightObservation Project(JsonElement raw,PlayerState player,NavWaypoint? selected,double fuelReserve,DateTimeOffset now)
{
var fsd=raw.GetProperty("fsd");var geometry=raw.GetProperty("geometry");var thermal=raw.GetProperty("thermal");
if(!B(raw,"localPlayerShipVerified")||!B(fsd,"fresh")||raw.GetProperty("entityId").GetString()!=fsd.GetProperty("entityId").GetString())throw new FlightTelemetryUnavailableException("等待同一艘玩家飞船的姿态与 FSD 同步。");
var unified=B(geometry,"referenceFrameVerified");
if(B(raw,"adaptiveFlightControl")&&!unified)
throw new FlightTelemetryUnavailableException("当前恒星与行星的完整避障包络尚未同步"+
(geometry.TryGetProperty("referenceFailureStage",out var stage)?$"(定位阶段 {stage.GetInt32()})":"")+"。");
if(!unified&&geometry.GetProperty("bodyKind").GetInt32()!=1)
throw new InvalidOperationException("当前加载的旧版导航插件未提供空间站/行星参考系。请更新插件并重启游戏后再开始导航。");
if(!B(geometry,"fresh"))throw new FlightTelemetryUnavailableException("当前参考系的天体位置与排除区尚未同步。");
if(unified&&(!raw.TryGetProperty("referenceWorldAddress",out var reference)||reference.GetString()!=geometry.GetProperty("worldAddress").GetString()))
throw new FlightTelemetryUnavailableException("飞船参考系已切换,正在重新同步天体位置。");
if(!B(fsd,"targetValid"))throw new FlightTelemetryUnavailableException("等待游戏确认下一跳目标向量。");
if(geometry.GetProperty("bodyKind").GetInt32()!=1)throw new InvalidOperationException("请先离开行星附近,进入主恒星周围的超巡空间。");
// Cobra's SystemBodyAddress packs the body index in bits 55..63. The
// physics reference frame remains the complete body address; Journal
// SystemAddress contains only the low 55 bits (including binary stars).
var system=SystemAddressFromBody(ulong.Parse(geometry.GetProperty("worldAddress").GetString()!,CultureInfo.InvariantCulture));
var body=long.Parse(geometry.GetProperty("bodyAddress").GetString()!,CultureInfo.InvariantCulture);
var ship=player.Ships.FirstOrDefault(s=>s.ShipId==player.CurrentShipId);
if(ship?.ConfigurationAt is null||ship.ConfigurationChanged)throw new InvalidOperationException("等待当前飞船的完整装配快照。");
var currentFingerprint=Convert.ToHexStringLower(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{ship.ShipId,ship.Type,ship.UnladenMass,Modules=ship.Modules.Select(m=>new{m.Slot,m.Item,m.Enabled,m.Priority,m.Engineering})},ToolboxSettings.JsonOptions)));
if(fingerprint is not null&&fingerprint!=currentFingerprint)throw new InvalidOperationException("导航期间飞船装配发生变化,已停止控制。");
fingerprint=currentFingerprint;
var drive=NavigationPreviewBuilder.Drive(ship)??throw new InvalidOperationException("当前 FSD 的最大单跳用油参数尚未确认。");
var adaptive=B(raw,"adaptiveFlightControl");
var displayScale=B(raw,"heatNormalizationVerified")&&raw.TryGetProperty("heatDisplayScale",out var heatScale)?heatScale.GetDouble():1;
if(!double.IsFinite(displayScale)||displayScale is <.5 or >4)throw new InvalidDataException("游戏热量显示换算无效。");
if(adaptive&&!B(raw,"heatNormalizationVerified"))throw new FlightTelemetryUnavailableException("游戏插件尚未提供已核对的仪表热量换算,请更新插件并重启游戏。");
var fuel=player.Navigation.FuelAt>player.StatusAt?player.Navigation.MainFuel:player.Status?.FuelMain??player.Navigation.MainFuel;
var fuelAt=player.Navigation.FuelAt>player.StatusAt?player.Navigation.FuelAt:player.StatusAt??player.Navigation.FuelAt;
var budget=drive.MaxFuelPerJump+fuelReserve+.25;
if(player.Navigation.Route.Count>0)
{
var currentIndex=player.Navigation.Route.ToList().FindIndex(w=>w.SystemAddress==player.Navigation.CurrentSystemAddress);
if(currentIndex>=0)
{
var count=0;
foreach(var point in player.Navigation.Route.Skip(currentIndex+1))
{count++;if(point.Scoopable&&NavigationPreviewBuilder.HasScoop(ship))break;}
if(count>0)budget=drive.MaxFuelPerJump*count+fuelReserve+.25;
}
}
var position=V(unified?geometry:raw,"position");var radius=position.Length;var exclusion=geometry.GetProperty("exclusionRadius").GetDouble();
if(!position.Finite||!double.IsFinite(exclusion)||exclusion<=0)throw new InvalidDataException("原生米制恒星位置或排除区无效。");
var starType=geometry.GetProperty("starType").GetInt32();var starClass=starType is >=0 and <=6?"OBAFGKM"[starType].ToString():"Unknown";
var flags=player.Status?.Flags??0;var scoopActive=(flags&2048)!=0;
var nativeHeatWarning=adaptive&&raw.GetProperty("internalHeatPercent").GetDouble()>=100;
var thermalDangerExplained=adaptive&&thermalDanger.Observe(player.Status?.Flags,player.Navigation.ExternalThreat,nativeHeatWarning,radius<=exclusion*3);
var nativeScoop=geometry.TryGetProperty("scoop",out var scoop)&&B(scoop,"verified");
double? fullRateRadius=nativeScoop?scoop.GetProperty("fullRateRadius").GetDouble():null;
double? efficiency=nativeScoop?scoop.GetProperty("efficiency").GetDouble():null;
if(nativeScoop)
{
if(!double.IsFinite(fullRateRadius!.Value)||fullRateRadius<=exclusion*1.05||efficiency is not >=0 or >1.001)throw new InvalidDataException("游戏油勺的满功率包络无效。");
scoopActive=B(scoop,"active");
}
if(world!=system||primaryBody!=body){var keepRefilling=world==system&&fillingTank;world=system;primaryBody=body;orbitRadius=null;scoopAnchored=false;scoopRate=null;previousFuel=null;previousFuelAt=null;bandSearchAt=now;scoopBand=new();fillingTank=keepRefilling;}
var jumpFuel=drive.MaxFuelPerJump;var minimumFuelBudget=budget;double? maximumScoop=null;
if(adaptive&&fuel is {} actualFuel)
{
var calculated=NavigationFuelBudget.Calculate(player,ship,drive,actualFuel,fuelReserve);
jumpFuel=calculated.NextJump;budget=minimumFuelBudget=calculated.UntilRefuel;
if(!NavigationPreviewBuilder.HasScoop(ship))fillingTank=false;
else if(actualFuel<budget)fillingTank=true;
if(ship.FuelMain is {} capacity&&actualFuel>=capacity-.015)fillingTank=false;
if(fillingTank&&ship.FuelMain is {} full)budget=Math.Max(budget,full-.01);
maximumScoop=ScoopReference.MaximumRate(ship);
if(nativeScoop)maximumScoop=scoop.GetProperty("maximumRate").GetDouble();
if(fillingTank&&NavigationPreviewBuilder.HasScoop(ship)&&ScoopRules.CanRefuel(starClass)&&!nativeScoop)
throw new FlightTelemetryUnavailableException("等待油勺满功率包络同步;若持续不可用,请更新游戏插件并重启游戏。");
orbitRadius=scoopBand.Update(radius,exclusion,raw.GetProperty("heatPercent").GetDouble(),scoopActive,fuel,fuelAt,maximumScoop,fillingTank,now,fullRateRadius);
scoopRate=nativeScoop?(scoopActive?maximumScoop*efficiency:0):scoopBand.Rate;
}
else if(scoopActive)
{
if(!scoopAnchored){orbitRadius=radius*.999;scoopAnchored=true;}
bandSearchAt=now;
if(fuel is {} actual&&previousFuel is {} previous&&fuelAt is {} at&&previousFuelAt is {} before&&at>before&&actual>previous)
scoopRate=(actual-previous)/(at-before).TotalSeconds;
}
else if(!adaptive&&orbitRadius is null)orbitRadius=Math.Max(exclusion*1.25,radius*.9);
else if(!adaptive&&now-bandSearchAt>TimeSpan.FromSeconds(15)&&!scoopActive&&!scoopAnchored)
{orbitRadius=Math.Max(exclusion*1.25,(orbitRadius??radius*.9)-exclusion*.02);bandSearchAt=now;}
else if(!adaptive&&scoopAnchored&&fuel<budget&&now-bandSearchAt>TimeSpan.FromSeconds(1)&&raw.GetProperty("heatPercent").GetDouble()<86)
{
// Turning response causes a small outward tracking offset. If the actual scoop
// stops before the budget is filled, close that offset gradually using its live flag.
orbitRadius=Math.Max(exclusion*1.25,orbitRadius!.Value-exclusion*.002);bandSearchAt=now;
}
if(fuelAt>previousFuelAt||previousFuelAt is null){previousFuel=fuel;previousFuelAt=fuelAt;}
// The reference's per-jump maximum includes current engineering. Original game eligibility
// still decides actual range/fuel consumption; no reference estimate is written into game state.
var nativeState=fsd.GetProperty("state").GetInt32();var duration=fsd.GetProperty("duration").GetDouble();var chargeClock=fsd.GetProperty("clock").GetDouble();
var snapshotState=raw.TryGetProperty("rawFsdState",out var sourceState)?sourceState.GetInt32():nativeState;
var phase=nativeState switch{3 when chargeClock>=duration&&duration>0=>FsdPhase.Charged,3=>FsdPhase.Charging,4=>FsdPhase.Jumping,2=>FsdPhase.Idle,_=>FsdPhase.Cooldown};
// Physics and the post-FSD observer can straddle the very first idle
// tick. Steering is already available, but an original desired-input
// request also validates the physics snapshot. Wait for both to agree.
if(nativeState==2&&snapshotState!=2)phase=FsdPhase.Cooldown;
var star=new StarEnvelope(body,starClass,Vector3d.Zero,exclusion,nativeScoop?exclusion*1.05:null,nativeScoop?scoop.GetProperty("outerRadius").GetDouble():null);
var obstacles=new List<StarEnvelope>();
if(unified)
{
var nearby=geometry.GetProperty("nearbyBodies");
if(nearby.GetArrayLength() is <1 or >256)throw new InvalidDataException("当前参考系的天体列表无效。");
foreach(var value in nearby.EnumerateArray())
{
var id=unchecked((long)ulong.Parse(value.GetProperty("bodyAddress").GetString()!,CultureInfo.InvariantCulture));
var centre=V(value,"centre");var size=value.GetProperty("exclusionRadius").GetDouble();
if(!centre.Finite||!double.IsFinite(size)||size<=0)throw new InvalidDataException("当前参考系中存在无效天体包络。");
if(id!=body)obstacles.Add(new(id,"Unknown",centre,size,null,null));
else if(centre.Length>1||Math.Abs(size-exclusion)>1)throw new InvalidDataException("主恒星与天体列表不一致。");
}
if(!nearby.EnumerateArray().Any(v=>v.GetProperty("bodyAddress").GetString()==geometry.GetProperty("bodyAddress").GetString()))throw new InvalidDataException("当前参考系缺少主恒星。");
}
var target=position+V(fsd,"targetDirection")*fsd.GetProperty("targetDistance").GetDouble();
var frame=new FlightFrame
{
Sequence=raw.GetProperty("sequence").GetInt64(),ObservedAt=DateTimeOffset.FromUnixTimeMilliseconds(raw.GetProperty("observedAtUnixMilliseconds").GetInt64()),GameSha256=build,
LoadoutFingerprint=currentFingerprint,GeometryVerified=true,InSupercruise=(flags&16)!=0,PlayerOverride=B(raw,"playerOverride"),Position=position,Forward=V(unified?geometry:raw,"forward"),Up=V(unified?geometry:raw,"up"),TargetPosition=target,
SystemAddress=system,TargetSystemAddress=long.Parse(fsd.GetProperty("targetAddress").GetString()!,CultureInfo.InvariantCulture),SpeedMetresPerSecond=raw.GetProperty("speedMetresPerSecond").GetDouble(),SpeedFraction=fsd.GetProperty("speedFraction").GetDouble(),
ObservedThrottleCommand=fsd.TryGetProperty("throttle",out var throttle)?throttle.GetDouble():null,
EnginePips=player.Status?.Pips is {Count:3} pips?pips[1]:null,
HeatPercent=raw.GetProperty("heatPercent").GetDouble(),FuelMain=fuel,FuelRequiredForJump=jumpFuel,FuelNeededToNextRefuel=budget,MinimumFuelToNextRefuel=minimumFuelBudget,
AdaptiveFlightControl=adaptive,NativeHeatWarning=nativeHeatWarning,ThermalDangerExplained=thermalDangerExplained,RefuellingToFull=fillingTank,FuelTankCapacity=ship.FuelMain,ScoopRate=scoopRate,ScoopMaximumRate=maximumScoop,
ScoopFullRateRadius=fullRateRadius,ScoopEfficiency=efficiency,
AngularSpeedDegreesPerSecond=raw.TryGetProperty("angularSpeedDegreesPerSecond",out var angular)&&angular.ValueKind==JsonValueKind.Number?angular.GetDouble():null,
AngularVelocityDegrees=B(raw,"angularVelocityVerified")?V(raw,"angularVelocity"):null,
ScoopPowered=NavigationPreviewBuilder.HasScoop(ship),ScoopActive=scoopActive,PreferredOrbitRadius=orbitRadius,CurrentStar=star,Obstacles=obstacles,Fsd=phase,
CanBeginCharge=nativeState==2&&snapshotState==2&&(flags&65536)==0,JumpCommitInterlockVerified=true,ChargeSecondsRemaining=Math.Max(0,duration-chargeClock),AlignmentRateLowerDegreesPerSecond=4,
ManoeuvreSecondsUpper=0,RefuelSecondsUpper=scoopRate is >0&&fuel is {} f?Math.Min(120,Math.Max(0,budget-f)/scoopRate.Value+2):120,
PlannedMinimumStarDistance=radius*.995,PlannedMaximumStarDistance=radius+3e12,OutwardDepartureRequired=!unified||radius<exclusion*3&&(!adaptive||(flags&16)!=0||raw.GetProperty("speedMetresPerSecond").GetDouble()>1000),
// Respect both the native forecast and the actual-temperature cancellation
// guard. Legacy plugins retain their earlier, narrower thermal envelope.
NativeAllowsCharging=B(thermal,"allowsCharging")&&thermal.TryGetProperty("fullChargeAndHoldPeak",out var peak)&&peak.ValueKind==JsonValueKind.Number&&peak.GetDouble()<=(adaptive?95:89)&&raw.GetProperty("heatPercent").GetDouble()<(adaptive?97:87),
NativeFullChargePeak=thermal.TryGetProperty("fullChargeAndHoldPeak",out var nativePeak)&&nativePeak.ValueKind==JsonValueKind.Number?nativePeak.GetDouble():null
};
ShipThermalCalibration? model=null;
if(B(thermal,"fresh")&&B(thermal,"coolingActive")&&B(fsd,"driveParametersValid")&&B(fsd,"coolingConfigurationValid"))
{
var capacity=fsd.GetProperty("heatCapacity").GetDouble()*displayScale;var scale=thermal.GetProperty("coolingScale").GetDouble();
if(capacity<=0||!double.IsFinite(capacity)||scale<=0||!double.IsFinite(scale))throw new InvalidDataException("原生热容量或散热倍率无效。");
var input=thermal.GetProperty("idleInputUpper").GetDouble()*100/capacity;
var gain=(fsd.GetProperty("driveHeatBase").GetDouble()+fsd.GetProperty("driveHeatRamp").GetDouble())*100/capacity;
model=new(){GameSha256=build,LoadoutFingerprint=currentFingerprint,StarBodyId=body,Verified=true,ExpiresAt=now.AddSeconds(120),MinimumHeat=0,MaximumHeat=250,
ChargingGainUpperPerSecond=gain,ChargedHoldGainUpperPerSecond=gain,UncertaintyPercent=2,ChargeDurationUpperSeconds=fsd.GetProperty("driveChargeSeconds").GetDouble(),
// This rolling model is limited by the controller to an outward departure. Inbound
// scoop/search runs uncharged and is observed again before any charge is requested.
DistanceBands=[new(radius*.995,radius+3e12,input,0)],
CoolingCurve=new(fsd.GetProperty("coolingPassive").GetDouble()*scale*.99*100/capacity,fsd.GetProperty("coolingMaximum").GetDouble()*scale*.99*100/capacity,
fsd.GetProperty("coolingHeatLower").GetDouble()*100/displayScale,fsd.GetProperty("coolingHeatUpper").GetDouble()*100/displayScale,2),Evidence=thermal.GetProperty("evidence").GetString()!};
}
return new(frame,model);
}
public static long SystemAddressFromBody(ulong bodyAddress)=>checked((long)(bodyAddress&0x007FFFFFFFFFFFFFUL));
}
using System.Globalization;
using System.Security.Cryptography;
using System.Text.Json;
using XFEEDToolBox.Core.Models;
namespace XFEEDToolBox.Core.Navigation;
/// <summary>Combines owned-ship native geometry/heat with actual Journal loadout, fuel and route observations.</summary>
public sealed class NativeFrameProjector(string build)
{
private string? fingerprint;
private long world;
private long primaryBody;
private double? orbitRadius;
private bool scoopAnchored;
private DateTimeOffset bandSearchAt;
private double? previousFuel;
private DateTimeOffset? previousFuelAt;
private double? scoopRate;
private ScoopBandTracker scoopBand=new();
private bool fillingTank;
private readonly ThermalDangerTracker thermalDanger=new();
private static Vector3d V(JsonElement e,string key){var a=e.GetProperty(key);return new(a[0].GetDouble(),a[1].GetDouble(),a[2].GetDouble());}
private static bool B(JsonElement e,string key)=>e.TryGetProperty(key,out var value)&&value.ValueKind==JsonValueKind.True;
public FlightObservation Project(JsonElement raw,PlayerState player,NavWaypoint? selected,double fuelReserve,DateTimeOffset now)
{
var fsd=raw.GetProperty("fsd");var geometry=raw.GetProperty("geometry");var thermal=raw.GetProperty("thermal");
if(!B(raw,"localPlayerShipVerified")||!B(fsd,"fresh")||raw.GetProperty("entityId").GetString()!=fsd.GetProperty("entityId").GetString())throw new FlightTelemetryUnavailableException("等待同一艘玩家飞船的姿态与 FSD 同步。");
var unified=B(geometry,"referenceFrameVerified");
if(B(raw,"adaptiveFlightControl")&&!unified)
throw new FlightTelemetryUnavailableException("当前恒星与行星的完整避障包络尚未同步"+
(geometry.TryGetProperty("referenceFailureStage",out var stage)?$"(定位阶段 {stage.GetInt32()})":"")+"。");
if(!unified&&geometry.GetProperty("bodyKind").GetInt32()!=1)
throw new InvalidOperationException("当前加载的旧版导航插件未提供空间站/行星参考系。请更新插件并重启游戏后再开始导航。");
if(!B(geometry,"fresh"))throw new FlightTelemetryUnavailableException("当前参考系的天体位置与排除区尚未同步。");
if(unified&&(!raw.TryGetProperty("referenceWorldAddress",out var reference)||reference.GetString()!=geometry.GetProperty("worldAddress").GetString()))
throw new FlightTelemetryUnavailableException("飞船参考系已切换,正在重新同步天体位置。");
if(!B(fsd,"targetValid"))throw new FlightTelemetryUnavailableException("等待游戏确认下一跳目标向量。");
if(geometry.GetProperty("bodyKind").GetInt32()!=1)throw new InvalidOperationException("请先离开行星附近,进入主恒星周围的超巡空间。");
// Cobra's SystemBodyAddress packs the body index in bits 55..63. The
// physics reference frame remains the complete body address; Journal
// SystemAddress contains only the low 55 bits (including binary stars).
var system=SystemAddressFromBody(ulong.Parse(geometry.GetProperty("worldAddress").GetString()!,CultureInfo.InvariantCulture));
var body=long.Parse(geometry.GetProperty("bodyAddress").GetString()!,CultureInfo.InvariantCulture);
var ship=player.Ships.FirstOrDefault(s=>s.ShipId==player.CurrentShipId);
if(ship?.ConfigurationAt is null||ship.ConfigurationChanged)throw new InvalidOperationException("等待当前飞船的完整装配快照。");
var currentFingerprint=Convert.ToHexStringLower(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{ship.ShipId,ship.Type,ship.UnladenMass,Modules=ship.Modules.Select(m=>new{m.Slot,m.Item,m.Enabled,m.Priority,m.Engineering})},ToolboxSettings.JsonOptions)));
if(fingerprint is not null&&fingerprint!=currentFingerprint)throw new InvalidOperationException("导航期间飞船装配发生变化,已停止控制。");
fingerprint=currentFingerprint;
var drive=NavigationPreviewBuilder.Drive(ship)??throw new InvalidOperationException("当前 FSD 的最大单跳用油参数尚未确认。");
var adaptive=B(raw,"adaptiveFlightControl");
var displayScale=B(raw,"heatNormalizationVerified")&&raw.TryGetProperty("heatDisplayScale",out var heatScale)?heatScale.GetDouble():1;
if(!double.IsFinite(displayScale)||displayScale is <.5 or >4)throw new InvalidDataException("游戏热量显示换算无效。");
if(adaptive&&!B(raw,"heatNormalizationVerified"))throw new FlightTelemetryUnavailableException("游戏插件尚未提供已核对的仪表热量换算,请更新插件并重启游戏。");
var fuel=player.Navigation.FuelAt>player.StatusAt?player.Navigation.MainFuel:player.Status?.FuelMain??player.Navigation.MainFuel;
var fuelAt=player.Navigation.FuelAt>player.StatusAt?player.Navigation.FuelAt:player.StatusAt??player.Navigation.FuelAt;
var budget=drive.MaxFuelPerJump+fuelReserve+.25;
if(player.Navigation.Route.Count>0)
{
var currentIndex=player.Navigation.Route.ToList().FindIndex(w=>w.SystemAddress==player.Navigation.CurrentSystemAddress);
if(currentIndex>=0)
{
var count=0;
foreach(var point in player.Navigation.Route.Skip(currentIndex+1))
{count++;if(point.Scoopable&&NavigationPreviewBuilder.HasScoop(ship))break;}
if(count>0)budget=drive.MaxFuelPerJump*count+fuelReserve+.25;
}
}
var position=V(unified?geometry:raw,"position");var radius=position.Length;var exclusion=geometry.GetProperty("exclusionRadius").GetDouble();
if(!position.Finite||!double.IsFinite(exclusion)||exclusion<=0)throw new InvalidDataException("原生米制恒星位置或排除区无效。");
var starType=geometry.GetProperty("starType").GetInt32();var starClass=starType is >=0 and <=6?"OBAFGKM"[starType].ToString():"Unknown";
var flags=player.Status?.Flags??0;var scoopActive=(flags&2048)!=0;
var nativeHeatWarning=adaptive&&raw.GetProperty("internalHeatPercent").GetDouble()>=100;
var thermalDangerExplained=adaptive&&thermalDanger.Observe(player.Status?.Flags,player.Navigation.ExternalThreat,nativeHeatWarning,radius<=exclusion*3);
var nativeScoop=geometry.TryGetProperty("scoop",out var scoop)&&B(scoop,"verified");
double? fullRateRadius=nativeScoop?scoop.GetProperty("fullRateRadius").GetDouble():null;
double? efficiency=nativeScoop?scoop.GetProperty("efficiency").GetDouble():null;
if(nativeScoop)
{
if(!double.IsFinite(fullRateRadius!.Value)||fullRateRadius<=exclusion*1.05||efficiency is not >=0 or >1.001)throw new InvalidDataException("游戏油勺的满功率包络无效。");
scoopActive=B(scoop,"active");
}
if(world!=system||primaryBody!=body){var keepRefilling=world==system&&fillingTank;world=system;primaryBody=body;orbitRadius=null;scoopAnchored=false;scoopRate=null;previousFuel=null;previousFuelAt=null;bandSearchAt=now;scoopBand=new();fillingTank=keepRefilling;}
var jumpFuel=drive.MaxFuelPerJump;var minimumFuelBudget=budget;double? maximumScoop=null;
if(adaptive&&fuel is {} actualFuel)
{
var calculated=NavigationFuelBudget.Calculate(player,ship,drive,actualFuel,fuelReserve);
jumpFuel=calculated.NextJump;budget=minimumFuelBudget=calculated.UntilRefuel;
if(!NavigationPreviewBuilder.HasScoop(ship))fillingTank=false;
else if(actualFuel<budget)fillingTank=true;
if(ship.FuelMain is {} capacity&&actualFuel>=capacity-.015)fillingTank=false;
if(fillingTank&&ship.FuelMain is {} full)budget=Math.Max(budget,full-.01);
maximumScoop=ScoopReference.MaximumRate(ship);
if(nativeScoop)maximumScoop=scoop.GetProperty("maximumRate").GetDouble();
if(fillingTank&&NavigationPreviewBuilder.HasScoop(ship)&&ScoopRules.CanRefuel(starClass)&&!nativeScoop)
throw new FlightTelemetryUnavailableException("等待油勺满功率包络同步;若持续不可用,请更新游戏插件并重启游戏。");
orbitRadius=scoopBand.Update(radius,exclusion,raw.GetProperty("heatPercent").GetDouble(),scoopActive,fuel,fuelAt,maximumScoop,fillingTank,now,fullRateRadius);
scoopRate=nativeScoop?(scoopActive?maximumScoop*efficiency:0):scoopBand.Rate;
}
else if(scoopActive)
{
if(!scoopAnchored){orbitRadius=radius*.999;scoopAnchored=true;}
bandSearchAt=now;
if(fuel is {} actual&&previousFuel is {} previous&&fuelAt is {} at&&previousFuelAt is {} before&&at>before&&actual>previous)
scoopRate=(actual-previous)/(at-before).TotalSeconds;
}
else if(!adaptive&&orbitRadius is null)orbitRadius=Math.Max(exclusion*1.25,radius*.9);
else if(!adaptive&&now-bandSearchAt>TimeSpan.FromSeconds(15)&&!scoopActive&&!scoopAnchored)
{orbitRadius=Math.Max(exclusion*1.25,(orbitRadius??radius*.9)-exclusion*.02);bandSearchAt=now;}
else if(!adaptive&&scoopAnchored&&fuel<budget&&now-bandSearchAt>TimeSpan.FromSeconds(1)&&raw.GetProperty("heatPercent").GetDouble()<86)
{
// Turning response causes a small outward tracking offset. If the actual scoop
// stops before the budget is filled, close that offset gradually using its live flag.
orbitRadius=Math.Max(exclusion*1.25,orbitRadius!.Value-exclusion*.002);bandSearchAt=now;
}
if(fuelAt>previousFuelAt||previousFuelAt is null){previousFuel=fuel;previousFuelAt=fuelAt;}
// The reference's per-jump maximum includes current engineering. Original game eligibility
// still decides actual range/fuel consumption; no reference estimate is written into game state.
var nativeState=fsd.GetProperty("state").GetInt32();var duration=fsd.GetProperty("duration").GetDouble();var chargeClock=fsd.GetProperty("clock").GetDouble();
var snapshotState=raw.TryGetProperty("rawFsdState",out var sourceState)?sourceState.GetInt32():nativeState;
var phase=nativeState switch{3 when chargeClock>=duration&&duration>0=>FsdPhase.Charged,3=>FsdPhase.Charging,4=>FsdPhase.Jumping,2=>FsdPhase.Idle,_=>FsdPhase.Cooldown};
// Physics and the post-FSD observer can straddle the very first idle
// tick. Steering is already available, but an original desired-input
// request also validates the physics snapshot. Wait for both to agree.
if(nativeState==2&&snapshotState!=2)phase=FsdPhase.Cooldown;
var star=new StarEnvelope(body,starClass,Vector3d.Zero,exclusion,nativeScoop?exclusion*1.05:null,nativeScoop?scoop.GetProperty("outerRadius").GetDouble():null);
var obstacles=new List<StarEnvelope>();
if(unified)
{
var nearby=geometry.GetProperty("nearbyBodies");
if(nearby.GetArrayLength() is <1 or >256)throw new InvalidDataException("当前参考系的天体列表无效。");
foreach(var value in nearby.EnumerateArray())
{
var id=unchecked((long)ulong.Parse(value.GetProperty("bodyAddress").GetString()!,CultureInfo.InvariantCulture));
var centre=V(value,"centre");var size=value.GetProperty("exclusionRadius").GetDouble();
if(!centre.Finite||!double.IsFinite(size)||size<=0)throw new InvalidDataException("当前参考系中存在无效天体包络。");
if(id!=body)obstacles.Add(new(id,"Unknown",centre,size,null,null));
else if(centre.Length>1||Math.Abs(size-exclusion)>1)throw new InvalidDataException("主恒星与天体列表不一致。");
}
if(!nearby.EnumerateArray().Any(v=>v.GetProperty("bodyAddress").GetString()==geometry.GetProperty("bodyAddress").GetString()))throw new InvalidDataException("当前参考系缺少主恒星。");
}
var target=position+V(fsd,"targetDirection")*fsd.GetProperty("targetDistance").GetDouble();
var frame=new FlightFrame
{
Sequence=raw.GetProperty("sequence").GetInt64(),ObservedAt=DateTimeOffset.FromUnixTimeMilliseconds(raw.GetProperty("observedAtUnixMilliseconds").GetInt64()),GameSha256=build,
LoadoutFingerprint=currentFingerprint,GeometryVerified=true,InSupercruise=(flags&16)!=0,PlayerOverride=B(raw,"playerOverride"),Position=position,Forward=V(unified?geometry:raw,"forward"),Up=V(unified?geometry:raw,"up"),TargetPosition=target,
SystemAddress=system,TargetSystemAddress=long.Parse(fsd.GetProperty("targetAddress").GetString()!,CultureInfo.InvariantCulture),SpeedMetresPerSecond=raw.GetProperty("speedMetresPerSecond").GetDouble(),SpeedFraction=fsd.GetProperty("speedFraction").GetDouble(),
ObservedThrottleCommand=fsd.TryGetProperty("throttle",out var throttle)?throttle.GetDouble():null,
EnginePips=player.Status?.Pips is {Count:3} pips?pips[1]:null,
HeatPercent=raw.GetProperty("heatPercent").GetDouble(),FuelMain=fuel,FuelRequiredForJump=jumpFuel,FuelNeededToNextRefuel=budget,MinimumFuelToNextRefuel=minimumFuelBudget,
AdaptiveFlightControl=adaptive,NativeHeatWarning=nativeHeatWarning,ThermalDangerExplained=thermalDangerExplained,RefuellingToFull=fillingTank,FuelTankCapacity=ship.FuelMain,ScoopRate=scoopRate,ScoopMaximumRate=maximumScoop,
ScoopFullRateRadius=fullRateRadius,ScoopEfficiency=efficiency,
AngularSpeedDegreesPerSecond=raw.TryGetProperty("angularSpeedDegreesPerSecond",out var angular)&&angular.ValueKind==JsonValueKind.Number?angular.GetDouble():null,
AngularVelocityDegrees=B(raw,"angularVelocityVerified")?V(raw,"angularVelocity"):null,
ScoopPowered=NavigationPreviewBuilder.HasScoop(ship),ScoopActive=scoopActive,PreferredOrbitRadius=orbitRadius,CurrentStar=star,Obstacles=obstacles,Fsd=phase,
CanBeginCharge=nativeState==2&&snapshotState==2&&(flags&65536)==0,JumpCommitInterlockVerified=true,ChargeSecondsRemaining=Math.Max(0,duration-chargeClock),AlignmentRateLowerDegreesPerSecond=4,
ManoeuvreSecondsUpper=0,RefuelSecondsUpper=scoopRate is >0&&fuel is {} f?Math.Min(120,Math.Max(0,budget-f)/scoopRate.Value+2):120,
PlannedMinimumStarDistance=radius*.995,PlannedMaximumStarDistance=radius+3e12,OutwardDepartureRequired=!unified||radius<exclusion*3&&(!adaptive||(flags&16)!=0||raw.GetProperty("speedMetresPerSecond").GetDouble()>1000),
// Respect both the native forecast and the actual-temperature cancellation
// guard. Legacy plugins retain their earlier, narrower thermal envelope.
NativeAllowsCharging=B(thermal,"allowsCharging")&&thermal.TryGetProperty("fullChargeAndHoldPeak",out var peak)&&peak.ValueKind==JsonValueKind.Number&&peak.GetDouble()<=(adaptive?95:89)&&raw.GetProperty("heatPercent").GetDouble()<(adaptive?97:87),
NativeFullChargePeak=thermal.TryGetProperty("fullChargeAndHoldPeak",out var nativePeak)&&nativePeak.ValueKind==JsonValueKind.Number?nativePeak.GetDouble():null
};
ShipThermalCalibration? model=null;
if(B(thermal,"fresh")&&B(thermal,"coolingActive")&&B(fsd,"driveParametersValid")&&B(fsd,"coolingConfigurationValid"))
{
var capacity=fsd.GetProperty("heatCapacity").GetDouble()*displayScale;var scale=thermal.GetProperty("coolingScale").GetDouble();
if(capacity<=0||!double.IsFinite(capacity)||scale<=0||!double.IsFinite(scale))throw new InvalidDataException("原生热容量或散热倍率无效。");
var input=thermal.GetProperty("idleInputUpper").GetDouble()*100/capacity;
var gain=(fsd.GetProperty("driveHeatBase").GetDouble()+fsd.GetProperty("driveHeatRamp").GetDouble())*100/capacity;
model=new(){GameSha256=build,LoadoutFingerprint=currentFingerprint,StarBodyId=body,Verified=true,ExpiresAt=now.AddSeconds(120),MinimumHeat=0,MaximumHeat=250,
ChargingGainUpperPerSecond=gain,ChargedHoldGainUpperPerSecond=gain,UncertaintyPercent=2,ChargeDurationUpperSeconds=fsd.GetProperty("driveChargeSeconds").GetDouble(),
// This rolling model is limited by the controller to an outward departure. Inbound
// scoop/search runs uncharged and is observed again before any charge is requested.
DistanceBands=[new(radius*.995,radius+3e12,input,0)],
CoolingCurve=new(fsd.GetProperty("coolingPassive").GetDouble()*scale*.99*100/capacity,fsd.GetProperty("coolingMaximum").GetDouble()*scale*.99*100/capacity,
fsd.GetProperty("coolingHeatLower").GetDouble()*100/displayScale,fsd.GetProperty("coolingHeatUpper").GetDouble()*100/displayScale,2),Evidence=thermal.GetProperty("evidence").GetString()!};
}
return new(frame,model);
}
public static long SystemAddressFromBody(ulong bodyAddress)=>checked((long)(bodyAddress&0x007FFFFFFFFFFFFFUL));
}