using System.Collections.Concurrent; using DataServer.Data.Entities; using DataServer.Data.Enums; namespace GameServer.Dungeon; /// /// Admin/management extensions for DungeonHandler /// public partial class DungeonHandler { // Track changed tiles per dungeon for differential updates private readonly ConcurrentDictionary> _changedTiles = new(); /// /// Mark a tile as changed for differential updates /// public void MarkTileChanged(Guid dungeonId, int x, int y, int layer = 0) { var bag = _changedTiles.GetOrAdd(dungeonId, _ => new ConcurrentBag<(int, int, int)>()); bag.Add((x, y, layer)); } /// /// Get all active dungeon instances (for admin viewing) /// public IReadOnlyCollection GetActiveDungeons() { return _dungeons.Values.ToList().AsReadOnly(); } /// /// Get a specific dungeon by ID (for admin viewing) /// public DungeonInstance? GetDungeon(Guid id) { _dungeons.TryGetValue(id, out var dungeon); return dungeon; } /// /// Force close a dungeon (admin action) /// public bool ForceCloseDungeon(Guid dungeonId) { if (!_dungeons.TryGetValue(dungeonId, out var dungeon)) return false; foreach (var player in dungeon.Simulation.Players.Values.ToList()) { try { Console.WriteLine("Remove Player - Not Implemented."); } catch { } } return _dungeons.TryRemove(dungeonId, out _); } /// /// Force archive a dungeon (admin action). Fails if players are inside. /// public async Task<(bool ok, string? error)> ForceArchiveDungeonAsync(Guid dungeonId, CancellationToken ct = default) { if (!_dungeons.TryGetValue(dungeonId, out var dungeon)) return (false, "Dungeon not found."); if (dungeon.Simulation.Players.Count > 0) return (false, "Dungeon has active players."); if (dungeon.IsPersisted) return (false, "Dungeon already archived."); if (dungeon.AllBossesDefeated) return (false, "Boss was killed; dungeon is marked for cleanup, not archive."); await PersistDungeonAsync(dungeon, ct); if (!dungeon.IsPersisted) return (false, "Failed to archive dungeon. Check server logs for details."); _dungeons.TryRemove(dungeonId, out _); return (true, null); } /// /// Get summary statistics for admin dashboard /// public DungeonStats GetStats() { var dungeons = _dungeons.Values.ToList(); return new DungeonStats { ActiveCount = dungeons.Count, TotalPlayers = dungeons.Sum(d => d.Simulation.Players.Count), TotalMobsAlive = dungeons.Sum(d => d.Simulation.Mobs.Values.Count(m => m.IsAlive)), CompletedCount = dungeons.Count(d => d.Simulation.Phase == DungeonPhase.Cleared), BossesKilled = dungeons.Count(d => d.AllBossesDefeated) }; } /// /// Get the pre-built sprite config for a mob definition (admin use) /// public string? GetMobSpriteConfig(int mobDefinitionId) { if (_mobSpriteConfigs.TryGetValue(mobDefinitionId, out var config)) return config; return null; } /// /// Get a mob definition by ID (admin use) /// public DungeonMobDefinition? GetMobDefinition(int mobDefinitionId) { if (_mobDefinitions.TryGetValue(mobDefinitionId, out var def)) return def; return null; } /// /// Spawn a mob in a dungeon (admin action) /// public MobInstance? SpawnMobInDungeon(Guid dungeonId, int mobDefinitionId, float x, float y) { if (!_dungeons.TryGetValue(dungeonId, out var dungeon)) return null; if (!_mobDefinitions.TryGetValue(mobDefinitionId, out var mobDef)) return null; string? spriteConfig = null; if (_mobSpriteConfigs.TryGetValue(mobDefinitionId, out var cachedConfig) && !string.IsNullOrEmpty(cachedConfig)) spriteConfig = cachedConfig; else spriteConfig = mobDef.SpriteConfigJson; var newMobId = dungeon.Simulation.AllocateRuntimeMobId(); var stats = mobDef.GetStatsForBracket(dungeon.LevelBracketMin); var mob = new MobInstance { Id = newMobId, DefinitionId = mobDef.Id, Name = mobDef.Name, Type = mobDef.Type, X = x, Y = y, SpawnX = x, SpawnY = y, Health = stats.MaxHealth, MaxHealth = stats.MaxHealth, Mana = mobDef.BaseMana, MaxMana = mobDef.BaseMana, Stats = stats, State = MobState.Idle, StateTime = 0, IsAlive = true, Behavior = mobDef.Behavior, PreferredRange = mobDef.PreferredRange, FleeThreshold = mobDef.FleeThreshold, SpriteConfigJson = spriteConfig, TintColor = mobDef.TintColor ?? "#ffffff", Scale = mobDef.Scale, CurrentAnimation = "idle_down", FacingDirection = "down" }; dungeon.Simulation.InitializeMobAbilities(mob, mobDef, stats); dungeon.Simulation.Mobs[newMobId] = mob; if (mob.Type == MobType.Boss) { dungeon.RegisterBossSpawn(newMobId); } return mob; } // ==================== TILE EDITING ==================== /// /// Set a tile's walkability (simple mode) /// public bool SetTileWalkable(Guid dungeonId, int x, int y, bool walkable) { if (!_dungeons.TryGetValue(dungeonId, out var dungeon)) return false; var layout = dungeon.LayoutV2; if (layout == null) return false; if (x < 0 || x >= layout.Width || y < 0 || y >= layout.Height) return false; layout.Walkable[x, y] = walkable; layout.Tiles[x, y] = walkable ? 1 : 0; return true; } /// /// Fill a rectangle with walkable or wall tiles /// public int FillTileRect(Guid dungeonId, int x1, int y1, int x2, int y2, bool walkable) { if (!_dungeons.TryGetValue(dungeonId, out var dungeon)) return 0; var layout = dungeon.LayoutV2; if (layout == null) return 0; int minX = Math.Max(0, Math.Min(x1, x2)); int maxX = Math.Min(layout.Width - 1, Math.Max(x1, x2)); int minY = Math.Max(0, Math.Min(y1, y2)); int maxY = Math.Min(layout.Height - 1, Math.Max(y1, y2)); int count = 0; for (int x = minX; x <= maxX; x++) { for (int y = minY; y <= maxY; y++) { layout.Walkable[x, y] = walkable; layout.Tiles[x, y] = walkable ? 1 : 0; count++; } } return count; } /// /// Place a visual tile at a position (full tile editing with graphics) /// public bool PlaceVisualTile(Guid dungeonId, int x, int y, int sheetId, int frameIndex, int layer = 0, bool walkable = true, int rotation = 0, bool flipX = false, bool flipY = false) { if (!_dungeons.TryGetValue(dungeonId, out var dungeon)) return false; var layout = dungeon.LayoutV2; if (layout == null) return false; if (x < 0 || x >= layout.Width || y < 0 || y >= layout.Height) return false; // Update walkability layout.Walkable[x, y] = walkable; layout.Tiles[x, y] = walkable ? 1 : 0; // Find existing tile at this position and layer, or create new var existingTile = layout.TileDetails.FirstOrDefault(t => t.X == x && t.Y == y && t.Layer == layer); if (existingTile != null) { existingTile.SheetId = sheetId; existingTile.FrameIndex = frameIndex; existingTile.Rotation = rotation; existingTile.FlipX = flipX; existingTile.FlipY = flipY; } else { layout.TileDetails.Add(new PlacedTile { X = x, Y = y, SheetId = sheetId, FrameIndex = frameIndex, Layer = layer, Rotation = rotation, FlipX = flipX, FlipY = flipY, TileDefinitionId = 0 }); } // Mark dungeon as having pending tile updates MarkTileChanged(dungeonId, x, y, layer); dungeon.HasPendingTileUpdates = true; return true; } /// /// Place a tile template at a position /// public bool PlaceTileTemplate(Guid dungeonId, int x, int y, TileTemplate template) { if (!_dungeons.TryGetValue(dungeonId, out var dungeon)) return false; var layout = dungeon.LayoutV2; if (layout == null) return false; // For multi-tile templates, parse TilesJson if (!string.IsNullOrEmpty(template.TilesJson)) { try { var tiles = System.Text.Json.JsonSerializer.Deserialize>(template.TilesJson); if (tiles != null) { foreach (var tile in tiles) { int tileX = x + tile.X; int tileY = y + tile.Y; if (tileX >= 0 && tileX < layout.Width && tileY >= 0 && tileY < layout.Height) { layout.Walkable[tileX, tileY] = template.IsWalkable; layout.Tiles[tileX, tileY] = template.IsWalkable ? 1 : 0; // Add visual tile var existingTile = layout.TileDetails.FirstOrDefault(t => t.X == tileX && t.Y == tileY && t.Layer == tile.Layer); if (existingTile != null) { existingTile.SheetId = tile.SheetId; existingTile.FrameIndex = tile.FrameIndex; existingTile.TileDefinitionId = (int)tile.TileDefId; } else { layout.TileDetails.Add(new PlacedTile { X = tileX, Y = tileY, SheetId = tile.SheetId, FrameIndex = tile.FrameIndex, Layer = tile.Layer, TileDefinitionId = (int)tile.TileDefId }); } // Track change for differential update MarkTileChanged(dungeonId, tileX, tileY, tile.Layer); } } } } catch { return false; } } else if (template.PrimaryTileDefinition != null) { // Simple 1x1 template var tileDef = template.PrimaryTileDefinition; if (x >= 0 && x < layout.Width && y >= 0 && y < layout.Height) { layout.Walkable[x, y] = template.IsWalkable; layout.Tiles[x, y] = template.IsWalkable ? 1 : 0; var existingTile = layout.TileDetails.FirstOrDefault(t => t.X == x && t.Y == y && t.Layer == 0); if (existingTile != null) { existingTile.SheetId = tileDef.TileMapSheetId; existingTile.FrameIndex = tileDef.FrameIndex; existingTile.TileDefinitionId = tileDef.Id; } else { layout.TileDetails.Add(new PlacedTile { X = x, Y = y, SheetId = tileDef.TileMapSheetId, FrameIndex = tileDef.FrameIndex, Layer = 0, TileDefinitionId = tileDef.Id }); } // Track change for differential update MarkTileChanged(dungeonId, x, y, 0); } } dungeon.HasPendingTileUpdates = true; return true; } /// /// Remove a tile at a position (makes it empty/wall) /// public bool RemoveTile(Guid dungeonId, int x, int y, int? layer = null) { if (!_dungeons.TryGetValue(dungeonId, out var dungeon)) return false; var layout = dungeon.LayoutV2; if (layout == null) return false; if (layer.HasValue) { layout.TileDetails.RemoveAll(t => t.X == x && t.Y == y && t.Layer == layer.Value); MarkTileChanged(dungeonId, x, y, layer.Value); } else { // Remove all layers at this position var removedLayers = layout.TileDetails .Where(t => t.X == x && t.Y == y) .Select(t => t.Layer) .Distinct() .ToList(); layout.TileDetails.RemoveAll(t => t.X == x && t.Y == y); layout.Walkable[x, y] = false; layout.Tiles[x, y] = 0; // Mark all removed layers as changed foreach (var l in removedLayers) { MarkTileChanged(dungeonId, x, y, l); } if (removedLayers.Count == 0) { MarkTileChanged(dungeonId, x, y, 0); // At least mark ground layer } } dungeon.HasPendingTileUpdates = true; return true; } /// /// Get tiles that have been updated since last broadcast /// public List? GetPendingTileUpdates(Guid dungeonId) { if (!_dungeons.TryGetValue(dungeonId, out var dungeon)) return null; if (!dungeon.HasPendingTileUpdates) return null; dungeon.HasPendingTileUpdates = false; return dungeon.LayoutV2?.TileDetails; } // ==================== PLAYER MANIPULATION ==================== public PlayerInstance? GetPlayer(Guid dungeonId, ulong characterId) { if (!_dungeons.TryGetValue(dungeonId, out var dungeon)) return null; dungeon.Simulation.Players.TryGetValue(characterId, out var player); return player; } public bool TeleportPlayer(Guid dungeonId, ulong characterId, float x, float y) { if (!_dungeons.TryGetValue(dungeonId, out var dungeon)) return false; if (!dungeon.Simulation.Players.TryGetValue(characterId, out var player)) return false; player.X = x; player.Y = y; return true; } public bool HealPlayer(Guid dungeonId, ulong characterId) { if (!_dungeons.TryGetValue(dungeonId, out var dungeon)) return false; if (!dungeon.Simulation.Players.TryGetValue(characterId, out var player)) return false; player.Health = player.MaxHealth; player.Mana = player.MaxMana; player.Stamina = player.MaxStamina; player.StatusEffects.Clear(); return true; } public bool KillPlayer(Guid dungeonId, ulong characterId) { if (!_dungeons.TryGetValue(dungeonId, out var dungeon)) return false; if (!dungeon.Simulation.Players.TryGetValue(characterId, out var player)) return false; player.Health = 0; player.IsAlive = false; return true; } public bool SetPlayerInvulnerable(Guid dungeonId, ulong characterId, bool invulnerable) { if (!_dungeons.TryGetValue(dungeonId, out var dungeon)) return false; if (!dungeon.Simulation.Players.TryGetValue(characterId, out var player)) return false; player.IsInvulnerable = invulnerable; return true; } /// /// Get dungeons with pending tile updates (for tick loop) /// public IEnumerable GetDungeonsWithPendingTileUpdates() { return _dungeons.Values.Where(d => d.HasPendingTileUpdates); } public (bool enabled, float radiusPx, int intervalTicks) GetSpatialUpdateTuning() { return (_spatialStateFilterEnabled, _spatialStateRadiusPx, _spatialStateIntervalTicks); } public void SetSpatialUpdateRangePx(float radiusPx) { _spatialStateRadiusPx = Math.Clamp(radiusPx, 128f, 8192f); _log.LogInformation("Updated spatial state radius to {RadiusPx}px", _spatialStateRadiusPx); } public void SetSpatialUpdateIntervalTicks(int intervalTicks) { _spatialStateIntervalTicks = Math.Clamp(intervalTicks, 1, 20); _log.LogInformation("Updated spatial state interval to {IntervalTicks} ticks", _spatialStateIntervalTicks); } public void SetSpatialFilterEnabled(bool enabled) { _spatialStateFilterEnabled = enabled; _log.LogInformation("Updated spatial state filtering enabled={Enabled}", _spatialStateFilterEnabled); } /// /// Build tile update payload for broadcasting to clients /// public object? BuildTileUpdatePayload(Guid dungeonId) { if (!_dungeons.TryGetValue(dungeonId, out var dungeon)) return null; if (!dungeon.HasPendingTileUpdates) return null; dungeon.HasPendingTileUpdates = false; var layout = dungeon.LayoutV2; if (layout == null) return null; // Build walkability data var walkable = new List(); for (int y = 0; y < layout.Height; y++) for (int x = 0; x < layout.Width; x++) walkable.Add(layout.Walkable[x, y]); return new { width = layout.Width, height = layout.Height, walkable = walkable, tiles = layout.TileDetails.Select(t => new { x = t.X, y = t.Y, sid = t.SheetId, frame = t.FrameIndex, l = t.Layer, r = t.Rotation, fx = t.FlipX, fy = t.FlipY }), sheets = layout.TileMapSheets.Select(s => new { id = s.Id, path = s.CdnPath, tileW = s.TileWidth, tileH = s.TileHeight, sheetW = s.SheetWidth, sheetH = s.SheetHeight, cols = s.Columns }) }; } } ///// ///// Helper class for parsing template tile placements ///// //public class TemplateTilePlacement //{ // public int X { get; set; } // public int Y { get; set; } // public int TileDefinitionId { get; set; } // public int SheetId { get; set; } // public int FrameIndex { get; set; } // public int Layer { get; set; } //} /// /// Statistics for admin dashboard /// public class DungeonStats { public int ActiveCount { get; set; } public int TotalPlayers { get; set; } public int TotalMobsAlive { get; set; } public int CompletedCount { get; set; } public int BossesKilled { get; set; } } /// /// Tile update payload for broadcasting to clients /// public class TileUpdatePayload { public List Tiles { get; set; } = new(); public List Walkable { get; set; } = new(); } public class TileUpdateData { public int X { get; set; } public int Y { get; set; } public int SheetId { get; set; } public int Frame { get; set; } public int Layer { get; set; } public int Rotation { get; set; } public bool FlipX { get; set; } public bool FlipY { get; set; } } public class WalkableUpdateData { public int X { get; set; } public int Y { get; set; } public bool Walkable { get; set; } }