Files
systemrevivalserver/Game/World/WorldBroadcastService.cs
T
2026-02-17 11:18:55 -05:00

155 lines
5.9 KiB
C#

using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using Server.Networking;
using Server.Networking.Messages;
namespace GameServer.World;
public sealed class WorldBroadcastService
{
private readonly WorldChunkCache _cache;
private readonly IMessageSerializer _ser;
private readonly ILogger<WorldBroadcastService> _log;
public WorldBroadcastService(WorldChunkCache cache, IMessageSerializer ser, ILogger<WorldBroadcastService> log)
{
_cache = cache;
_ser = ser;
_log = log;
}
/// <summary>
/// Compute chunk load/unload updates for a player based on their current position.
/// Uses the cache exclusively -- the only async path is a cache-miss DB load for new chunks.
/// </summary>
public async ValueTask<List<(string type, object payload)>> GetChunkUpdatesAsync(
WorldChunkCache.CachedRegion region,
WorldSessionState s,
CancellationToken ct)
{
var required = new HashSet<string>(StringComparer.Ordinal);
var list = new List<(string, object)>();
var chunksPerRegionX = region.ZonesPerRegionX * region.ChunksPerZoneX;
var chunksPerRegionY = region.ZonesPerRegionY * region.ChunksPerZoneY;
if (chunksPerRegionX <= 0 || chunksPerRegionY <= 0)
return list;
var centerAbsChunkX = (s.ZoneX * region.ChunksPerZoneX) + s.ChunkX;
var centerAbsChunkY = (s.ZoneY * region.ChunksPerZoneY) + s.ChunkY;
for (var ay = Math.Max(0, centerAbsChunkY - 1); ay <= Math.Min(chunksPerRegionY - 1, centerAbsChunkY + 1); ay++)
for (var ax = Math.Max(0, centerAbsChunkX - 1); ax <= Math.Min(chunksPerRegionX - 1, centerAbsChunkX + 1); ax++)
{
var zx = ax / region.ChunksPerZoneX;
var zy = ay / region.ChunksPerZoneY;
var cx = ax % region.ChunksPerZoneX;
var cy = ay % region.ChunksPerZoneY;
var key = WorldChunkCache.ChunkKey(region.Id, zx, zy, s.ZoneZ, cx, cy);
required.Add(key);
if (!s.ChunkVersions.ContainsKey(key))
{
var cached = await _cache.GetChunkAsync(region.Id, zx, zy, s.ZoneZ, cx, cy, ct);
s.ChunkVersions[key] = cached?.Version ?? 0;
if (cached != null)
{
list.Add(("chunk_full", new
{
type = "chunk_full",
chunk = cached.ChunkDto,
tiles = cached.TileDtos,
objects = cached.ObjectDtos,
npcs = cached.NpcDtos,
mobs = cached.MobDtos
}));
}
else
{
list.Add(("chunk_full", new
{
type = "chunk_full",
chunk = new { regionId = region.Id, zoneX = zx, zoneY = zy, chunkX = cx, chunkY = cy, version = 0, width = region.ChunkWidthTiles, height = region.ChunkHeightTiles },
tiles = Array.Empty<object>(),
objects = Array.Empty<object>(),
npcs = Array.Empty<object>(),
mobs = Array.Empty<object>()
}));
}
}
}
foreach (var stale in s.ChunkVersions.Keys.Where(k => !required.Contains(k)).ToList())
{
s.ChunkVersions.Remove(stale);
var p = stale.Split(':');
if (p.Length >= 6)
{
list.Add(("chunk_unload", new
{
type = "chunk_unload",
regionId = int.Parse(p[0]),
zoneX = int.Parse(p[1]),
zoneY = int.Parse(p[2]),
zoneZ = int.Parse(p[3]),
chunkX = int.Parse(p[4]),
chunkY = int.Parse(p[5])
}));
}
}
return list;
}
public 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);
}
}
public Task SendErrorAsync(IConnection connection, string error, CancellationToken ct)
=> SendAsync(connection, OpCodes.ERROR, new { error }, ct);
public async Task BroadcastToRegionAsync(
int opCode,
object payload,
int regionId,
ConcurrentDictionary<Guid, WorldSessionState> players,
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);
}
/// <summary>
/// Send a chunk delta to all players who currently have the given chunk key in their visible set.
/// </summary>
public async Task BroadcastChunkDeltaAsync(
string chunkKey,
object deltaPayload,
long newVersion,
ConcurrentDictionary<Guid, WorldSessionState> players)
{
var tasks = new List<Task>();
foreach (var s in players.Values)
{
if (!s.ChunkVersions.ContainsKey(chunkKey))
continue;
// Update the player's tracked version so the next tick doesn't re-send a full chunk_load
s.ChunkVersions[chunkKey] = newVersion;
tasks.Add(SendAsync(s.Connection, OpCodes.WORLD_CHUNK_DELTA, deltaPayload, CancellationToken.None));
}
if (tasks.Count > 0)
await Task.WhenAll(tasks);
}
}