using System.Collections.Concurrent; using System.Text.Json; using DataServer.Data; using DataServer.Data.Entities; using GameServer.Dungeon; using GameServices; 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 partial class WorldHandler : IClientMessageHandler { private const int TileSize = 32; private const float TickDeltaSeconds = 0.1f; // 10Hz private const float RespawnInvulnerabilitySeconds = 3.0f; private static readonly TimeSpan NeutralInputGrace = TimeSpan.FromMilliseconds(180); private static readonly TimeSpan DirectionalPriorityGrace = TimeSpan.FromMilliseconds(450); private readonly ILogger _log; private readonly ISessionRegistry _sessions; private readonly IServiceScopeFactory _scopeFactory; private readonly WorldChunkCache _cache; private readonly WorldMovementService _movement; private readonly WorldBroadcastService _broadcast; private readonly WorldEditDeltaHub _deltaHub; private readonly LootService _lootService; private readonly ConcurrentDictionary _players = new(); private readonly ConcurrentDictionary _portalCooldownByCharacter = new(); private readonly bool _debugInput; // Zone simulations (keyed by "{regionId}:{zoneX}:{zoneY}:{zoneZ}") private readonly ConcurrentDictionary _activeZones = new(); // PvP flag cache per zone (keyed by zone key) private readonly ConcurrentDictionary _zonePvpFlags = new(); // Mob/NPC definition caches (loaded once at init) private Dictionary _mobDefinitions = new(); private Dictionary _npcDefinitions = new(); private Task? _tickTask; private CancellationTokenSource? _tickCts; private long _tick; private volatile bool _initialized; public WorldHandler( ILogger log, ISessionRegistry sessions, IServiceScopeFactory scopeFactory, WorldChunkCache cache, WorldMovementService movement, WorldBroadcastService broadcast, WorldEditDeltaHub deltaHub, LootService lootService) { _log = log; _sessions = sessions; _scopeFactory = scopeFactory; _cache = cache; _movement = movement; _broadcast = broadcast; _deltaHub = deltaHub; _lootService = lootService; var debugInputEnv = Environment.GetEnvironmentVariable("WORLD_INPUT_DEBUG"); _debugInput = !string.IsNullOrWhiteSpace(debugInputEnv) && (debugInputEnv == "1" || string.Equals(debugInputEnv, "true", StringComparison.OrdinalIgnoreCase)); } public IReadOnlyCollection SupportedOpCodes => new[] { OpCodes.WORLD_SPAWN_REQUEST, OpCodes.WORLD_INPUT, OpCodes.PONG, // World combat OpCodes.WORLD_ATTACK, OpCodes.WORLD_MOB_LOOT_REQUEST, OpCodes.WORLD_RESPAWN_REQUEST, // World NPC OpCodes.WORLD_NPC_INTERACT, OpCodes.WORLD_NPC_DIALOG_SELECT, OpCodes.WORLD_NPC_SHOP_ACTION, // World objects OpCodes.WORLD_OBJECT_INTERACT }; public async Task InitializeAsync() { if (_initialized) return; // Load mob and NPC definitions for zone simulations await LoadWorldDefinitionsAsync(); _tickCts = new CancellationTokenSource(); _tickTask = Task.Run(() => TickLoopAsync(_tickCts.Token), _tickCts.Token); _deltaHub.OnDeltaPublished += OnWorldEditDelta; _initialized = true; _log.LogInformation( "WorldHandler initialized with {MobCount} mob defs, {NpcCount} NPC defs", _mobDefinitions.Count, _npcDefinitions.Count); } private async Task LoadWorldDefinitionsAsync() { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var mobs = await db.Set() .AsNoTracking() .Where(m => m.IsEnabled) .Include(m => m.AbilityAssignments) .ThenInclude(a => a.AbilityDefinition) .ToListAsync(); _mobDefinitions = mobs.ToDictionary(m => m.Id); var npcs = await db.Set() .AsNoTracking() .Where(n => n.IsEnabled) .ToListAsync(); _npcDefinitions = npcs.ToDictionary(n => n.Id); // Log mob stats for debugging foreach (var mob in mobs.Take(5)) { var stats = mob.GetStatsForBracket(1); _log.LogInformation( "MobDef {Id} '{Name}': MoveSpeed={MoveSpeed}, AggroRange={AggroRange}, LeashRange={LeashRange}, Behavior={Behavior}, Abilities={AbilityCount}", mob.Id, mob.Name, stats.MoveSpeed, stats.AggroRange, stats.LeashRange, mob.Behavior, mob.AbilityAssignments?.Count(a => a.IsEnabled) ?? 0); } } public async Task HandleAsync(int opCode, IConnection connection, ReadOnlyMemory 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 _broadcast.SendErrorAsync(connection, "auth_required", ct); return; } if (opCode == OpCodes.WORLD_SPAWN_REQUEST) { await HandleSpawnAsync(connection, accountId, payload, ct); return; } if (opCode == OpCodes.WORLD_INPUT) { HandleInput(connection, accountId, payload); return; } // All remaining opcodes require the player to be spawned if (!_players.TryGetValue(connection.Id, out var session)) return; switch (opCode) { // Combat case OpCodes.WORLD_ATTACK: await HandleWorldAttackAsync(connection, session, payload, ct); break; case OpCodes.WORLD_MOB_LOOT_REQUEST: await HandleWorldMobLootAsync(connection, session, payload, ct); break; case OpCodes.WORLD_RESPAWN_REQUEST: await HandleWorldRespawnAsync(connection, session, ct); break; // NPC case OpCodes.WORLD_NPC_INTERACT: await HandleWorldNpcInteract(connection, session, payload, ct); break; case OpCodes.WORLD_NPC_DIALOG_SELECT: await HandleWorldNpcDialogSelect(connection, session, payload, ct); break; case OpCodes.WORLD_NPC_SHOP_ACTION: await HandleWorldNpcShopAction(connection, session, payload, ct); break; // Objects case OpCodes.WORLD_OBJECT_INTERACT: await HandleWorldObjectInteract(connection, session, payload, ct); break; } } public void OnDisconnect(Guid connectionId) { if (_players.TryRemove(connectionId, out var s)) { // Remove from zone simulation var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ); if (_activeZones.TryGetValue(zoneKey, out var zoneSim)) { zoneSim.RemovePlayer(s.CharacterId); } _ = PersistPlayerLocationAsync(s); _ = _broadcast.BroadcastToRegionAsync( OpCodes.WORLD_DESPAWN, new { playerId = s.CharacterId, reason = "disconnect" }, s.RegionId, _players, s.ConnectionId); } } // ---- Spawn (DB access only here, once per connect) ---- private async Task HandleSpawnAsync(IConnection conn, ulong accountId, ReadOnlyMemory payload, CancellationToken ct) { var req = WorldInputParser.Parse(payload) ?? new WorldInputParser.SpawnReq(); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var account = await db.Accounts.AsNoTracking().FirstOrDefaultAsync(a => a.Id == accountId, ct); if (account == null) { await _broadcast.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 _cache.ResolveRegionAsync(req.RegionId ?? character.WorldRegionId, ct); if (region == null) { await _broadcast.SendErrorAsync(conn, "region_not_found", ct); return; } await _cache.EnsureZonesAsync(region.Id, ct); var requestedExplicitChunk = req.ZoneX.HasValue || req.ZoneY.HasValue || req.ChunkX.HasValue || req.ChunkY.HasValue; var zx = Math.Clamp(req.ZoneX ?? character.WorldZoneX ?? 0, 0, Math.Max(0, region.ZonesPerRegionX - 1)); var zy = Math.Clamp(req.ZoneY ?? character.WorldZoneY ?? 0, 0, Math.Max(0, region.ZonesPerRegionY - 1)); var zz = character.WorldZoneZ ?? 0; var cx = Math.Clamp(req.ChunkX ?? character.WorldChunkX ?? 0, 0, Math.Max(0, region.ChunksPerZoneX - 1)); var cy = Math.Clamp(req.ChunkY ?? character.WorldChunkY ?? 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 = requestedExplicitChunk ? WorldMovementService.WorldPxX(region, zx, cx, tx) : (character.WorldX ?? WorldMovementService.WorldPxX(region, zx, cx, tx)); var y = requestedExplicitChunk ? WorldMovementService.WorldPxY(region, zy, cy, ty) : (character.WorldY ?? WorldMovementService.WorldPxY(region, zy, cy, ty)); if (!float.IsFinite(x) || x < (TileSize / 2f)) x = WorldMovementService.WorldPxX(region, zx, cx, tx); if (!float.IsFinite(y) || y < (TileSize / 2f)) y = WorldMovementService.WorldPxY(region, zy, cy, ty); var (pzX, pzY, pcX, pcY) = WorldMovementService.ToChunkPos(region, x, y); var s = new WorldSessionState { 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, ZoneZ = zz, ChunkX = pcX, ChunkY = pcY, X = x, Y = y }; _players[conn.Id] = s; character.WorldRegionId = s.RegionId; character.WorldZoneX = s.ZoneX; character.WorldZoneY = s.ZoneY; character.WorldZoneZ = s.ZoneZ; character.WorldChunkX = s.ChunkX; character.WorldChunkY = s.ChunkY; character.WorldX = s.X; character.WorldY = s.Y; character.LastPlayedAt = DateTime.UtcNow; await db.SaveChangesAsync(ct); var initial = await _broadcast.GetChunkUpdatesAsync(region, s, ct); var tileSheets = await db.TileMapSheets .AsNoTracking() .Where(ts => ts.IsEnabled) .OrderBy(ts => ts.Id) .Select(ts => new { id = ts.Id, name = ts.Name, path = ts.CdnPath, tileW = ts.TileWidth, tileH = ts.TileHeight, cols = ts.Columns, sheetW = ts.SheetWidth, sheetH = ts.SheetHeight }) .ToArrayAsync(ct); await _broadcast.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 }, tileSheets, 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 _broadcast.BroadcastToRegionAsync(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, _players, s.ConnectionId); } // ---- Input (pure in-memory, no DB) ---- private void HandleInput(IConnection conn, ulong accountId, ReadOnlyMemory payload) { if (!_players.TryGetValue(conn.Id, out var s)) return; if (s.AccountId != accountId) return; var req = WorldInputParser.ParseWorldInput(payload, s.X, s.Y); if (req == null) 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 hasMovement = MathF.Abs(dx) > 0.001f || MathF.Abs(dy) > 0.001f; var now = DateTime.UtcNow; if (req.NativeDirectional && hasMovement) { s.PreferDirectionalUntil = now + DirectionalPriorityGrace; s.HasPendingTarget = false; } if (req.UseTargetPosition && now >= s.PreferDirectionalUntil) { s.HasPendingTarget = true; s.PendingTargetX = req.TargetX; s.PendingTargetY = req.TargetY; s.LastNonNeutralInputAt = now; } else if (hasMovement) { s.HasPendingTarget = false; } if (hasMovement) { s.PendingMoveX = dx; s.PendingMoveY = dy; s.PendingIsRunning = req.IsRunning; s.LastNonNeutralInputAt = now; } else { var explicitDirectionalStop = req.NativeDirectional && !req.UseTargetPosition; var shouldStopNow = explicitDirectionalStop || (req.IsMovingProvided && !req.IsMoving) || (now - s.LastNonNeutralInputAt) > NeutralInputGrace; if (shouldStopNow) { s.PendingMoveX = 0f; s.PendingMoveY = 0f; s.PendingIsRunning = req.IsRunning; s.HasPendingTarget = false; } } if (!string.IsNullOrWhiteSpace(req.Facing)) s.PendingFacing = req.Facing; s.PendingSeq = req.Seq; if (_debugInput) { _log.LogInformation( "WORLD_INPUT conn={Conn} seq={Seq} nativeDir={NativeDir} useTarget={UseTarget} hasTarget={HasTarget} move=({MoveX:F3},{MoveY:F3}) target=({TargetX:F2},{TargetY:F2}) pendingTarget={PendingTarget} pendingMove=({PendingX:F3},{PendingY:F3}) pos=({PosX:F2},{PosY:F2})", conn.Id, req.Seq, req.NativeDirectional, req.UseTargetPosition, req.HasTargetPosition, req.MoveX, req.MoveY, req.TargetX, req.TargetY, s.HasPendingTarget, s.PendingMoveX, s.PendingMoveY, s.X, s.Y); } } // ---- Tick loop (zero DB queries in hot path) ---- 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 && _activeZones.IsEmpty) return; var tick = Interlocked.Read(ref _tick); // 1. Ensure players are registered in zone simulations await EnsurePlayersInZoneSimsAsync(tick, ct); // 2. Tick all active zone simulations (mob AI, combat, projectiles, etc.) TickActiveZones(tick); // 3. Broadcast combat events from zone simulations await BroadcastCombatEventsAsync(ct); // 4. Process all players (movement, chunk updates, state broadcast) var tasks = _players.Values.Select(s => ProcessPlayerTickAsync(s, tick, ct)); await Task.WhenAll(tasks); // 5. Clean up deactivated zones CleanupInactiveZones(); } private async Task ProcessPlayerTickAsync(WorldSessionState s, long tick, CancellationToken ct) { try { var region = await _cache.GetRegionAsync(s.RegionId, ct); if (region == null) { s.Errors.Add("region_not_found"); return; } // Movement + collision + portal detection (synchronous, pure in-memory) _movement.ApplyMovement(region, s, tick, _portalCooldownByCharacter, _debugInput); // Resolve cross-region portal teleports (async cache lookup, rare) await _movement.ResolvePortalTeleportAsync(s, tick, _portalCooldownByCharacter, ct); // Chunk updates (from cache, possibly one async load for first-time chunks) var updates = await _broadcast.GetChunkUpdatesAsync(region, s, ct); var errs = s.Errors.Count == 0 ? null : s.Errors.Distinct().ToArray(); s.Errors.Clear(); // Get mob/NPC data from zone simulation if active var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ); object[]? nearbyMobs = null; object[]? nearbyNpcs = null; if (_activeZones.TryGetValue(zoneKey, out var zoneSim)) { float visRange = TileSize * 48; nearbyMobs = zoneSim.Mobs.Values .Where(m => Math.Abs(m.X - s.X) <= visRange && Math.Abs(m.Y - s.Y) <= visRange) .Select(m => zoneSim.SerializeMob(m)) .ToArray(); nearbyNpcs = zoneSim.Npcs.Values .Where(n => Math.Abs(n.X - s.X) <= visRange && Math.Abs(n.Y - s.Y) <= visRange) .Select(n => zoneSim.SerializeNpc(n)) .ToArray(); } // Check PvP flag for current zone var isPvp = false; if (zoneSim != null) { isPvp = zoneSim.IsPvpEnabled; } else { var pvpKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ); _zonePvpFlags.TryGetValue(pvpKey, out isPvp); } await _broadcast.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, zoneZ = s.ZoneZ, chunkX = s.ChunkX, chunkY = s.ChunkY, isPvp }, 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 }), mobs = nearbyMobs, npcs = nearbyNpcs, chunkUpdates = updates.Select(u => u.payload), portalEvent = s.PendingPortalEvent, errors = errs }, ct); s.PendingPortalEvent = null; } catch (Exception ex) { _log.LogWarning(ex, "Error processing tick for player {CharacterId}", s.CharacterId); } } private IEnumerable VisiblePlayers(WorldSessionState self) => _players.Values.Where(p => p.ConnectionId != self.ConnectionId && p.RegionId == self.RegionId && p.ZoneZ == self.ZoneZ && 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)); // ---- Live delta forwarding (admin world edits -> game clients) ---- private void OnWorldEditDelta(string chunkKey, string deltaJson) { // Fire-and-forget: forward delta to clients and invalidate cache _ = ProcessDeltaAsync(chunkKey, deltaJson); } private async Task ProcessDeltaAsync(string chunkKey, string deltaJson) { try { // Parse the delta to extract version and operation details using var doc = JsonDocument.Parse(deltaJson); var root = doc.RootElement; var toVersion = root.TryGetProperty("toVersion", out var tv) && tv.ValueKind == JsonValueKind.Number ? tv.GetInt64() : 0L; // Parse chunk coordinates from the key for cache invalidation var parts = chunkKey.Split(':'); if (parts.Length == 6 && int.TryParse(parts[0], out var regionId) && int.TryParse(parts[1], out var zoneX) && int.TryParse(parts[2], out var zoneY) && int.TryParse(parts[3], out var zoneZ) && int.TryParse(parts[4], out var chunkX) && int.TryParse(parts[5], out var chunkY)) { // Invalidate cache so next access reloads fresh data from DB _cache.InvalidateChunk(regionId, zoneX, zoneY, zoneZ, chunkX, chunkY); // Deserialize the delta to a dynamic object for forwarding to clients. // The raw JSON from the hub already has all the fields the client needs. var deltaPayload = JsonSerializer.Deserialize(deltaJson); if (deltaPayload != null) { await _broadcast.BroadcastChunkDeltaAsync(chunkKey, deltaPayload, toVersion, _players); } } } catch (Exception ex) { _log.LogWarning(ex, "Error processing world edit delta for chunk {ChunkKey}", chunkKey); } } // ---- Zone Simulation Lifecycle ---- /// /// Ensure all players are registered in their zone's simulation. /// Activates new zone simulations as needed. /// private async Task EnsurePlayersInZoneSimsAsync(long tick, CancellationToken ct) { foreach (var s in _players.Values) { var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ); if (!_activeZones.TryGetValue(zoneKey, out var zoneSim)) { // Activate zone simulation zoneSim = await ActivateZoneSimulationAsync(zoneKey, s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ, ct); if (zoneSim == null) continue; } // Ensure player is in the simulation if (!zoneSim.Players.ContainsKey(s.CharacterId)) { var combatState = new WorldPlayerCombatState(s); await InitializePlayerCombatStateAsync(combatState, s.CharacterId, ct); zoneSim.AddPlayer(combatState); } } } /// /// Load real character stats + gear bonuses from DB to initialize player combat state. /// private async Task InitializePlayerCombatStateAsync(WorldPlayerCombatState combatState, ulong characterId, CancellationToken ct) { try { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var character = await db.DungeonCharacters .AsNoTracking() .FirstOrDefaultAsync(c => c.Id == characterId, ct); if (character == null) { // Fallback to defaults combatState.InitializeFromCharacter( strength: 10, intelligence: 10, endurance: 10, dexterity: 10, armor: 0, maxHealth: 100, weaponDamageTypeKey: "physical", resistances: new Dictionary()); return; } // Load equipped items with their definitions and crafted bonuses var equippedItems = await db.DungeonCharacterItems .AsNoTracking() .Include(i => i.ItemDefinition) .Include(i => i.CraftedItem) .Where(i => i.CharacterId == characterId && i.IsEquipped) .ToListAsync(ct); // Sum gear stat bonuses int gearStr = 0, gearInt = 0, gearEnd = 0, gearDex = 0, gearHealth = 0; int gearArmor = 0; string weaponDamageType = "physical"; var equippedDefs = new List(); foreach (var item in equippedItems) { if (item.ItemDefinition == null) continue; equippedDefs.Add(item.ItemDefinition); var (str, intel, wis, end, dex, health, mana) = item.GetTotalStats(item.ItemDefinition); gearStr += str; gearInt += intel; gearEnd += end; gearDex += dex; gearHealth += health; gearArmor += item.ItemDefinition.Armor; // Check if this is the weapon (equipped weapon slot) if (item.EquipSlot == DataServer.Data.Enums.DungeonEquipmentSlot.MainHand && !string.IsNullOrEmpty(item.ItemDefinition.DamageTypeKey)) { weaponDamageType = item.ItemDefinition.DamageTypeKey; } } // Total stats = base character + gear int totalStr = character.Strength + gearStr; int totalInt = character.Intelligence + gearInt; int totalEnd = character.Endurance + gearEnd; int totalDex = character.Dexterity + gearDex; // Max health from Endurance formula + gear bonus health int maxHealth = (50 + (totalEnd * 10)) + gearHealth; // Merge innate + gear resistances var resistances = CombatCalculator.CalculatePlayerTotalResistances( character.Resistances, equippedDefs); combatState.InitializeFromCharacter( strength: totalStr, intelligence: totalInt, endurance: totalEnd, dexterity: totalDex, armor: gearArmor, maxHealth: maxHealth, weaponDamageTypeKey: weaponDamageType, resistances: resistances); } catch (Exception ex) { _log.LogWarning(ex, "Failed to load combat stats for character {CharacterId}, using defaults", characterId); combatState.InitializeFromCharacter( strength: 10, intelligence: 10, endurance: 10, dexterity: 10, armor: 0, maxHealth: 100, weaponDamageTypeKey: "physical", resistances: new Dictionary()); } } /// /// Activate a new zone simulation by loading mob/NPC spawn data from cached chunks. /// private async Task ActivateZoneSimulationAsync( string zoneKey, int regionId, int zoneX, int zoneY, int zoneZ, CancellationToken ct) { try { var region = await _cache.GetRegionAsync(regionId, ct); if (region == null) return null; var zoneSim = new WorldZoneSimulation(zoneKey, regionId, zoneX, zoneY, zoneZ, _cache); zoneSim.SetRegion(region); // Load PvP flag from DB try { using var pvpScope = _scopeFactory.CreateScope(); var pvpDb = pvpScope.ServiceProvider.GetRequiredService(); var zone = await pvpDb.WorldZones.AsNoTracking() .FirstOrDefaultAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY && z.ZoneZ == zoneZ, ct); if (zone != null) { zoneSim.IsPvpEnabled = zone.IsPvpEnabled; _zonePvpFlags[zoneKey] = zone.IsPvpEnabled; } } catch (Exception ex) { _log.LogWarning(ex, "Failed to load PvP flag for zone {ZoneKey}", zoneKey); } // Collect mob and NPC spawns from all chunks in this zone var mobSpawns = new List<(WorldChunkMobSpawnData, int, int)>(); var npcSpawns = new List<(NpcInstance, int, int)>(); int nextNpcId = 1; for (int cx = 0; cx < region.ChunksPerZoneX; cx++) for (int cy = 0; cy < region.ChunksPerZoneY; cy++) { var chunk = await _cache.GetChunkAsync(regionId, zoneX, zoneY, zoneZ, cx, cy, ct); if (chunk == null) continue; // Calculate world pixel offset for this chunk int chunkWorldOffsetX = (zoneX * region.ChunksPerZoneX + cx) * region.ChunkWidthTiles * TileSize; int chunkWorldOffsetY = (zoneY * region.ChunksPerZoneY + cy) * region.ChunkHeightTiles * TileSize; // Extract mob spawns from MobDtos (anonymous objects) ExtractMobSpawnsFromChunk(chunk, chunkWorldOffsetX, chunkWorldOffsetY, mobSpawns); // Extract NPC spawns from NpcDtos ExtractNpcSpawnsFromChunk(chunk, chunkWorldOffsetX, chunkWorldOffsetY, npcSpawns, ref nextNpcId); } zoneSim.Initialize(_mobDefinitions, mobSpawns, npcSpawns); if (_activeZones.TryAdd(zoneKey, zoneSim)) { _log.LogInformation( "Activated zone simulation {ZoneKey}: {MobCount} mobs, {NpcCount} NPCs, {SpawnPoints} spawn points", zoneKey, zoneSim.Mobs.Count, zoneSim.Npcs.Count, zoneSim.MobSpawnTracker?.SpawnPointCount ?? 0); // Log mob details for debugging foreach (var mob in zoneSim.Mobs.Values.Take(3)) { _log.LogInformation( " Mob {Id} '{Name}' at ({X:F0},{Y:F0}): MoveSpeed={MoveSpeed}, Behavior={Behavior}, State={State}, Abilities={AbilityCount}", mob.Id, mob.Name, mob.X, mob.Y, mob.Stats.MoveSpeed, mob.Behavior, mob.State, mob.Abilities.Count); } return zoneSim; } // Another thread beat us, use their version return _activeZones.TryGetValue(zoneKey, out var existing) ? existing : null; } catch (Exception ex) { _log.LogWarning(ex, "Failed to activate zone simulation {ZoneKey}", zoneKey); return null; } } /// /// Extract mob spawn data from a cached chunk's MobDtos. /// The MobDtos are anonymous objects serialized from WorldChunkMobSpawn entities. /// private static void ExtractMobSpawnsFromChunk( WorldChunkCache.CachedChunk chunk, int chunkWorldOffsetX, int chunkWorldOffsetY, List<(WorldChunkMobSpawnData, int, int)> mobSpawns) { foreach (var mobDto in chunk.MobDtos) { // MobDtos are anonymous objects with: id, x, y, mobDefinitionId, mobName, rotation, spawnCount, respawnSeconds, metadataJson // Use JSON round-trip to extract values var json = JsonSerializer.Serialize(mobDto); using var doc = JsonDocument.Parse(json); var root = doc.RootElement; var spawnData = new WorldChunkMobSpawnData { Id = root.TryGetProperty("id", out var idProp) ? idProp.GetInt64() : 0, MobDefinitionId = root.TryGetProperty("mobDefinitionId", out var mobDefProp) ? mobDefProp.GetInt32() : 0, TileX = root.TryGetProperty("x", out var xProp) ? xProp.GetInt32() : 0, TileY = root.TryGetProperty("y", out var yProp) ? yProp.GetInt32() : 0, SpawnCount = root.TryGetProperty("spawnCount", out var scProp) ? scProp.GetInt32() : 1, RespawnSeconds = root.TryGetProperty("respawnSeconds", out var rsProp) ? rsProp.GetSingle() : 30f }; if (spawnData.MobDefinitionId > 0) { mobSpawns.Add((spawnData, chunkWorldOffsetX, chunkWorldOffsetY)); } } } /// /// Extract NPC instances from a cached chunk's NpcDtos. /// private void ExtractNpcSpawnsFromChunk( WorldChunkCache.CachedChunk chunk, int chunkWorldOffsetX, int chunkWorldOffsetY, List<(NpcInstance, int, int)> npcSpawns, ref int nextNpcId) { foreach (var npcDto in chunk.NpcDtos) { var json = JsonSerializer.Serialize(npcDto); using var doc = JsonDocument.Parse(json); var root = doc.RootElement; int npcDefId = root.TryGetProperty("npcDefinitionId", out var defProp) ? defProp.GetInt32() : 0; if (npcDefId <= 0 || !_npcDefinitions.TryGetValue(npcDefId, out var npcDef)) continue; int tileX = root.TryGetProperty("x", out var xProp) ? xProp.GetInt32() : 0; int tileY = root.TryGetProperty("y", out var yProp) ? yProp.GetInt32() : 0; float worldX = chunkWorldOffsetX + (tileX * TileSize) + (TileSize / 2f); float worldY = chunkWorldOffsetY + (tileY * TileSize) + (TileSize / 2f); var npc = NpcInstance.FromDefinition(npcDef, nextNpcId++, worldX, worldY); npcSpawns.Add((npc, chunkWorldOffsetX, chunkWorldOffsetY)); } } /// /// Tick all active zone simulations. /// private void TickActiveZones(long tick) { foreach (var (zoneKey, zoneSim) in _activeZones) { try { zoneSim.Tick(tick, TickDeltaSeconds); // Periodic debug log every ~10 seconds (100 ticks) if (tick % 100 == 0 && zoneSim.Mobs.Count > 0) { var sample = zoneSim.Mobs.Values.FirstOrDefault(); if (sample != null) { _log.LogDebug( "Zone {ZoneKey} tick {Tick}: {MobCount} mobs, {PlayerCount} players. Sample mob {Id} '{Name}' state={State} pos=({X:F0},{Y:F0}) speed={Speed}", zoneKey, tick, zoneSim.Mobs.Count, zoneSim.Players.Count, sample.Id, sample.Name, sample.State, sample.X, sample.Y, sample.Stats.MoveSpeed); } } } catch (Exception ex) { _log.LogWarning(ex, "Error ticking zone simulation {ZoneKey}", zoneKey); } } } /// /// Broadcast pending combat events from all zone simulations. /// private async Task BroadcastCombatEventsAsync(CancellationToken ct) { foreach (var (_, zoneSim) in _activeZones) { var events = new List(); while (zoneSim.PendingEvents.TryDequeue(out var evt)) { events.Add(new { type = evt.Type.ToString(), sourceMobId = evt.SourceMobId, sourcePlayerId = evt.SourcePlayerId, targetMobId = evt.TargetMobId, targetPlayerId = evt.TargetPlayerId, damage = evt.Damage, damageTypeKey = evt.DamageTypeKey, x = evt.X, y = evt.Y, mobData = evt.MobData }); } if (events.Count == 0) continue; // Send combat state to all players in this zone foreach (var player in zoneSim.Players.Values) { await _broadcast.SendAsync( player.Session.Connection, OpCodes.WORLD_COMBAT_STATE, new { events }, ct); } } } /// /// Remove deactivated zone simulations. /// private void CleanupInactiveZones() { foreach (var (zoneKey, zoneSim) in _activeZones) { if (!zoneSim.IsActive) { if (_activeZones.TryRemove(zoneKey, out var removed)) { removed.Deactivate(); _log.LogInformation("Deactivated zone simulation {ZoneKey}", zoneKey); } } } } // ---- Persistence (only on disconnect) ---- private async Task PersistPlayerLocationAsync(WorldSessionState s) { try { _log.LogInformation( "Persisting location for character {CharacterId}: Region={RegionId} Zone=({ZoneX},{ZoneY},{ZoneZ}) Chunk=({ChunkX},{ChunkY}) Pos=({X:F1},{Y:F1})", s.CharacterId, s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ, s.ChunkX, s.ChunkY, s.X, s.Y); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == s.CharacterId); if (character == null) { _log.LogWarning("Character {CharacterId} not found for position persist", s.CharacterId); return; } character.WorldRegionId = s.RegionId; character.WorldZoneX = s.ZoneX; character.WorldZoneY = s.ZoneY; character.WorldZoneZ = s.ZoneZ; character.WorldChunkX = s.ChunkX; character.WorldChunkY = s.ChunkY; character.WorldX = s.X; character.WorldY = s.Y; character.LastPlayedAt = DateTime.UtcNow; await db.SaveChangesAsync(); _log.LogInformation("Successfully persisted location for character {CharacterId}", s.CharacterId); } catch (Exception ex) { _log.LogError(ex, "Failed to persist world location for character {CharacterId}", s.CharacterId); } } }