#if PLUGIN_CRUISE_OBSERVATION
using System.IO.Pipes;
using System.Text;
namespace XFEEDToolBox.Plugin;
// Only observes the original SCO update. This module cannot start, stop,
// renew or redirect an overcharge, alter a flight axis or select a target.
internal static class CruiseObservationRuntime
{
private const nuint Update=0x2EADB40;
private const string Service="CruiseObservation0514c";
private static readonly object sync=new();
private static bool started,enabled;
private static nuint image,original;
private static uint thread;
private static ulong entity,world,watchAt,calls,matches,errors;
private static ulong lastSampleTick;
private static Navigation.RecoveryCruiseBinding? binding;
private static string? issue;
private static JsonObject? latest;
private static async Task<JsonElement> NativeReadAsync(string operation)
{
using var timeout=new CancellationTokenSource(TimeSpan.FromMilliseconds(150));
using var pipe=new NamedPipeClientStream(".",$"XFEEDToolBox.Navigation.{ProcessId}",PipeDirection.InOut,PipeOptions.Asynchronous);
await pipe.ConnectAsync(timeout.Token);await pipe.WriteAsync(Encoding.UTF8.GetBytes(Obj(("op",operation)).ToJsonString()+"\n"),timeout.Token);await pipe.FlushAsync(timeout.Token);
var bytes=new byte[65536];var count=0;
while(count<bytes.Length)
{var length=await pipe.ReadAsync(bytes.AsMemory(count),timeout.Token);if(length==0)break;count+=length;if(bytes[count-1]=='\n')break;}
if(count is 0 or 65536)throw new IOException("Invalid original cruise observation response");
using var parsed=JsonDocument.Parse(bytes.AsMemory(0,count));var response=parsed.RootElement;
if(!response.GetProperty("ok").GetBoolean())throw new InvalidOperationException(response.GetProperty("error").GetString());
return response.GetProperty("result").Clone();
}
private static bool Fresh(ulong at,ulong now)=>at<=now&&now-at<=300;
private static JsonObject Describe()
{
lock(sync)
{
var observed=latest?["observedAtUnixMilliseconds"]?.GetValue<ulong>()??0;var fresh=observed!=0&&Fresh(observed,Utc());
return Obj(("schema",1),("service",Service),("processId",ProcessId),("gameSha256",GameHash),("enabled",enabled),("owningThread",thread),
("watchEntityId",entity.ToString()),("watchReferenceWorld",world.ToString()),("watchInterface",binding?.component.ToString("x")),("watchAtUnixMilliseconds",watchAt),("calls",calls),("matches",matches),("errors",errors),("issue",issue),
("sampleReady",fresh),("sample",latest?.DeepClone()),("overchargeControl",false),("gameInputsSent",0),("overchargeCommandsSent",0));
}
}
private static JsonNode Handle(JsonElement request)
{
var operation=request.Str("op");
if(operation is "describe" or "read")return Describe();
if(operation=="watch")
{
var frame=NativeReadAsync("read").GetAwaiter().GetResult();var health=NativeReadAsync("health.read").GetAwaiter().GetResult();var now=Utc();
if(!frame.GetProperty("inGame").GetBoolean()||!frame.GetProperty("localPlayerShipVerified").GetBoolean()||!health.GetProperty("localPlayerShipVerified").GetBoolean()
||!Fresh(frame.GetProperty("observedAtUnixMilliseconds").GetUInt64(),now)||!Fresh(health.GetProperty("observedAtUnixMilliseconds").GetUInt64(),now)
||!health.GetProperty("shipHealth").GetProperty("verified").GetBoolean()||frame.GetProperty("entityId").GetString()!=health.GetProperty("entityId").GetString())
throw new InvalidOperationException("Current original main-ship identity is unavailable");
var next=ulong.Parse(frame.GetProperty("entityId").GetString()!);var reference=ulong.Parse(frame.GetProperty("referenceWorldAddress").GetString()!);
var nextBinding=Navigation.BindRecoveryCruise(next);
lock(sync){if(entity!=next||world!=reference||binding?.component!=nextBinding.component)latest=null;entity=next;world=reference;binding=nextBinding;watchAt=now;
issue=nextBinding.component==0?"current-entity-has-no-SCO-interface":"awaiting-current-main-ship-SCO-update";}
return Describe();
}
if(operation=="deactivate")
{
lock(sync)enabled=false;HookDisable(image+Update);return Describe();
}
throw new InvalidOperationException("This read-only module cannot execute cruise commands");
}
[UnmanagedCallersOnly]private static unsafe ulong Observe(nuint sco,float delta,double time)
{
ulong result;try{result=Call(original,(ulong)sco,F32(delta),F64(time));}catch{return 0;}
try
{
ulong wanted,reference;uint expected;Navigation.RecoveryCruiseBinding? selected;
lock(sync){calls++;if(!enabled)return result;wanted=entity;reference=world;expected=thread;selected=binding;}
if(wanted==0||selected==null||selected.component!=sco||GetCurrentThreadId()!=expected)return result;
var now=GetTickCount64();if(now-lastSampleTick<20)return result;lastSampleTick=now;
var observed=Navigation.ObserveRecoveryCruise(selected,sco);if(observed==null)return result;
if(observed["referenceWorldAddress"]!.GetValue<string>()!=reference.ToString())return result;
lock(sync){if(enabled&&entity==wanted&&world==reference){latest=observed;matches++;issue=null;}}
}
catch(Exception error){lock(sync){errors++;issue=error.GetType().Name+": "+error.Message;}}
return result;
}
internal static unsafe uint Start(nuint owningThread)
{
lock(sync)
{
if(started)return thread==owningThread?1u:0u;
if(owningThread is 0 or >uint.MaxValue||ImageHash(ModulePath())!=GameHash)return 0;
image=ImageBase;thread=(uint)owningThread;Navigation.ConfigureRecoveryReadOnlyImage();
if(!ReadBytes(image+Update,10).AsSpan().SequenceEqual(new byte[]{0x48,0x89,0x5C,0x24,0x18,0x57,0x48,0x83,0xEC,0x40}))return 0;
var status=HookInitialize();if(status is not(0 or 1))return 0;
if(HookCreate(image+Update,(nuint)(delegate* unmanaged<nuint,float,double,ulong>)&Observe,out original)!=0)return 0;
if(!Pin((nuint)(delegate* unmanaged<nuint,float,double,ulong>)&Observe)||HookEnable(image+Update)!=0)return 0;
started=enabled=true;PipeServer.StartJson(Service,32768,Handle);return 1;
}
}
internal static uint SelfTest()
{
if(started||ImageHash(ModulePath())==GameHash)return 0;uint result=0;
if(Fresh(100,400)&&!Fresh(100,401)&&!Fresh(100,99))result|=1;
var value=Describe();if(!value["overchargeControl"]!.GetValue<bool>()&&value["gameInputsSent"]!.GetValue<int>()==0)result|=2;
if(!value["sampleReady"]!.GetValue<bool>())result|=4;
foreach(var op in new[]{"activate","cruise.overcharge.set","input.set","local.select"})
{using var request=JsonDocument.Parse(Obj(("op",op)).ToJsonString());try{Handle(request.RootElement);return result;}catch(InvalidOperationException){}}
result|=8;
if(XFEEDToolBox.Core.Navigation.OriginalCurveBounds.TryBound([new(0,0,1,-12),new(1,0,0,-12)],2,0,1,out var bounds)&&bounds.Maximum>=1.5&&bounds.Maximum<1.501)result|=16;
if(!XFEEDToolBox.Core.Navigation.OriginalCurveBounds.TryBound([],2,0,1,out _))result|=32;
if(!XFEEDToolBox.Core.Navigation.OriginalCurveBounds.TryBound([new(0,double.NaN,1,0)],2,0,1,out _))result|=64;
if(value["overchargeCommandsSent"]!.GetValue<int>()==0&&value["service"]!.GetValue<string>()==Service)result|=128;
return result;
}
}
internal static class CruiseObservationExports
{
[UnmanagedCallersOnly(EntryPoint="XFEInteractionStart")]internal static uint Start(nuint thread){try{return CruiseObservationRuntime.Start(thread);}catch{return 0;}}
[UnmanagedCallersOnly(EntryPoint="XFECruiseObservationSelfTest")]internal static uint SelfTest(){try{return CruiseObservationRuntime.SelfTest();}catch{return 0;}}
}
#endif
#if PLUGIN_CRUISE_OBSERVATION
using System.IO.Pipes;
using System.Text;
namespace XFEEDToolBox.Plugin;
// Only observes the original SCO update. This module cannot start, stop,
// renew or redirect an overcharge, alter a flight axis or select a target.
internal static class CruiseObservationRuntime
{
private const nuint Update=0x2EADB40;
private const string Service="CruiseObservation0514c";
private static readonly object sync=new();
private static bool started,enabled;
private static nuint image,original;
private static uint thread;
private static ulong entity,world,watchAt,calls,matches,errors;
private static ulong lastSampleTick;
private static Navigation.RecoveryCruiseBinding? binding;
private static string? issue;
private static JsonObject? latest;
private static async Task<JsonElement> NativeReadAsync(string operation)
{
using var timeout=new CancellationTokenSource(TimeSpan.FromMilliseconds(150));
using var pipe=new NamedPipeClientStream(".",$"XFEEDToolBox.Navigation.{ProcessId}",PipeDirection.InOut,PipeOptions.Asynchronous);
await pipe.ConnectAsync(timeout.Token);await pipe.WriteAsync(Encoding.UTF8.GetBytes(Obj(("op",operation)).ToJsonString()+"\n"),timeout.Token);await pipe.FlushAsync(timeout.Token);
var bytes=new byte[65536];var count=0;
while(count<bytes.Length)
{var length=await pipe.ReadAsync(bytes.AsMemory(count),timeout.Token);if(length==0)break;count+=length;if(bytes[count-1]=='\n')break;}
if(count is 0 or 65536)throw new IOException("Invalid original cruise observation response");
using var parsed=JsonDocument.Parse(bytes.AsMemory(0,count));var response=parsed.RootElement;
if(!response.GetProperty("ok").GetBoolean())throw new InvalidOperationException(response.GetProperty("error").GetString());
return response.GetProperty("result").Clone();
}
private static bool Fresh(ulong at,ulong now)=>at<=now&&now-at<=300;
private static JsonObject Describe()
{
lock(sync)
{
var observed=latest?["observedAtUnixMilliseconds"]?.GetValue<ulong>()??0;var fresh=observed!=0&&Fresh(observed,Utc());
return Obj(("schema",1),("service",Service),("processId",ProcessId),("gameSha256",GameHash),("enabled",enabled),("owningThread",thread),
("watchEntityId",entity.ToString()),("watchReferenceWorld",world.ToString()),("watchInterface",binding?.component.ToString("x")),("watchAtUnixMilliseconds",watchAt),("calls",calls),("matches",matches),("errors",errors),("issue",issue),
("sampleReady",fresh),("sample",latest?.DeepClone()),("overchargeControl",false),("gameInputsSent",0),("overchargeCommandsSent",0));
}
}
private static JsonNode Handle(JsonElement request)
{
var operation=request.Str("op");
if(operation is "describe" or "read")return Describe();
if(operation=="watch")
{
var frame=NativeReadAsync("read").GetAwaiter().GetResult();var health=NativeReadAsync("health.read").GetAwaiter().GetResult();var now=Utc();
if(!frame.GetProperty("inGame").GetBoolean()||!frame.GetProperty("localPlayerShipVerified").GetBoolean()||!health.GetProperty("localPlayerShipVerified").GetBoolean()
||!Fresh(frame.GetProperty("observedAtUnixMilliseconds").GetUInt64(),now)||!Fresh(health.GetProperty("observedAtUnixMilliseconds").GetUInt64(),now)
||!health.GetProperty("shipHealth").GetProperty("verified").GetBoolean()||frame.GetProperty("entityId").GetString()!=health.GetProperty("entityId").GetString())
throw new InvalidOperationException("Current original main-ship identity is unavailable");
var next=ulong.Parse(frame.GetProperty("entityId").GetString()!);var reference=ulong.Parse(frame.GetProperty("referenceWorldAddress").GetString()!);
var nextBinding=Navigation.BindRecoveryCruise(next);
lock(sync){if(entity!=next||world!=reference||binding?.component!=nextBinding.component)latest=null;entity=next;world=reference;binding=nextBinding;watchAt=now;
issue=nextBinding.component==0?"current-entity-has-no-SCO-interface":"awaiting-current-main-ship-SCO-update";}
return Describe();
}
if(operation=="deactivate")
{
lock(sync)enabled=false;HookDisable(image+Update);return Describe();
}
throw new InvalidOperationException("This read-only module cannot execute cruise commands");
}
[UnmanagedCallersOnly]private static unsafe ulong Observe(nuint sco,float delta,double time)
{
ulong result;try{result=Call(original,(ulong)sco,F32(delta),F64(time));}catch{return 0;}
try
{
ulong wanted,reference;uint expected;Navigation.RecoveryCruiseBinding? selected;
lock(sync){calls++;if(!enabled)return result;wanted=entity;reference=world;expected=thread;selected=binding;}
if(wanted==0||selected==null||selected.component!=sco||GetCurrentThreadId()!=expected)return result;
var now=GetTickCount64();if(now-lastSampleTick<20)return result;lastSampleTick=now;
var observed=Navigation.ObserveRecoveryCruise(selected,sco);if(observed==null)return result;
if(observed["referenceWorldAddress"]!.GetValue<string>()!=reference.ToString())return result;
lock(sync){if(enabled&&entity==wanted&&world==reference){latest=observed;matches++;issue=null;}}
}
catch(Exception error){lock(sync){errors++;issue=error.GetType().Name+": "+error.Message;}}
return result;
}
internal static unsafe uint Start(nuint owningThread)
{
lock(sync)
{
if(started)return thread==owningThread?1u:0u;
if(owningThread is 0 or >uint.MaxValue||ImageHash(ModulePath())!=GameHash)return 0;
image=ImageBase;thread=(uint)owningThread;Navigation.ConfigureRecoveryReadOnlyImage();
if(!ReadBytes(image+Update,10).AsSpan().SequenceEqual(new byte[]{0x48,0x89,0x5C,0x24,0x18,0x57,0x48,0x83,0xEC,0x40}))return 0;
var status=HookInitialize();if(status is not(0 or 1))return 0;
if(HookCreate(image+Update,(nuint)(delegate* unmanaged<nuint,float,double,ulong>)&Observe,out original)!=0)return 0;
if(!Pin((nuint)(delegate* unmanaged<nuint,float,double,ulong>)&Observe)||HookEnable(image+Update)!=0)return 0;
started=enabled=true;PipeServer.StartJson(Service,32768,Handle);return 1;
}
}
internal static uint SelfTest()
{
if(started||ImageHash(ModulePath())==GameHash)return 0;uint result=0;
if(Fresh(100,400)&&!Fresh(100,401)&&!Fresh(100,99))result|=1;
var value=Describe();if(!value["overchargeControl"]!.GetValue<bool>()&&value["gameInputsSent"]!.GetValue<int>()==0)result|=2;
if(!value["sampleReady"]!.GetValue<bool>())result|=4;
foreach(var op in new[]{"activate","cruise.overcharge.set","input.set","local.select"})
{using var request=JsonDocument.Parse(Obj(("op",op)).ToJsonString());try{Handle(request.RootElement);return result;}catch(InvalidOperationException){}}
result|=8;
if(XFEEDToolBox.Core.Navigation.OriginalCurveBounds.TryBound([new(0,0,1,-12),new(1,0,0,-12)],2,0,1,out var bounds)&&bounds.Maximum>=1.5&&bounds.Maximum<1.501)result|=16;
if(!XFEEDToolBox.Core.Navigation.OriginalCurveBounds.TryBound([],2,0,1,out _))result|=32;
if(!XFEEDToolBox.Core.Navigation.OriginalCurveBounds.TryBound([new(0,double.NaN,1,0)],2,0,1,out _))result|=64;
if(value["overchargeCommandsSent"]!.GetValue<int>()==0&&value["service"]!.GetValue<string>()==Service)result|=128;
return result;
}
}
internal static class CruiseObservationExports
{
[UnmanagedCallersOnly(EntryPoint="XFEInteractionStart")]internal static uint Start(nuint thread){try{return CruiseObservationRuntime.Start(thread);}catch{return 0;}}
[UnmanagedCallersOnly(EntryPoint="XFECruiseObservationSelfTest")]internal static uint SelfTest(){try{return CruiseObservationRuntime.SelfTest();}catch{return 0;}}
}
#endif