using Godot;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Data;
using RailEnterprise.Protocol;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
namespace RailEnterprise.Client.Net;
///
/// Sessione di gioco del client: connessione, copia locale del mondo, esiti dei comandi e
/// notifiche. I messaggi si applicano sul thread principale in .
///
public sealed class GameSession : IAsyncDisposable
{
private readonly Dictionary> _callbacks = [];
private long _pingSentMs;
private ulong _pingNonce;
public ProtocolClient Connection { get; }
public ClientWorld World { get; }
public string ServerLabel { get; }
/// Preset di difficoltà della partita (dal Welcome; serve a «Nuova partita+»).
public string Difficulty { get; private set; } = "";
public LocalServerLauncher? LocalServer { get; set; }
/// Istante di arrivo (ms) dell'ultimo moto di ogni treno, per l'interpolazione.
public Dictionary MotionReceivedMs { get; } = [];
/// Ritardo di andata e ritorno dell'ultimo ping (ms).
public double LatencyMs { get; private set; }
public event Action? MessageApplied;
public event Action? Notified;
public event Action? CommandFailed;
private GameSession(ProtocolClient connection, ClientWorld world, string label)
{
Connection = connection;
World = world;
ServerLabel = label;
}
public static async Task ConnectAsync(GameData data, Uri uri, string token, string label, CancellationToken ct = default)
{
var connection = await ProtocolClient.ConnectAsync(uri, ct);
try
{
var welcome = await connection.HandshakeAsync(new Hello
{
ClientVersion = typeof(GameSession).Assembly.GetName().Version?.ToString() ?? "0",
Token = token,
DataHash = data.Hash,
}, ct);
var world = new ClientWorld(data);
world.Apply(welcome);
return new GameSession(connection, world, label) { Difficulty = welcome.Difficulty };
}
catch
{
await connection.DisposeAsync();
throw;
}
}
public bool IsOpen => Connection.IsOpen;
/// Applica i messaggi arrivati (al massimo maxMessages per fotogramma).
public int Poll(int maxMessages = 2000)
{
int n = 0;
while (n < maxMessages && Connection.TryReceive(out var message))
{
n++;
World.Apply(message);
switch (message)
{
case CommandResultMessage r:
if (_callbacks.Remove(r.Seq, out var callback)) callback(r);
if (!r.Ok) CommandFailed?.Invoke(r);
break;
case TrainMotion motion:
MotionReceivedMs[motion.TrainId] = (long)Time.GetTicksMsec();
break;
case Notification note:
Notified?.Invoke(note.Event);
break;
case DailyDigest digest when RequestedSpeed == digest.Speed:
RequestedSpeed = null;
break;
case Welcome welcome:
Difficulty = welcome.Difficulty;
break;
case Pong pong when pong.Nonce == _pingNonce:
LatencyMs = (long)Time.GetTicksMsec() - _pingSentMs;
break;
}
MessageApplied?.Invoke(message);
}
if ((long)Time.GetTicksMsec() - _pingSentMs > 2000) Ping();
return n;
}
private void Ping()
{
_pingSentMs = (long)Time.GetTicksMsec();
_pingNonce++;
Send(new Ping { Nonce = _pingNonce });
}
public void Send(IMessage message) => _ = SendSafe(message);
private async Task SendSafe(IMessage message)
{
try
{
await Connection.SendAsync(message);
}
catch (Exception e)
{
GD.PrintErr($"Invio non riuscito: {e.Message}");
}
}
/// Invia un comando; la callback riceve l'esito sul thread principale.
public void Command(GameCommand command, Action? onResult = null)
{
uint seq = Connection.ReserveSeq();
if (onResult is not null) _callbacks[seq] = onResult;
Send(new CommandMessage { Seq = seq, Command = command });
}
/// Ultima velocità chiesta da questo client (mostrata finché il resoconto non la conferma).
public byte? RequestedSpeed { get; private set; }
public void SetSpeed(byte speed)
{
RequestedSpeed = speed;
Send(new SetSpeed { Speed = speed });
}
public async ValueTask DisposeAsync()
{
await Connection.DisposeAsync();
LocalServer?.Dispose();
}
}