XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEEDToolBox

【WinUI】XFE精英危险工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Globalization;
using XFEEDToolBox.Core.Plugins;

namespace XFEEDToolBox.Core.Navigation;

public sealed class NativeGameInputChannel(int processId,string gameHash,string packageDirectory):IGameInputChannel
{
    private readonly NavigationPipeClient pipe=new(processId,"Interaction");
    private readonly NavigationPipeClient mainShip=new(processId);
    private bool connected;
    public async Task ConnectAsync(int owningThread,CancellationToken token)
    {
        if(connected)return;
        System.Text.Json.JsonElement? existing=null;
        try{existing=await pipe.CallAsync(new{op="describe"},token);}
        catch(Exception error)when(!token.IsCancellationRequested&&error is IOException or OperationCanceledException){}
        if(existing is {} live)
        {
            Validate(live,owningThread);connected=true;return;
        }
        await RuntimeInteractionModule.LoadAsync(processId,gameHash,owningThread,packageDirectory,token);
        var result=await pipe.CallAsync(new{op="describe"},token);
        Validate(result,owningThread);connected=true;
    }
    private void Validate(System.Text.Json.JsonElement result,int owningThread)
    {
        if(result.GetProperty("schema").GetInt32()!=1||result.GetProperty("name").GetString()!="XFEEDToolBox.Interaction"||result.GetProperty("processId").GetInt32()!=processId
            ||result.GetProperty("gameSha256").GetString()!=gameHash||result.GetProperty("owningThread").GetInt32()!=owningThread||!result.GetProperty("ready").GetBoolean())throw new InvalidDataException("游戏输入通道身份不匹配。");
    }
    public async Task<GameInputState> ReadAsync(CancellationToken token)
    {
        var watch=System.Diagnostics.Stopwatch.StartNew();
        while(true)
        {
            var expected=await ReadMainShipAsync(token);
            var r=await pipe.CallAsync(new{op="read"},token);
            var value=new GameInputState(r.GetProperty("sequence").GetInt64(),ulong.Parse(r.GetProperty("entityId").GetString()!,CultureInfo.InvariantCulture),DateTimeOffset.FromUnixTimeMilliseconds(r.GetProperty("observedAtUnixMilliseconds").GetInt64()),
                r.GetProperty("hardpoints").GetBoolean(),r.GetProperty("cargoScoop").GetBoolean(),r.GetProperty("landingGear").GetBoolean(),r.GetProperty("appliedGeneration").GetInt64());
            var now=DateTimeOffset.UtcNow;
            // Older observers can see another ship's getter on the same update
            // thread. Never expose that sample as the player's desired inputs.
            if(value.EntityId==expected&&value.Sequence>0&&value.ObservedAt<=now.AddMilliseconds(100)&&now-value.ObservedAt<=TimeSpan.FromMilliseconds(300)
                &&await ReadMainShipAsync(token)==expected)return value;
            if(watch.Elapsed>TimeSpan.FromSeconds(1))throw new FlightTelemetryUnavailableException("正在同步当前主船的原生输入观测。");
            await Task.Delay(20,token);
        }
    }
    private async Task<ulong> ReadMainShipAsync(CancellationToken token)
    {
        var frame=await mainShip.CallAsync(new{op="health.read"},token);var health=frame.GetProperty("shipHealth");
        var at=DateTimeOffset.FromUnixTimeMilliseconds(health.GetProperty("observedAtUnixMilliseconds").GetInt64());var now=DateTimeOffset.UtcNow;
        if(!frame.GetProperty("localPlayerShipVerified").GetBoolean()||!health.GetProperty("verified").GetBoolean()
            ||frame.GetProperty("entityId").GetString()!=health.GetProperty("entityId").GetString()||at>now.AddMilliseconds(100)||now-at>TimeSpan.FromMilliseconds(300)
            ||!ulong.TryParse(frame.GetProperty("entityId").GetString(),CultureInfo.InvariantCulture,out var entity)||entity==0)
            throw new FlightTelemetryUnavailableException("等待已核对身份的当前主船观测。");
        return entity;
    }
    public async Task<long> SetAsync(GameInputState frame,string input,bool value,CancellationToken token)
    {
        if(input is not ("hardpoints" or "cargoScoop" or "landingGear"))throw new ArgumentException("未知飞船输入。",nameof(input));
        if(await ReadMainShipAsync(token)!=frame.EntityId)throw new InvalidOperationException("输入指令不属于当前主船,未发送操作。");
        var r=await pipe.CallAsync(new{op="input.set",sequence=frame.Sequence,entityId=frame.EntityId.ToString(CultureInfo.InvariantCulture),input,value,expiresAtUnixMilliseconds=frame.ObservedAt.AddMilliseconds(250).ToUnixTimeMilliseconds()},token);
        return r.GetProperty("generation").GetInt64();
    }
}