// Server.Services.World/WorldService.cs using System.Collections.Concurrent; using Microsoft.Extensions.Logging; using Server.Data; using Server.World; using StackExchange.Redis; using SystemRevivalServer.Networking.Messages; namespace Server.Services.World; public sealed class WorldService : IWorldService { private readonly ILogger _log; private readonly ICharactersRepository _chars; private readonly IPresenceStore _presence; private readonly IDatabase _db; // Redis private readonly TimeSpan _cellTtl = TimeSpan.FromSeconds(30); // In-memory zone state (per owner node) private sealed record Entity(ulong Id, string Name, float X, float Y, float Z, float FacingRad, float Speed); private readonly ConcurrentDictionary> _zones = new(); private readonly ConcurrentDictionary> _inputs = new(); public WorldService( ILogger log, ICharactersRepository chars, IPresenceStore presence, IDatabase db) { _log = log; _chars = chars; _presence = presence; _db = db; } public async Task<(bool ok, string? error, WorldSpawn self, IEnumerable neighbors)> SpawnAsync(ulong accountId, ulong characterId, CancellationToken ct) { // Prefer Redis presence; fallback to DB row. var pos = await _presence.GetAsync(characterId, ct); Old_Character? row; if (pos is null) { row = await _chars.FindByIdAsync(characterId, ct); if (row is null || row.AccountId != accountId) return (false, "char_not_found", default!, Array.Empty()); var facingRad = row.FacingDeg * (MathF.PI / 180f); pos = new Pos(row.ZoneId, (float)row.PosX, (float)row.PosY, (float)row.PosZ, facingRad); await _presence.SetAsync(characterId, pos, ct); } else { row = await _chars.FindByIdAsync(characterId, ct); if (row is null) return (false, "char_not_found", default!, Array.Empty()); } // Update spatial cell var cell = SpatialIndex.Cell(pos.X, pos.Y, pos.Z); await SpatialIndex.UpdateAsync(_db, pos.ZoneId, characterId, cell, cell, _cellTtl); // Track in-memory entity var zone = _zones.GetOrAdd(pos.ZoneId, _ => new()); var ent = new Entity(characterId, row!.Name, pos.X, pos.Y, pos.Z, pos.FacingRad, 5f); zone[characterId] = ent; var self = new WorldSpawn(ent.Id, ent.Name, (int)pos.ZoneId, ent.X, ent.Y, ent.Z, ent.FacingRad, ent.Speed); var neighbors = zone.Values.Where(e => e.Id != ent.Id) .Select(e => new WorldSpawn(e.Id, e.Name, (int)pos.ZoneId, e.X, e.Y, e.Z, e.FacingRad, e.Speed)) .ToArray(); return (true, null, self, neighbors); } public void EnqueueInput(ulong zoneId, ulong characterId, float dx, float dy, float facingRad, uint clientSeq) { var q = _inputs.GetOrAdd(zoneId, _ => new()); q.Enqueue((characterId, dx, dy, facingRad)); } public async Task TickOwnerAsync(ulong zoneId, float dt, CancellationToken ct) { if (!_zones.TryGetValue(zoneId, out var ents)) return; if (_inputs.TryGetValue(zoneId, out var q)) { while (q.TryDequeue(out var itm)) { if (!ents.TryGetValue(itm.CharId, out var e)) continue; // Normalize input var dx = itm.Dx; var dy = itm.Dy; var mag = MathF.Sqrt(dx * dx + dy * dy); if (mag > 1e-4f) { dx /= mag; dy /= mag; } var nx = e.X + dx * e.Speed * dt; var ny = e.Y + dy * e.Speed * dt; var nf = float.IsFinite(itm.FacingRad) ? itm.FacingRad : e.FacingRad; var updated = e with { X = nx, Y = ny, FacingRad = nf }; ents[e.Id] = updated; await _presence.SetAsync(e.Id, new Pos(zoneId, nx, ny, e.Z, nf), ct); var oldCell = SpatialIndex.Cell(e.X, e.Y, e.Z); var newCell = SpatialIndex.Cell(nx, ny, e.Z); await SpatialIndex.UpdateAsync(_db, zoneId, e.Id, oldCell, newCell, _cellTtl); } } } public WorldState BuildSnapshot(ulong zoneId, long tick) { if (!_zones.TryGetValue(zoneId, out var ents)) return new WorldState((int)zoneId, tick, Array.Empty()); var list = ents.Values.Select(e => new WorldEntityState(e.Id, e.X, e.Y, e.Z, e.FacingRad, e.Speed)).ToArray(); return new WorldState((int)zoneId, tick, list); } }