From 6e3be67f64625bb15f6fde439c5607447ff30fc6 Mon Sep 17 00:00:00 2001 From: dingo Date: Sun, 8 Feb 2026 18:57:04 -0500 Subject: [PATCH] Ability fixes and cleanup --- AbilitySystemReview.md | 82 ++++++++++++++++++++++++ Game/Dungeon/DungeonHandler.Dungeons.cs | 6 +- Game/Dungeon/DungeonHandler.MobCache.cs | 7 +- Game/Dungeon/DungeonHandler.cs | 20 ++++-- Game/Dungeon/DungeonHandlerAdmin.cs | 3 +- Game/Dungeon/DungeonSimulation.cs | 65 ++++++++++++++++++- Game/Dungeon/MobAI.cs | 8 +++ Game/Dungeon/MobInstance.cs | 1 + Services/Admin/Pages/Mobs/Edit.cshtml | 26 ++++++++ Services/Admin/Pages/Mobs/Edit.cshtml.cs | 46 ++++++++++++- 10 files changed, 248 insertions(+), 16 deletions(-) create mode 100644 AbilitySystemReview.md diff --git a/AbilitySystemReview.md b/AbilitySystemReview.md new file mode 100644 index 0000000..02d70cd --- /dev/null +++ b/AbilitySystemReview.md @@ -0,0 +1,82 @@ +# Ability System Review (Dungeon) + +## Scope +- Files reviewed: `Game/Dungeon/MobAI.cs`, `Game/Dungeon/DungeonSimulation.cs`, `Game/Dungeon/DungeonHandler.cs`, `Game/Dungeon/DungeonHandlerAdmin.cs`. +- Goal: document what works, what is missing, and the plan for per-ability animation binding when assigning abilities to mobs. + +## How It Currently Works +1. Mob definitions and ability assignments are loaded into cache in `DungeonHandler` (`RefreshMobCacheAsync`). +2. When a dungeon simulation is created, each spawned mob gets runtime `MobAbilityState` entries from `MobAbilityAssignment`. +3. During ticks, mobs in `MobState.Attacking` call `ProcessMobAbility`. +4. `ProcessMobAbility` selects highest-priority available ability and routes to the implementation by `MobAbilityType`. +5. Ability visuals are emitted as `AbilityEvent` and now sent to clients in dungeon state packets (`events.abilities`). + +## Ability Type Coverage + +### Implemented in `DungeonSimulation.ProcessMobAbility` +- `MeleeAttack` +- `Cleave` +- `ProjectileSingle` +- `ProjectileAoe` +- `GroundAoe` +- `ConeAttack` +- `SummonSingle` +- `SummonBulk` +- `Poison` +- `Bleed` +- `Burn` +- `Stun` +- `Slow` +- `Root` +- `Fear` +- `Knockback` +- `Pull` +- `HazardZone` + +### Declared in enum but not executed in `ProcessMobAbility` +- `HealSelf` +- `HealAlly` +- `HealAoe` +- `Silence` (status builder exists, but switch does not route this type) +- `BuffSelf` +- `BuffAllies` +- `Debuff` +- `Enrage` +- `Shield` +- `Charge` +- `Teleport` +- `Retreat` +- `PhaseChange` + +## Known Gaps / Risks +- Healer AI can enter `MobState.Healing`, but ability execution currently only runs when state is `MobState.Attacking`. +- `Targeting` metadata on ability definitions is currently not used in runtime targeting logic. +- Player ability-cast pipeline is not present in dungeon simulation right now (player flow is basic attack), so player-ability mana enforcement is pending until player ability execution exists. + +## Bonelord / Summon Issue Notes +- Root cause for disappearing admin-spawned boss after cast: runtime mob ID collision risk between admin-spawned IDs and summoned IDs. +- Fix approach implemented: centralized runtime ID allocation for both admin spawns and summons. + +## Plan: Ability Animation Binding on Mob Ability Assignment +1. Add optional mapping from `MobAbilityAssignment` to animation key. +2. Resolve animation key for each runtime ability at load: + - mapping override if present + - else ability definition animation + - else `attack` +3. Support directional placeholders (`[dir]` / `{dir}`) at cast time. +4. Emit resolved animation key in ability events. +5. Admin UX: when assigning ability, optionally choose animation key from assigned mob animations. +6. Show assigned/resolved animation in mob ability table for transparency. + +## Implementation Checklist +- [x] Load `mob_ability_animation_mappings` into dungeon mob cache. +- [x] Pass ability-animation mappings into all `DungeonSimulation` constructors. +- [x] Resolve mapped animation key into runtime `MobAbilityState`. +- [x] Support `[dir]` / `{dir}` replacement when emitting ability animation key. +- [x] Include ability events in outbound dungeon state payload (`events.abilities`). +- [x] Enforce mob ability mana costs before casting. +- [x] Add admin UI support to select optional animation key when assigning a mob ability. +- [x] Display ability animation (and override marker) in mob ability list. +- [x] Remove ability-animation mappings when removing an ability assignment. +- [x] Fix runtime mob ID allocation so admin spawns and summons cannot collide. +- [ ] Enforce mana for **player-cast abilities** once player ability casting exists in dungeon runtime. diff --git a/Game/Dungeon/DungeonHandler.Dungeons.cs b/Game/Dungeon/DungeonHandler.Dungeons.cs index b08a868..d3921ff 100644 --- a/Game/Dungeon/DungeonHandler.Dungeons.cs +++ b/Game/Dungeon/DungeonHandler.Dungeons.cs @@ -204,7 +204,7 @@ public sealed partial class DungeonHandler } } - var simulation = new DungeonSimulation(layout, tier, _mobDefinitions, bracketMin, _abilityDefinitions, _mobSpriteConfigs); + var simulation = new DungeonSimulation(layout, tier, _mobDefinitions, bracketMin, _abilityDefinitions, _mobSpriteConfigs, _abilityAnimationMappings); var instance = new DungeonInstance { @@ -497,7 +497,7 @@ public sealed partial class DungeonHandler try { var layout = DungeonGenerator.Generate(persisted.Seed, persisted.Tier); - var simulation = new DungeonSimulation(layout, persisted.Tier, _mobDefinitions, persisted.LevelBracketMin, _abilityDefinitions, _mobSpriteConfigs); + var simulation = new DungeonSimulation(layout, persisted.Tier, _mobDefinitions, persisted.LevelBracketMin, _abilityDefinitions, _mobSpriteConfigs, _abilityAnimationMappings); // NOTE: We intentionally do NOT restore mob state here. // When a dungeon is restored (all players left), ALL mobs respawn fresh. @@ -571,7 +571,7 @@ public sealed partial class DungeonHandler // Using DungeonGenerator.Generate() would create a V1 layout which has different // room geometry than V2/V3, causing mobs to spawn in wrong positions. var layout = instance.Simulation.Layout; - var freshSimulation = new DungeonSimulation(layout, instance.Tier, _mobDefinitions, instance.LevelBracketMin, _abilityDefinitions, _mobSpriteConfigs); + var freshSimulation = new DungeonSimulation(layout, instance.Tier, _mobDefinitions, instance.LevelBracketMin, _abilityDefinitions, _mobSpriteConfigs, _abilityAnimationMappings); // Clear and rebuild mobs, keeping those with loot instance.Simulation.Mobs.Clear(); diff --git a/Game/Dungeon/DungeonHandler.MobCache.cs b/Game/Dungeon/DungeonHandler.MobCache.cs index 5626a0c..c59cdb4 100644 --- a/Game/Dungeon/DungeonHandler.MobCache.cs +++ b/Game/Dungeon/DungeonHandler.MobCache.cs @@ -42,6 +42,10 @@ public sealed partial class DungeonHandler _abilityDefinitions = abilities.ToDictionary(a => a.Id); + var abilityAnimationMappings = await db.Set() + .ToListAsync(); + _abilityAnimationMappings = abilityAnimationMappings.ToDictionary(m => m.AbilityAssignmentId); + // Build sprite configs from animation assignments var spriteConfigBuilder = new MobSpriteConfigBuilder(db); _mobSpriteConfigs = await spriteConfigBuilder.BuildSpriteConfigsAsync(mobs.Select(m => m.Id)); @@ -50,10 +54,11 @@ public sealed partial class DungeonHandler var assignmentCount = await db.Set().CountAsync(); var abilityAssignmentsCount = mobs.Sum(m => m.AbilityAssignments?.Count ?? 0); _log.LogInformation( - "Refreshed mob cache: {MobCount} mobs, {AbilityCount} abilities, {AbilityAssignments} ability assignments, {AssignmentCount} animation assignments", + "Refreshed mob cache: {MobCount} mobs, {AbilityCount} abilities, {AbilityAssignments} ability assignments, {AbilityAnimationMappings} ability animation mappings, {AssignmentCount} animation assignments", mobs.Count, _abilityDefinitions.Count, abilityAssignmentsCount, + _abilityAnimationMappings.Count, assignmentCount); if (abilityAssignmentsCount > 0) diff --git a/Game/Dungeon/DungeonHandler.cs b/Game/Dungeon/DungeonHandler.cs index 3b1ff5a..b852d75 100644 --- a/Game/Dungeon/DungeonHandler.cs +++ b/Game/Dungeon/DungeonHandler.cs @@ -41,6 +41,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler // Mob definitions cache private Dictionary _mobDefinitions = new(); private Dictionary _abilityDefinitions = new(); + private Dictionary _abilityAnimationMappings = new(); private Dictionary _mobSpriteConfigs = new(); // MobDefinitionId -> SpriteConfig JSON private bool _initialized = false; @@ -678,7 +679,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler } } - var simulation = new DungeonSimulation(layout, tier, _mobDefinitions, bracketMin, _abilityDefinitions, _mobSpriteConfigs); + var simulation = new DungeonSimulation(layout, tier, _mobDefinitions, bracketMin, _abilityDefinitions, _mobSpriteConfigs, _abilityAnimationMappings); instance = new DungeonInstance { @@ -1531,7 +1532,6 @@ public sealed partial class DungeonHandler : IClientMessageHandler { _ = HandleDungeonClearedAsync(session); } - continue; } foreach (var session in playersInDungeon) @@ -2891,6 +2891,16 @@ public sealed partial class DungeonHandler : IClientMessageHandler x = e.X, y = e.Y, reason = e.Reason + }), + abilities = tickResult.AbilityEvents.Select(e => new + { + sourceType = e.SourceType.ToString().ToLower(), + sourceId = e.SourceId, + abilityKey = e.AbilityKey, + animationKey = e.AnimationKey, + targetX = e.TargetX, + targetY = e.TargetY, + targetId = e.TargetId }) }, @@ -2919,10 +2929,10 @@ public sealed partial class DungeonHandler : IClientMessageHandler { _log.LogInformation("Dungeon cleared! Player {Name} can now exit via portal", session.Character.Name); - // Send dungeon cleared notification (but don't force exit) - await SendAsync(session.Connection, DungeonOpCodes.DUNGEON_STATE, new + // Send dungeon cleared notification on dedicated opcode. + // Full world state still flows through regular DUNGEON_STATE packets. + await SendAsync(session.Connection, DungeonOpCodes.DUNGEON_CLEARED, new { - phase = "cleared", message = "Dungeon cleared! Use the portal to exit." }, CancellationToken.None); diff --git a/Game/Dungeon/DungeonHandlerAdmin.cs b/Game/Dungeon/DungeonHandlerAdmin.cs index 40926d8..190c8aa 100644 --- a/Game/Dungeon/DungeonHandlerAdmin.cs +++ b/Game/Dungeon/DungeonHandlerAdmin.cs @@ -134,8 +134,7 @@ public partial class DungeonHandler else spriteConfig = mobDef.SpriteConfigJson; - var maxId = dungeon.Simulation.Mobs.Keys.DefaultIfEmpty(0).Max(); - var newMobId = maxId + 1; + var newMobId = dungeon.Simulation.AllocateRuntimeMobId(); var stats = mobDef.GetStatsForBracket(dungeon.LevelBracketMin); var mob = new MobInstance diff --git a/Game/Dungeon/DungeonSimulation.cs b/Game/Dungeon/DungeonSimulation.cs index f02a09a..7163875 100644 --- a/Game/Dungeon/DungeonSimulation.cs +++ b/Game/Dungeon/DungeonSimulation.cs @@ -47,9 +47,11 @@ public partial class DungeonSimulation private int _nextDroppedItemId = 1; private int _nextMobId = 10000; // Start summoned mobs at high ID to avoid conflicts + private readonly object _mobIdLock = new(); private readonly Dictionary _mobDefinitions; private readonly Dictionary? _abilityDefinitions; private readonly Dictionary? _spriteConfigs; + private readonly Dictionary? _abilityAnimationMappings; private readonly List<(int MobDefinitionId, float X, float Y, int Tier)> _pendingSummons = new(); public DungeonSimulation( @@ -58,7 +60,8 @@ public partial class DungeonSimulation Dictionary mobDefinitions, int bracketMin = 1, Dictionary? abilityDefinitions = null, - Dictionary? spriteConfigs = null) + Dictionary? spriteConfigs = null, + Dictionary? abilityAnimationMappings = null) { Layout = layout; Tier = tier; @@ -66,6 +69,7 @@ public partial class DungeonSimulation _mobDefinitions = mobDefinitions; _abilityDefinitions = abilityDefinitions; _spriteConfigs = spriteConfigs; + _abilityAnimationMappings = abilityAnimationMappings; SpawnMobs(); InitializeChests(); @@ -272,6 +276,7 @@ public partial class DungeonSimulation AnimationKey = "attack", DamageTypeKey = stats.DamageTypeKey }, + ResolvedAnimationKey = "attack", CooldownRemaining = 0, Priority = 1 }); @@ -434,9 +439,18 @@ public partial class DungeonSimulation float distance = Distance(mob.X, mob.Y, target.X, target.Y); bool isSummonAbility = ability.Definition.AbilityType is MobAbilityType.SummonSingle or MobAbilityType.SummonBulk; if (!isSummonAbility && ability.Definition.Range > 0 && distance > ability.Definition.Range) return; + + int manaCost = Math.Max(0, ability.Definition.ManaCost); + if (manaCost > 0) + { + if (mob.Mana < manaCost) return; + mob.Mana -= manaCost; + } // Put ability on cooldown ability.CooldownRemaining = ability.Definition.Cooldown; + + string animationKey = ResolveAbilityAnimationKey(mob, ability); // Emit ability event for client animation _pendingAbilityEvents.Add(new AbilityEvent @@ -444,7 +458,7 @@ public partial class DungeonSimulation SourceType = EntityType.Mob, SourceId = mob.Id, AbilityKey = ability.Definition.Key, - AnimationKey = ability.Definition.AnimationKey, + AnimationKey = animationKey, TargetX = target.X, TargetY = target.Y, TargetId = (int)target.CharacterId @@ -574,6 +588,7 @@ public partial class DungeonSimulation { AbilityId = abilityDef.Id, Definition = abilityDef, + ResolvedAnimationKey = ResolveMappedAnimationKey(assignment.Id, abilityDef), CooldownRemaining = 0, Priority = assignment.PriorityOverride ?? abilityDef.Priority, Phase = assignment.Phase, @@ -582,6 +597,32 @@ public partial class DungeonSimulation }); } } + + private string ResolveMappedAnimationKey(int abilityAssignmentId, MobAbilityDefinition abilityDef) + { + if (_abilityAnimationMappings != null && + _abilityAnimationMappings.TryGetValue(abilityAssignmentId, out var mapping) && + !string.IsNullOrWhiteSpace(mapping.AnimationKey)) + { + return mapping.AnimationKey.Trim(); + } + + return string.IsNullOrWhiteSpace(abilityDef.AnimationKey) ? "attack" : abilityDef.AnimationKey; + } + + private static string ResolveAbilityAnimationKey(MobInstance mob, MobAbilityState ability) + { + var key = string.IsNullOrWhiteSpace(ability.ResolvedAnimationKey) + ? ability.Definition.AnimationKey + : ability.ResolvedAnimationKey; + + if (string.IsNullOrWhiteSpace(key)) + key = "attack"; + + key = key.Replace("[dir]", mob.FacingDirection, StringComparison.OrdinalIgnoreCase); + key = key.Replace("{dir}", mob.FacingDirection, StringComparison.OrdinalIgnoreCase); + return key; + } private void ProcessMeleeAbility(MobInstance mob, MobAbilityDefinition ability, PlayerInstance target) { @@ -1332,6 +1373,24 @@ public partial class DungeonSimulation _pendingSummons.Add((mobDefinitionId, x, y, tier)); } + public int AllocateRuntimeMobId() + { + lock (_mobIdLock) + { + if (_nextMobId < 10000) + { + _nextMobId = 10000; + } + + while (Mobs.ContainsKey(_nextMobId)) + { + _nextMobId++; + } + + return _nextMobId++; + } + } + /// /// Process all pending summon requests /// @@ -1374,7 +1433,7 @@ public partial class DungeonSimulation var mob = new MobInstance { - Id = _nextMobId++, + Id = AllocateRuntimeMobId(), DefinitionId = mobDef.Id, Name = mobDef.Name, X = x, diff --git a/Game/Dungeon/MobAI.cs b/Game/Dungeon/MobAI.cs index 8719611..b062b0b 100644 --- a/Game/Dungeon/MobAI.cs +++ b/Game/Dungeon/MobAI.cs @@ -544,6 +544,10 @@ public static class MobAI { mob.Health = Math.Min(mob.MaxHealth, mob.Health + (int)(mob.MaxHealth * 0.02f * deltaTime)); } + if (mob.Mana < mob.MaxMana) + { + mob.Mana = Math.Min(mob.MaxMana, mob.Mana + (int)(mob.MaxMana * 0.02f * deltaTime)); + } // State machine for wandering // States: Idle (standing still) -> Moving to wander target -> Idle again @@ -635,6 +639,10 @@ public static class MobAI { mob.Health = Math.Min(mob.MaxHealth, mob.Health + (int)(mob.MaxHealth * 0.05f * deltaTime)); } + if (mob.Mana < mob.MaxMana) + { + mob.Mana = Math.Min(mob.MaxMana, mob.Mana + (int)(mob.MaxMana * 0.05f * deltaTime)); + } } } diff --git a/Game/Dungeon/MobInstance.cs b/Game/Dungeon/MobInstance.cs index 498da0c..bb7289d 100644 --- a/Game/Dungeon/MobInstance.cs +++ b/Game/Dungeon/MobInstance.cs @@ -27,6 +27,7 @@ public class MobAbilityState { public int AbilityId { get; set; } public MobAbilityDefinition Definition { get; set; } = null!; + public string ResolvedAnimationKey { get; set; } = "attack"; public float CooldownRemaining { get; set; } public int Priority { get; set; } public int Phase { get; set; } diff --git a/Services/Admin/Pages/Mobs/Edit.cshtml b/Services/Admin/Pages/Mobs/Edit.cshtml index 9c4a0df..7b501b7 100644 --- a/Services/Admin/Pages/Mobs/Edit.cshtml +++ b/Services/Admin/Pages/Mobs/Edit.cshtml @@ -384,6 +384,7 @@ Ability Type + Animation Damage Range Cooldown @@ -396,9 +397,20 @@ @foreach (var assignment in Model.MobAbilities) { var ability = assignment.AbilityDefinition; + var hasMappedAnimation = Model.AbilityAnimationByAssignmentId.TryGetValue(assignment.Id, out var mappedAnimation); + var resolvedAnimation = hasMappedAnimation + ? mappedAnimation + : (!string.IsNullOrWhiteSpace(ability?.AnimationKey) ? ability!.AnimationKey : "attack"); @ability?.Name @ability?.AbilityType + + @resolvedAnimation + @if (hasMappedAnimation) + { + (override) + } + @ability?.BaseDamage @ability?.Range @ability?.Cooldown.ToString("0.#")s @@ -475,6 +487,20 @@ +
+ + + @if (!Model.AvailableAbilityAnimationKeys.Any()) + { +

No mob animations assigned yet. Add animations first.

+ } +
diff --git a/Services/Admin/Pages/Mobs/Edit.cshtml.cs b/Services/Admin/Pages/Mobs/Edit.cshtml.cs index b31f98d..1b4d8d4 100644 --- a/Services/Admin/Pages/Mobs/Edit.cshtml.cs +++ b/Services/Admin/Pages/Mobs/Edit.cshtml.cs @@ -47,6 +47,8 @@ public class EditModel : AdminPageModel // Ability management public List MobAbilities { get; set; } = new(); public List AllAbilities { get; set; } = new(); + public Dictionary AbilityAnimationByAssignmentId { get; set; } = new(); + public List AvailableAbilityAnimationKeys { get; set; } = new(); // Animation management public List MobAnimations { get; set; } = new(); @@ -138,12 +140,22 @@ public class EditModel : AdminPageModel .OrderBy(a => a.AbilityDefinition!.Name) .ToListAsync(); - MobAnimations = await _db.MobAnimationAssignments + MobAnimations = await _db.MobAnimationAssignments .Include(a => a.AnimationDefinition) .ThenInclude(d => d!.SpriteSheet) .Where(a => a.MobDefinitionId == id.Value) .OrderBy(a => a.AnimationDefinition!.Key) .ToListAsync(); + + AvailableAbilityAnimationKeys = BuildAvailableAbilityAnimationKeys(MobAnimations); + var assignmentIds = MobAbilities.Select(a => a.Id).ToList(); + if (assignmentIds.Count > 0) + { + var mappings = await _db.Set() + .Where(m => assignmentIds.Contains(m.AbilityAssignmentId)) + .ToListAsync(); + AbilityAnimationByAssignmentId = mappings.ToDictionary(m => m.AbilityAssignmentId, m => m.AnimationKey); + } } } else @@ -376,7 +388,7 @@ public class EditModel : AdminPageModel return RedirectToPage("/Mobs/Edit", new { id = mobId }); } - public async Task OnPostAddAbilityAsync(int mobId, int abilityId, int priority, int phase) + public async Task OnPostAddAbilityAsync(int mobId, int abilityId, int priority, int phase, string? animationKey) { // Check if already assigned var existing = await _db.MobAbilityAssignments @@ -400,6 +412,17 @@ public class EditModel : AdminPageModel _db.MobAbilityAssignments.Add(assignment); await _db.SaveChangesAsync(); + if (!string.IsNullOrWhiteSpace(animationKey)) + { + var mapping = new MobAbilityAnimationMapping + { + AbilityAssignmentId = assignment.Id, + AnimationKey = animationKey.Trim() + }; + _db.Set().Add(mapping); + await _db.SaveChangesAsync(); + } + return RedirectToPage("/Mobs/Edit", new { id = mobId }); } @@ -408,6 +431,14 @@ public class EditModel : AdminPageModel var assignment = await _db.MobAbilityAssignments.FindAsync(assignmentId); if (assignment != null) { + var mappings = await _db.Set() + .Where(m => m.AbilityAssignmentId == assignmentId) + .ToListAsync(); + if (mappings.Count > 0) + { + _db.Set().RemoveRange(mappings); + } + _db.MobAbilityAssignments.Remove(assignment); await _db.SaveChangesAsync(); } @@ -477,4 +508,15 @@ public class EditModel : AdminPageModel return Redirect($"/admin/mobs/edit?id={mobId}#animations-section"); } + + private static List BuildAvailableAbilityAnimationKeys(IEnumerable assignments) + { + return assignments + .Select(a => !string.IsNullOrWhiteSpace(a.OverrideKey) ? a.OverrideKey : a.AnimationDefinition?.Key) + .Where(k => !string.IsNullOrWhiteSpace(k)) + .Select(k => k!.Trim()) + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(k => k) + .ToList(); + } }