Wire overworld runtime handler and implement WORLD spawn/input/state flow

This commit is contained in:
dingo
2026-02-14 20:53:56 -05:00
parent 0ba4d02767
commit c221604ff2
3 changed files with 482 additions and 31 deletions
+446
View File
@@ -0,0 +1,446 @@
using System.Collections.Concurrent;
using System.Text;
using System.Text.Json;
using DataServer.Data;
using DataServer.Data.Entities;
using GameServices.Auth;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Server.Networking;
using Server.Networking.Handling;
using Server.Networking.Messages;
namespace GameServer.World;
public sealed class WorldHandler : IClientMessageHandler
{
private const int TileSize = 32;
private const float MoveWalk = 120f;
private const float MoveRun = 180f;
private const float StepSec = 0.05f;
private readonly ILogger<WorldHandler> _log;
private readonly ISessionRegistry _sessions;
private readonly IMessageSerializer _ser;
private readonly IServiceScopeFactory _scopeFactory;
private readonly ConcurrentDictionary<Guid, SessionState> _players = new();
private readonly JsonSerializerOptions _json = new() { PropertyNameCaseInsensitive = true };
private Task? _tickTask;
private CancellationTokenSource? _tickCts;
private long _tick;
private volatile bool _initialized;
public WorldHandler(
ILogger<WorldHandler> log,
ISessionRegistry sessions,
IMessageSerializer ser,
IServiceScopeFactory scopeFactory)
{
_log = log;
_sessions = sessions;
_ser = ser;
_scopeFactory = scopeFactory;
}
public IReadOnlyCollection<int> SupportedOpCodes => new[]
{
OpCodes.WORLD_SPAWN_REQUEST,
OpCodes.WORLD_INPUT,
OpCodes.PONG
};
public Task InitializeAsync()
{
if (_initialized) return Task.CompletedTask;
_tickCts = new CancellationTokenSource();
_tickTask = Task.Run(() => TickLoopAsync(_tickCts.Token), _tickCts.Token);
_initialized = true;
_log.LogInformation("WorldHandler initialized");
return Task.CompletedTask;
}
public async Task HandleAsync(int opCode, IConnection connection, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
if (!_initialized) await InitializeAsync();
if (opCode == OpCodes.PONG) return;
if (!_sessions.TryGet(connection.Id, out var accountId, out _))
{
if (opCode == OpCodes.WORLD_INPUT) return;
await SendErrorAsync(connection, "auth_required", ct);
return;
}
if (opCode == OpCodes.WORLD_SPAWN_REQUEST)
{
await HandleSpawnAsync(connection, accountId, payload, ct);
return;
}
if (opCode == OpCodes.WORLD_INPUT)
{
await HandleInputAsync(connection, accountId, payload, ct);
}
}
public void OnDisconnect(Guid connectionId)
{
if (_players.TryRemove(connectionId, out var s))
{
_ = BroadcastAsync(OpCodes.WORLD_DESPAWN, new { playerId = s.CharacterId, reason = "disconnect" }, s.RegionId, s.ConnectionId);
}
}
private async Task HandleSpawnAsync(IConnection conn, ulong accountId, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var req = Parse<SpawnReq>(payload) ?? new SpawnReq();
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var account = await db.Accounts.AsNoTracking().FirstOrDefaultAsync(a => a.Id == accountId, ct);
if (account == null) { await SendErrorAsync(conn, "account_not_found", ct); return; }
var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.AccountId == accountId && !c.IsDeleted, ct);
if (character == null)
{
character = new DungeonCharacter { AccountId = accountId, Name = $"Hero_{accountId}", CreatedAt = DateTime.UtcNow, LastPlayedAt = DateTime.UtcNow };
db.DungeonCharacters.Add(character);
await db.SaveChangesAsync(ct);
}
var region = await ResolveRegionAsync(db, req.RegionId, ct);
if (region == null) { await SendErrorAsync(conn, "region_not_found", ct); return; }
await EnsureZonesAsync(db, region, ct);
var zx = Math.Clamp(req.ZoneX ?? 0, 0, Math.Max(0, region.ZonesPerRegionX - 1));
var zy = Math.Clamp(req.ZoneY ?? 0, 0, Math.Max(0, region.ZonesPerRegionY - 1));
var cx = Math.Clamp(req.ChunkX ?? 0, 0, Math.Max(0, region.ChunksPerZoneX - 1));
var cy = Math.Clamp(req.ChunkY ?? 0, 0, Math.Max(0, region.ChunksPerZoneY - 1));
var tx = Math.Max(0, Math.Min(region.ChunkWidthTiles - 1, region.ChunkWidthTiles / 2));
var ty = Math.Max(0, Math.Min(region.ChunkHeightTiles - 1, region.ChunkHeightTiles / 2));
var x = WorldPxX(region, zx, cx, tx);
var y = WorldPxY(region, zy, cy, ty);
var (pzX, pzY, pcX, pcY) = ToChunkPos(region, x, y);
var s = new SessionState
{
ConnectionId = conn.Id,
Connection = conn,
AccountId = accountId,
CharacterId = character.Id,
Name = character.Name,
IsVip = account.Role >= AccountRole.Vip,
RegionId = region.Id,
ZoneX = pzX,
ZoneY = pzY,
ChunkX = pcX,
ChunkY = pcY,
X = x,
Y = y
};
_players[conn.Id] = s;
var initial = await ChunkUpdatesAsync(db, region, s, ct);
await SendAsync(conn, OpCodes.WORLD_SPAWN, new
{
success = true,
player = new { id = s.CharacterId, name = s.Name, x = s.X, y = s.Y, regionId = s.RegionId, zoneX = s.ZoneX, zoneY = s.ZoneY, chunkX = s.ChunkX, chunkY = s.ChunkY, isVip = s.IsVip },
region = new { id = region.Id, name = region.Name, zonesX = region.ZonesPerRegionX, zonesY = region.ZonesPerRegionY, chunksPerZoneX = region.ChunksPerZoneX, chunksPerZoneY = region.ChunksPerZoneY, chunkWidthTiles = region.ChunkWidthTiles, chunkHeightTiles = region.ChunkHeightTiles },
initialChunks = initial.Where(u => u.type == "chunk_full").Select(u => u.payload),
nearbyPlayers = VisiblePlayers(s).Select(p => new { id = p.CharacterId, name = p.Name, x = p.X, y = p.Y, facing = p.Facing, speed = p.Speed, isMoving = p.IsMoving })
}, ct);
await BroadcastAsync(OpCodes.WORLD_SPAWN, new
{
success = true,
isRemote = true,
player = new { id = s.CharacterId, name = s.Name, x = s.X, y = s.Y, facing = s.Facing, speed = s.Speed, isMoving = s.IsMoving, regionId = s.RegionId, zoneX = s.ZoneX, zoneY = s.ZoneY, chunkX = s.ChunkX, chunkY = s.ChunkY }
}, s.RegionId, s.ConnectionId);
}
private async Task HandleInputAsync(IConnection conn, ulong accountId, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
if (!_players.TryGetValue(conn.Id, out var s)) { await SendErrorAsync(conn, "world_not_spawned", ct); return; }
if (s.AccountId != accountId) { await SendErrorAsync(conn, "session_account_mismatch", ct); return; }
var req = Parse<InputReq>(payload);
if (req == null) { await SendErrorAsync(conn, "invalid_world_input", ct); return; }
var dx = MathF.Max(-1f, MathF.Min(1f, req.MoveX));
var dy = MathF.Max(-1f, MathF.Min(1f, req.MoveY));
var len = MathF.Sqrt((dx * dx) + (dy * dy));
if (len > 1f) { dx /= len; dy /= len; }
var speed = req.IsRunning ? MoveRun : MoveWalk;
var nextX = s.X + (dx * speed * StepSec);
var nextY = s.Y + (dy * speed * StepSec);
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var region = await db.WorldRegions.AsNoTracking().FirstOrDefaultAsync(r => r.Id == s.RegionId && r.IsEnabled, ct);
if (region == null) { s.Errors.Add("region_not_found"); return; }
if (await WalkableAsync(db, region, nextX, s.Y, s.IsVip, ct)) s.X = nextX; else s.Errors.Add("blocked_non_walkable");
if (await WalkableAsync(db, region, s.X, nextY, s.IsVip, ct)) s.Y = nextY; else s.Errors.Add("blocked_non_walkable");
var (zx, zy, cx, cy) = ToChunkPos(region, s.X, s.Y);
s.ZoneX = zx; s.ZoneY = zy; s.ChunkX = cx; s.ChunkY = cy;
s.VelX = dx * speed; s.VelY = dy * speed; s.Speed = speed; s.IsMoving = MathF.Abs(dx) > 0.001f || MathF.Abs(dy) > 0.001f;
s.Facing = Facing(req.Facing, dx, dy, s.Facing); s.Seq = req.Seq;
}
private async Task TickLoopAsync(CancellationToken ct)
{
var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(100));
try
{
while (!ct.IsCancellationRequested && await timer.WaitForNextTickAsync(ct))
{
Interlocked.Increment(ref _tick);
await SendStatesAsync(ct);
}
}
catch (OperationCanceledException) { }
finally { timer.Dispose(); }
}
private async Task SendStatesAsync(CancellationToken ct)
{
if (_players.IsEmpty) return;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var tick = Interlocked.Read(ref _tick);
foreach (var s in _players.Values)
{
var region = await db.WorldRegions.AsNoTracking().FirstOrDefaultAsync(r => r.Id == s.RegionId && r.IsEnabled, ct);
if (region == null) { s.Errors.Add("region_not_found"); continue; }
var updates = await ChunkUpdatesAsync(db, region, s, ct);
var errs = s.Errors.Count == 0 ? null : s.Errors.Distinct().ToArray();
s.Errors.Clear();
await SendAsync(s.Connection, OpCodes.WORLD_STATE, new
{
tick,
ackSeq = s.Seq,
self = new { x = s.X, y = s.Y, velocityX = s.VelX, velocityY = s.VelY, regionId = s.RegionId, zoneX = s.ZoneX, zoneY = s.ZoneY, chunkX = s.ChunkX, chunkY = s.ChunkY },
players = VisiblePlayers(s).Select(p => new { id = p.CharacterId, name = p.Name, x = p.X, y = p.Y, facing = p.Facing, speed = p.Speed, isMoving = p.IsMoving, regionId = p.RegionId, zoneX = p.ZoneX, zoneY = p.ZoneY, chunkX = p.ChunkX, chunkY = p.ChunkY }),
chunkUpdates = updates.Select(u => u.payload),
errors = errs
}, ct);
}
}
private IEnumerable<SessionState> VisiblePlayers(SessionState self)
=> _players.Values.Where(p => p.ConnectionId != self.ConnectionId && p.RegionId == self.RegionId && Math.Abs(p.ZoneX - self.ZoneX) <= 1 && Math.Abs(p.ZoneY - self.ZoneY) <= 1 && Math.Abs(p.X - self.X) <= (TileSize * 48) && Math.Abs(p.Y - self.Y) <= (TileSize * 48));
private async Task<List<(string type, object payload)>> ChunkUpdatesAsync(GameDbContext db, WorldRegion region, SessionState s, CancellationToken ct)
{
var required = new HashSet<string>(StringComparer.Ordinal);
var list = new List<(string, object)>();
for (var zy = Math.Max(0, s.ZoneY - 1); zy <= Math.Min(region.ZonesPerRegionY - 1, s.ZoneY + 1); zy++)
for (var zx = Math.Max(0, s.ZoneX - 1); zx <= Math.Min(region.ZonesPerRegionX - 1, s.ZoneX + 1); zx++)
for (var cy = Math.Max(0, s.ChunkY - 1); cy <= Math.Min(region.ChunksPerZoneY - 1, s.ChunkY + 1); cy++)
for (var cx = Math.Max(0, s.ChunkX - 1); cx <= Math.Min(region.ChunksPerZoneX - 1, s.ChunkX + 1); cx++)
{
var key = $"{region.Id}:{zx}:{zy}:{cx}:{cy}";
required.Add(key);
var data = await LoadChunkAsync(db, region, zx, zy, cx, cy, ct);
if (!s.ChunkVersions.TryGetValue(key, out var known) || known != data.version)
{
s.ChunkVersions[key] = data.version;
list.Add(("chunk_full", new { type = "chunk_full", chunk = data.chunk, tiles = data.tiles, objects = data.objects, npcs = data.npcs }));
}
}
foreach (var stale in s.ChunkVersions.Keys.Where(k => !required.Contains(k)).ToList())
{
s.ChunkVersions.Remove(stale);
var p = stale.Split(':');
list.Add(("chunk_unload", new { type = "chunk_unload", regionId = int.Parse(p[0]), zoneX = int.Parse(p[1]), zoneY = int.Parse(p[2]), chunkX = int.Parse(p[3]), chunkY = int.Parse(p[4]) }));
}
return list;
}
private async Task<(long version, object chunk, object[] tiles, object[] objects, object[] npcs)> LoadChunkAsync(GameDbContext db, WorldRegion region, int zoneX, int zoneY, int chunkX, int chunkY, CancellationToken ct)
{
var zone = await db.WorldZones.AsNoTracking().FirstOrDefaultAsync(z => z.RegionId == region.Id && z.ZoneX == zoneX && z.ZoneY == zoneY && z.IsEnabled, ct);
if (zone == null)
return (0, new { regionId = region.Id, zoneX, zoneY, chunkX, chunkY, version = 0, width = region.ChunkWidthTiles, height = region.ChunkHeightTiles }, Array.Empty<object>(), Array.Empty<object>(), Array.Empty<object>());
var chunk = await db.WorldChunks.AsNoTracking().FirstOrDefaultAsync(c => c.WorldZoneId == zone.Id && c.ChunkX == chunkX && c.ChunkY == chunkY, ct);
if (chunk == null)
return (0, new { regionId = region.Id, zoneX, zoneY, chunkX, chunkY, version = 0, width = region.ChunkWidthTiles, height = region.ChunkHeightTiles }, Array.Empty<object>(), Array.Empty<object>(), Array.Empty<object>());
var tiles = await db.WorldChunkTiles.AsNoTracking().Where(t => t.WorldChunkId == chunk.Id).OrderBy(t => t.TileY).ThenBy(t => t.TileX).Select(t => new { id = t.Id, x = t.TileX, y = t.TileY, sheetId = t.SheetId, frameIndex = t.FrameIndex, isWalkable = t.IsWalkable, isInvisiblePaywall = t.IsInvisiblePaywall }).ToArrayAsync(ct);
var objects = await db.WorldChunkObjects.AsNoTracking().Include(o => o.ObjectDefinition).Where(o => o.WorldChunkId == chunk.Id).OrderBy(o => o.TileY).ThenBy(o => o.TileX).Select(o => new { id = o.Id, x = o.TileX, y = o.TileY, objectDefinitionId = o.ObjectDefinitionId, objectName = o.ObjectDefinition != null ? o.ObjectDefinition.Name : $"Object {o.ObjectDefinitionId}", rotation = o.Rotation, metadataJson = o.MetadataJson }).ToArrayAsync(ct);
var npcs = await db.WorldChunkNpcSpawns.AsNoTracking().Include(n => n.NpcDefinition).Where(n => n.WorldChunkId == chunk.Id).OrderBy(n => n.TileY).ThenBy(n => n.TileX).Select(n => new { id = n.Id, x = n.TileX, y = n.TileY, npcDefinitionId = n.NpcDefinitionId, npcName = n.NpcDefinition != null ? n.NpcDefinition.Name : $"NPC {n.NpcDefinitionId}", rotation = n.Rotation, metadataJson = n.MetadataJson }).ToArrayAsync(ct);
return (chunk.Version, new { id = chunk.Id, regionId = region.Id, zoneX, zoneY, chunkX, chunkY, version = chunk.Version, width = region.ChunkWidthTiles, height = region.ChunkHeightTiles }, tiles.Cast<object>().ToArray(), objects.Cast<object>().ToArray(), npcs.Cast<object>().ToArray());
}
private async Task<bool> WalkableAsync(GameDbContext db, WorldRegion region, float wx, float wy, bool isVip, CancellationToken ct)
{
var checks = new[] { (0f, 0f), (8f, 0f), (-8f, 0f), (0f, 8f), (0f, -8f) };
foreach (var (ox, oy) in checks)
{
var tile = await ResolveTileAsync(db, region, wx + ox, wy + oy, ct);
if (tile == null) continue;
if (!tile.IsWalkable) return false;
if (tile.IsInvisiblePaywall && !isVip) return false;
}
return true;
}
private async Task<WorldChunkTile?> ResolveTileAsync(GameDbContext db, WorldRegion region, float wx, float wy, CancellationToken ct)
{
var gx = (int)MathF.Floor(wx / TileSize);
var gy = (int)MathF.Floor(wy / TileSize);
if (gx < 0 || gy < 0) return null;
var zoneW = region.ChunksPerZoneX * region.ChunkWidthTiles;
var zoneH = region.ChunksPerZoneY * region.ChunkHeightTiles;
if (zoneW <= 0 || zoneH <= 0) return null;
var zx = gx / zoneW; var zy = gy / zoneH;
if (zx < 0 || zy < 0 || zx >= region.ZonesPerRegionX || zy >= region.ZonesPerRegionY) return null;
var lzx = gx - (zx * zoneW); var lzy = gy - (zy * zoneH);
var cx = lzx / region.ChunkWidthTiles; var cy = lzy / region.ChunkHeightTiles;
var tx = lzx % region.ChunkWidthTiles; var ty = lzy % region.ChunkHeightTiles;
var zone = await db.WorldZones.AsNoTracking().FirstOrDefaultAsync(z => z.RegionId == region.Id && z.ZoneX == zx && z.ZoneY == zy && z.IsEnabled, ct);
if (zone == null) return null;
var chunk = await db.WorldChunks.AsNoTracking().FirstOrDefaultAsync(c => c.WorldZoneId == zone.Id && c.ChunkX == cx && c.ChunkY == cy, ct);
if (chunk == null) return null;
return await db.WorldChunkTiles.AsNoTracking().FirstOrDefaultAsync(t => t.WorldChunkId == chunk.Id && t.TileX == tx && t.TileY == ty, ct);
}
private async Task<WorldRegion?> ResolveRegionAsync(GameDbContext db, int? requestedId, CancellationToken ct)
{
if (requestedId.HasValue && requestedId.Value > 0)
{
var match = await db.WorldRegions.AsNoTracking().FirstOrDefaultAsync(r => r.Id == requestedId.Value && r.IsEnabled, ct);
if (match != null) return match;
}
return await db.WorldRegions.AsNoTracking().Where(r => r.IsEnabled).OrderBy(r => r.Id).FirstOrDefaultAsync(ct);
}
private async Task EnsureZonesAsync(GameDbContext db, WorldRegion region, CancellationToken ct)
{
var existing = await db.WorldZones.Where(z => z.RegionId == region.Id).Select(z => new { z.ZoneX, z.ZoneY }).ToListAsync(ct);
var set = existing.Select(z => $"{z.ZoneX}:{z.ZoneY}").ToHashSet(StringComparer.Ordinal);
var now = DateTime.UtcNow; var changed = false;
for (var y = 0; y < region.ZonesPerRegionY; y++)
for (var x = 0; x < region.ZonesPerRegionX; x++)
{
if (set.Contains($"{x}:{y}")) continue;
db.WorldZones.Add(new WorldZone { RegionId = region.Id, ZoneX = x, ZoneY = y, Name = $"Zone {x},{y}", IsEnabled = true, CreatedAt = now, UpdatedAt = now });
changed = true;
}
if (changed) await db.SaveChangesAsync(ct);
}
private static float WorldPxX(WorldRegion r, int zoneX, int chunkX, int tileX) => (((zoneX * (r.ChunksPerZoneX * r.ChunkWidthTiles)) + (chunkX * r.ChunkWidthTiles) + tileX) * TileSize) + (TileSize / 2f);
private static float WorldPxY(WorldRegion r, int zoneY, int chunkY, int tileY) => (((zoneY * (r.ChunksPerZoneY * r.ChunkHeightTiles)) + (chunkY * r.ChunkHeightTiles) + tileY) * TileSize) + (TileSize / 2f);
private static (int zx, int zy, int cx, int cy) ToChunkPos(WorldRegion r, float wx, float wy)
{
var gx = Math.Max(0, (int)MathF.Floor(wx / TileSize));
var gy = Math.Max(0, (int)MathF.Floor(wy / TileSize));
var zoneW = r.ChunksPerZoneX * r.ChunkWidthTiles;
var zoneH = r.ChunksPerZoneY * r.ChunkHeightTiles;
var zx = Math.Clamp(zoneW > 0 ? gx / zoneW : 0, 0, Math.Max(0, r.ZonesPerRegionX - 1));
var zy = Math.Clamp(zoneH > 0 ? gy / zoneH : 0, 0, Math.Max(0, r.ZonesPerRegionY - 1));
var lzx = gx - (zx * zoneW); var lzy = gy - (zy * zoneH);
var cx = Math.Clamp(r.ChunkWidthTiles > 0 ? lzx / r.ChunkWidthTiles : 0, 0, Math.Max(0, r.ChunksPerZoneX - 1));
var cy = Math.Clamp(r.ChunkHeightTiles > 0 ? lzy / r.ChunkHeightTiles : 0, 0, Math.Max(0, r.ChunksPerZoneY - 1));
return (zx, zy, cx, cy);
}
private static string Facing(string? facing, float dx, float dy, string fallback)
{
if (!string.IsNullOrWhiteSpace(facing))
{
var f = facing.Trim().ToLowerInvariant();
if (f is "up" or "down" or "left" or "right") return f;
}
if (MathF.Abs(dx) > MathF.Abs(dy)) return dx >= 0 ? "right" : "left";
if (MathF.Abs(dy) > 0.001f) return dy >= 0 ? "down" : "up";
return fallback;
}
private T? Parse<T>(ReadOnlyMemory<byte> payload)
{
try
{
if (payload.IsEmpty) return default;
var s = Encoding.UTF8.GetString(payload.Span);
if (string.IsNullOrWhiteSpace(s)) return default;
return JsonSerializer.Deserialize<T>(s, _json);
}
catch { return default; }
}
private async Task BroadcastAsync(int opCode, object payload, int regionId, Guid? exceptConnectionId = null)
{
var tasks = _players.Values
.Where(p => p.RegionId == regionId && (exceptConnectionId == null || p.ConnectionId != exceptConnectionId.Value))
.Select(p => SendAsync(p.Connection, opCode, payload, CancellationToken.None));
await Task.WhenAll(tasks);
}
private async Task SendAsync(IConnection connection, int opCode, object payload, CancellationToken ct)
{
try
{
var bytes = _ser.Serialize(payload);
var msg = new ServerMessage(opCode, bytes);
await connection.SendAsync(_ser.Serialize(msg), ct);
}
catch (Exception ex)
{
_log.LogWarning(ex, "Failed sending opcode {Op} to {ConnectionId}", opCode, connection.Id);
}
}
private Task SendErrorAsync(IConnection connection, string error, CancellationToken ct) => SendAsync(connection, OpCodes.ERROR, new { error }, ct);
private sealed class SessionState
{
public Guid ConnectionId { get; set; }
public IConnection Connection { get; set; } = null!;
public ulong AccountId { get; set; }
public ulong CharacterId { get; set; }
public string Name { get; set; } = "";
public bool IsVip { get; set; }
public int RegionId { get; set; }
public int ZoneX { get; set; }
public int ZoneY { get; set; }
public int ChunkX { get; set; }
public int ChunkY { get; set; }
public float X { get; set; }
public float Y { get; set; }
public float VelX { get; set; }
public float VelY { get; set; }
public string Facing { get; set; } = "down";
public float Speed { get; set; }
public bool IsMoving { get; set; }
public uint Seq { get; set; }
public Dictionary<string, long> ChunkVersions { get; } = new(StringComparer.Ordinal);
public List<string> Errors { get; } = new();
}
private sealed class SpawnReq
{
public int? RegionId { get; set; }
public int? ZoneX { get; set; }
public int? ZoneY { get; set; }
public int? ChunkX { get; set; }
public int? ChunkY { get; set; }
}
private sealed class InputReq
{
public uint Seq { get; set; }
public float MoveX { get; set; }
public float MoveY { get; set; }
public bool IsRunning { get; set; }
public string? Facing { get; set; }
}
}
+5
View File
@@ -3,6 +3,7 @@ using System.Net.Sockets;
using DataServer.Data;
using GameServer;
using GameServer.Dungeon;
using GameServer.World;
using GameServices;
using GameServices.Admin.Pages;
using GameServices.Auth;
@@ -101,6 +102,8 @@ builder.Services.AddSingleton<IClientMessageHandler, AuthHandler>();
builder.Services.AddSingleton<DungeonHandler>();
builder.Services.AddSingleton<IClientMessageHandler>(sp => sp.GetRequiredService<DungeonHandler>());
builder.Services.AddSingleton<WorldHandler>();
builder.Services.AddSingleton<IClientMessageHandler>(sp => sp.GetRequiredService<WorldHandler>());
builder.Services.AddSingleton<LootService>();
builder.Services.AddSingleton<CraftingHandler>();
builder.Services.AddSingleton<MessageRouter>();
@@ -152,6 +155,8 @@ foreach (var k in keys)
var dungeonHandler = app.Services.GetRequiredService<DungeonHandler>();
await dungeonHandler.InitializeAsync();
var worldHandler = app.Services.GetRequiredService<WorldHandler>();
await worldHandler.InitializeAsync();
var craftingHandler = app.Services.GetRequiredService<CraftingHandler>();
await craftingHandler.InitializeAsync();
+31 -31
View File
@@ -128,23 +128,18 @@
- `POST /admin/worldeditor?handler=DeleteChunk`
- Tile paint now respects tile definition walkability when a definition exists for selected `sheetId + frameIndex`.
## Overworld Runtime Client Support (Still Needed)
## Overworld Runtime Client Support
- Browser world editor APIs are in place, but in-game overworld runtime streaming is still pending.
- Client still needs final runtime contract and handlers for:
- loading world region/zone/chunk state at player spawn
- receiving nearby chunk deltas from server during movement
- enforcing `isWalkable` and VIP paywall collision in live world movement
- Runtime world opcodes are now server-wired through `WorldHandler`.
- Browser world editor APIs still exist separately for admin live-editing.
### Runtime status and wiring note
### Runtime opcodes
- `WORLD_*` opcodes already reserved in `Networking/Messages/OpCodes.cs`:
- `WORLD_SPAWN_REQUEST` (`300`)
- `WORLD_SPAWN` (`301`)
- `WORLD_DESPAWN` (`302`)
- `WORLD_INPUT` (`310`)
- `WORLD_STATE` (`311`)
- Current server handler routing is still dungeon-only, so client should keep this behind a feature flag until runtime handlers are enabled.
- `WORLD_SPAWN_REQUEST` (`300`)
- `WORLD_SPAWN` (`301`)
- `WORLD_DESPAWN` (`302`)
- `WORLD_INPUT` (`310`)
- `WORLD_STATE` (`311`)
### Client world navigation requirements
@@ -160,37 +155,39 @@
- Block movement if target tile has `isWalkable == false`.
- Block movement if target tile has `isInvisiblePaywall == true` and player is not VIP.
### Draft runtime packet contract for client implementation
### Implemented runtime packet contract
- `WORLD_SPAWN_REQUEST` (`300`) request:
- `{ characterId? }` (or empty object if selected character is already server session state).
- `{ regionId?, zoneX?, zoneY?, chunkX?, chunkY? }`
- all fields optional; server defaults to the first enabled region at `zone/chunk = 0,0`.
- `WORLD_SPAWN` (`301`) response:
- `success`
- `player`: `{ id, x, y, regionId, zoneX, zoneY, chunkX, chunkY }`
- `player`: `{ id, name, x, y, regionId, zoneX, zoneY, chunkX, chunkY, isVip }`
- `region`: `{ id, name, zonesX, zonesY, chunksPerZoneX, chunksPerZoneY, chunkWidthTiles, chunkHeightTiles }`
- `initialChunks[]`: same shape as world-editor `OnGetChunk` payload (`chunk`, `tiles[]`, `objects[]`, `npcs[]`)
- `nearbyPlayers[]` minimal shape: `{ id, name, x, y, direction, speed }`
- `initialChunks[]`: subset of `chunkUpdates` entries where `type = "chunk_full"`:
- `{ type: "chunk_full", chunk, tiles[], objects[], npcs[] }`
- `nearbyPlayers[]`: `{ id, name, x, y, facing, speed, isMoving }`
- `WORLD_INPUT` (`310`) request (20hz max):
- `{ seq, moveX, moveY, isRunning, facing, x?, y? }`
- `{ seq, moveX, moveY, isRunning, facing }`
- `WORLD_STATE` (`311`) response (10-20hz):
- `tick`
- `ackSeq`
- `self`: `{ x, y, velocityX, velocityY }`
- `players[]`: `{ id, x, y, facing, speed, isMoving }`
- `chunkDeltas[]`: list of delta payloads matching `kind: "chunk_delta"` operations used by world editor stream.
- `players[]`: `{ id, name, x, y, facing, speed, isMoving, regionId, zoneX, zoneY, chunkX, chunkY }`
- `chunkUpdates[]`:
- `chunk_full`: `{ type, chunk, tiles[], objects[], npcs[] }`
- `chunk_unload`: `{ type, regionId, zoneX, zoneY, chunkX, chunkY }`
- `errors[]` optional: e.g. `["blocked_non_walkable"]`, `["blocked_paywall"]`.
- `WORLD_DESPAWN` (`302`) response:
- `{ playerId, reason }`.
### Chunk delta handling rules in client
### Chunk update handling rules in client
- Apply delta only if `fromVersion == cachedVersion`.
- If mismatch or cache missing:
- Mark chunk `dirty`.
- Request full chunk refresh from runtime endpoint (or reconnect world session if no runtime chunk endpoint exists yet).
- `chunk_clear`:
- Remove all cached tiles/objects/npcs for that chunk.
- `chunk_deleted`:
- Remove chunk cache entry entirely and unload visuals/colliders.
- `chunk_full`:
- replace/refresh cache entry for `regionId+zoneX+zoneY+chunkX+chunkY` using `chunk.version`.
- `chunk_unload`:
- remove cache entry and unload chunk visuals/colliders.
- server emits `chunk_full` when entering visibility range or when chunk version changes.
### Rendering and assets
@@ -199,6 +196,9 @@
- Keep non-smoothed nearest-neighbor rendering for pixel art.
- Render paywall tile overlay only in editor/debug mode; keep invisible in normal gameplay while still colliding.
- Render object and NPC world instances from their definition IDs, reusing existing sprite/animation systems.
- Movement authority:
- server blocks movement against `isWalkable == false` tiles.
- server blocks movement against `isInvisiblePaywall == true` when `player.isVip == false`.
## Dungeon Portals and Ledge-Safe Movement