using Ananta.SDK.Network;
using Ananta.SDK.Rpc;
using Ananta.SDK.Serialization;
using Ananta.Server.ClientData.Client4229938;
using Ananta.Server.Gameplay.Traffic;
using Ananta.Server.Protocol.Client4229938;
using GameMethods = Ananta.Server.RpcTypes.Client4229938.Methods.Game;
using SceneMethods = Ananta.Server.RpcTypes.Client4229938.Methods.GameScene;
namespace Ananta.Server.Handlers.Game;
///
/// Light rail / metro scheduling.
///
/// The client owns the whole carriage simulation: MetroManager builds the carriages, drives them
/// along the baked MetroPath of a line and plays the gate/door animation. All the server has to do is
/// answer AskGetAllMetroInfos and then keep telling the client "train X of line Y has been running for
/// Z seconds" through SyncRunningMetroInfos - MetroClientInfo has no position field at all
/// (Id, LineId, ElapsedTime, IsFinalTrain). That is why this feature needs no client patch.
///
/// The schedule comes straight out of the client's own Rail*Config tables (RailLineConfig /
/// RailStopConfig / RailStationConfig), which the panel exposes as "where is the train, which stop is
/// it at, how long / how far until the next one".
///
internal sealed partial class GameRouter
{
private const string MetroKey = "client4229938-metro";
private const int MetroDefaultPushMs = 250;
///
/// ElapsedTime is a reading of the *server* clock, not a scene second count. The client converts it
/// with Metro.GetClientTimeFromServerTime(t) = t * INV_SERVER_TIME_FACTOR = t / 15, because the
/// in-game clock the server reports runs SERVER_TIME_FACTOR = 15 times faster than real time.
/// The baked MetroPath timeline - and therefore the RailStopConfig arrival seconds we schedule with -
/// is real seconds (the Bayshore ring takes 1123 s for roughly 12 m/s between its stations), so what
/// we push has to be the timetable second multiplied by 15.
/// Pushing the raw timetable second made every carriage sit around the beginning of its own line
/// crawling at 1/15 speed, which is exactly what round 55 was called in to fix.
///
private const double MetroDefaultTimeFactor = 15.0;
///
/// Lines enabled on a fresh session: the four city light-rail rings
/// (1 = Bayshore inner, 2 = Bayshore outer, 3 = Central, 4 = East).
/// The Chongxiao lines 9..14 and the developer test paths 5..8 belong to other scenes, so they stay
/// off until the panel turns them on - the client cannot find a MetroPath for a line the loaded
/// scene does not contain.
///
private static readonly uint[] MetroDefaultLines = [1, 2, 3, 4];
internal sealed class MetroSessionState
{
internal object SyncRoot { get; } = new();
/// Master switch. When false the loop idles without stopping, so nothing has to restart.
internal bool Enabled = true;
/// Push cadence in milliseconds.
internal int PushMs = MetroDefaultPushMs;
/// Multiplier applied to the timetable second before it goes out as ElapsedTime.
internal double TimeFactor = MetroDefaultTimeFactor;
/// Lines currently being pushed.
internal HashSet Lines = [];
///
/// The scene has actually asked for the metro list at least once. Pushes stay silent until then:
/// the client only has its MetroPaths after it has loaded the scene, so an early
/// SyncRunningMetroInfos could reach a half-built MetroManager.
///
internal bool Requested;
/// Seconds of service folded away by a previous stop, so a restart does not jump the trains.
internal double OffsetSeconds;
internal DateTime StartedUtc = DateTime.UtcNow;
internal CancellationTokenSource? Cts;
internal Task? Loop;
internal long Ticks;
internal long Pushes;
internal long TrainsSent;
internal DateTime LastPushUtc = DateTime.MinValue;
internal string? LastError;
internal double ElapsedSeconds => OffsetSeconds + (DateTime.UtcNow - StartedUtc).TotalSeconds;
}
// ---------------------------------------------------------------- state
private static MetroSessionState? TryGetMetroState(TcpSession session)
=> session.Items.TryGetValue(MetroKey, out var raw) && raw is MetroSessionState state ? state : null;
private static MetroSessionState GetMetroState(TcpSession session)
{
lock (session.Items)
{
if (session.Items.TryGetValue(MetroKey, out var raw) && raw is MetroSessionState existing)
return existing;
var created = new MetroSessionState();
foreach (var id in MetroDefaultLines)
created.Lines.Add(id);
session.Items[MetroKey] = created;
return created;
}
}
private static void EnsureMetroLoop(TcpSession session, MetroSessionState owner)
{
lock (owner.SyncRoot)
{
if (owner.Loop is { IsCompleted: false })
return;
// Carry the service time over so a restart continues the same timetable instead of resetting.
owner.OffsetSeconds += (DateTime.UtcNow - owner.StartedUtc).TotalSeconds;
owner.StartedUtc = DateTime.UtcNow;
owner.Cts?.Dispose();
owner.Cts = new CancellationTokenSource();
owner.Loop = Task.Run(() => RunMetroLoopAsync(session, owner, owner.Cts.Token));
}
}
// ---------------------------------------------------------------- protocol
///
/// The scene asks once per load, with no arguments, and expects the list of metros currently
/// running. Answering with an empty/placeholder list is why no carriage ever appeared before.
///
[Handler(MethodId.AskGetAllMetroInfos, HandlerPacketKind.Invoke)]
private async Task AskGetAllMetroInfos(Connection conn, UxRpcMessage msg)
{
var owner = GetMetroState(msg.Context.Session);
lock (owner.SyncRoot)
owner.Requested = true;
var infos = BuildMetroInfos(owner);
conn.Log.Info($"[METRO] AskGetAllMetroInfos -> {infos.Count} train(s) lines=[{MetroLineSummary(owner)}]");
await conn.ReturnAsync(msg, infos);
EnsureMetroLoop(msg.Context.Session, owner);
}
private static List BuildMetroInfos(MetroSessionState owner)
{
List lines;
double elapsed;
double timeFactor;
lock (owner.SyncRoot)
{
lines = owner.Lines.OrderBy(id => id).ToList();
elapsed = owner.ElapsedSeconds;
timeFactor = owner.TimeFactor;
}
var result = new List();
foreach (var lineId in lines)
{
if (!RailCatalog4229938.TryGetLine(lineId, out var line))
continue;
// Line 2 is the same track as line 1 but counter-clockwise, so both are pushed and the
// client draws the two directions of the ring.
var count = line.EffectiveTrainCount;
for (var i = 0; i < count; i++)
{
result.Add(new GameMethods.MetroClientInfo
{
Id = (int)((lineId * 100) + (uint)i),
LineId = lineId,
ElapsedTime = (float)(RailCatalog4229938.ElapsedForTrain(line, i, elapsed) * timeFactor),
IsFinalTrain = false,
});
}
}
return result;
}
private static string MetroLineSummary(MetroSessionState owner)
{
lock (owner.SyncRoot)
return string.Join(",", owner.Lines.OrderBy(id => id));
}
// ---------------------------------------------------------------- the loop
private static async Task RunMetroLoopAsync(TcpSession session, MetroSessionState owner, CancellationToken token)
{
session.Log.Info("[METRO] loop started");
while (!token.IsCancellationRequested)
{
try
{
await TickMetroAsync(session, owner, token);
}
catch (OperationCanceledException)
{
break;
}
catch (ObjectDisposedException)
{
session.Log.Info("[METRO] loop stopped: the session was disposed");
break;
}
catch (Exception ex)
{
lock (owner.SyncRoot)
owner.LastError = ex.Message;
session.Log.Warn($"[METRO] tick failed: {ex.Message}");
}
int period;
lock (owner.SyncRoot)
period = owner.PushMs;
try
{
await Task.Delay(Math.Clamp(period, 50, 2000), token);
}
catch (OperationCanceledException)
{
break;
}
}
session.Log.Info("[METRO] loop exit");
}
private static async Task TickMetroAsync(TcpSession session, MetroSessionState owner, CancellationToken token)
{
lock (owner.SyncRoot)
{
owner.Ticks++;
if (!owner.Enabled || !owner.Requested)
return;
}
var infos = BuildMetroInfos(owner);
if (infos.Count == 0)
return;
await session.NotifyAsync(MethodId.SyncRunningMetroInfos, UxSerializer.Serialize(infos), token);
long pushes;
lock (owner.SyncRoot)
{
owner.Pushes++;
owner.TrainsSent += infos.Count;
owner.LastPushUtc = DateTime.UtcNow;
pushes = owner.Pushes;
}
if (pushes <= 3 || pushes % 400 == 0)
session.Log.Info($"[METRO] push #{pushes} trains={infos.Count} lines=[{MetroLineSummary(owner)}]");
}
// ---------------------------------------------------------------- panel API (future wiring)
///
/// Read-only snapshot for the web panel: the whole catalog plus, for every running train, the stop
/// it is calling at, the next stop, and the remaining time / straight-line distance to it.
///
internal static object MetroStatus(TcpSession? session)
{
if (session is null)
return new { ok = false, online = false, error = "session offline" };
var owner = TryGetMetroState(session);
if (owner is null)
{
return new
{
ok = true,
online = true,
started = false,
lines = MetroCatalogView([]),
trains = Array.Empty