Files
systemrevivalserver/Game/Dungeon/DungeonSimulation.cs
T
dingo aa81f93de5 Add explicit ability-use server logging
- Log mob ability key/type/targeting/target/range/mana when an ability is executed

- Keeps current projectile AOE behavior (single projectile with AoE impact) for easier verification
2026-02-11 08:09:14 -05:00

1679 lines
64 KiB
C#

using System.Collections.Concurrent;
using DataServer.Data.Entities;
using DataServer.Data.Enums;
namespace GameServer.Dungeon;
/// <summary>
/// Runtime simulation for an active dungeon instance
/// </summary>
public partial class DungeonSimulation
{
public DungeonLayout Layout { get; }
public int Tier { get; }
public int BracketMin { get; }
// Tick rate
public const int TicksPerSecond = 20;
public const float TickDelta = 1f / TicksPerSecond;
public long CurrentTick { get; private set; }
public DungeonPhase Phase { get; private set; } = DungeonPhase.Active;
// Entities
public ConcurrentDictionary<ulong, PlayerInstance> Players { get; } = new();
public ConcurrentDictionary<int, MobInstance> Mobs { get; } = new();
public ConcurrentDictionary<int, ChestInstance> Chests { get; } = new();
public ConcurrentDictionary<int, DroppedItem> DroppedItems { get; } = new();
public ConcurrentDictionary<int, PortalInstance> Portals { get; } = new();
public ConcurrentDictionary<int, LootChestInstance> LootChests { get; } = new();
public ConcurrentDictionary<int, ProjectileInstance> Projectiles { get; } = new();
public ConcurrentDictionary<int, HazardZone> HazardZones { get; } = new();
// ID generators
private int _nextLootChestId = 1;
private int _nextProjectileId = 1;
private int _nextHazardId = 1;
public int GetNextLootChestId() => _nextLootChestId++;
public int GetNextProjectileId() => _nextProjectileId++;
public int GetNextHazardId() => _nextHazardId++;
// Combat tracking
private readonly List<DamageEvent> _pendingDamageEvents = new();
private readonly List<DeathEvent> _pendingDeathEvents = new();
private readonly List<AbilityEvent> _pendingAbilityEvents = new();
private readonly List<ProjectileHitEvent> _pendingProjectileHitEvents = new();
private readonly List<ProjectileExpiredEvent> _pendingProjectileExpiredEvents = new();
private readonly Dictionary<string, ProjectileAbilityDiagnostics> _projectileDiagnostics = new(StringComparer.OrdinalIgnoreCase);
private long _lastProjectileDiagnosticsLogTick;
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<int, DungeonMobDefinition> _mobDefinitions;
private readonly Dictionary<int, MobAbilityDefinition>? _abilityDefinitions;
private readonly Dictionary<int, string?>? _spriteConfigs;
private readonly Dictionary<int, MobAbilityAnimationMapping>? _abilityAnimationMappings;
private readonly List<(int MobDefinitionId, float X, float Y, int Tier)> _pendingSummons = new();
public DungeonSimulation(
DungeonLayout layout,
int tier,
Dictionary<int, DungeonMobDefinition> mobDefinitions,
int bracketMin = 1,
Dictionary<int, MobAbilityDefinition>? abilityDefinitions = null,
Dictionary<int, string?>? spriteConfigs = null,
Dictionary<int, MobAbilityAnimationMapping>? abilityAnimationMappings = null)
{
Layout = layout;
Tier = tier;
BracketMin = bracketMin;
_mobDefinitions = mobDefinitions;
_abilityDefinitions = abilityDefinitions;
_spriteConfigs = spriteConfigs;
_abilityAnimationMappings = abilityAnimationMappings;
SpawnMobs();
InitializeChests();
SpawnExitPortal();
}
private void SpawnExitPortal()
{
// Spawn exit portal in corner of entrance room (away from center and hallways)
if (Layout.Rooms.Count == 0) return;
var entranceRoom = Layout.Rooms[0];
// Room uses X, Y as top-left corner
int roomLeft = entranceRoom.X + 1;
int roomRight = entranceRoom.X + entranceRoom.Width - 2;
int roomTop = entranceRoom.Y + 1;
int roomBottom = entranceRoom.Y + entranceRoom.Height - 2;
// Try corners first (away from center where players spawn)
var cornerPositions = new[]
{
(roomLeft + 1, roomTop + 1), // Top-left
(roomRight - 1, roomTop + 1), // Top-right
(roomLeft + 1, roomBottom - 1), // Bottom-left
(roomRight - 1, roomBottom - 1), // Bottom-right
};
foreach (var (tileX, tileY) in cornerPositions)
{
// Check if this is a valid floor tile
if (Layout.IsWalkable(tileX, tileY))
{
// Check surrounding tiles to avoid placing near hallways
bool nearHallway = false;
for (int dx = -1; dx <= 1 && !nearHallway; dx++)
{
for (int dy = -1; dy <= 1 && !nearHallway; dy++)
{
int checkX = tileX + dx;
int checkY = tileY + dy;
// Check if this position is outside the room bounds (potential hallway)
bool outsideRoom = checkX < entranceRoom.X ||
checkX >= entranceRoom.X + entranceRoom.Width ||
checkY < entranceRoom.Y ||
checkY >= entranceRoom.Y + entranceRoom.Height;
if (outsideRoom && Layout.IsWalkable(checkX, checkY)) // Floor outside room = hallway
{
nearHallway = true;
}
}
}
if (!nearHallway)
{
var portal = new PortalInstance
{
Id = 1,
X = tileX * 32 + 16, // Center of tile in world coords
Y = tileY * 32 + 16,
Type = PortalType.Exit,
IsActive = true
};
Portals[portal.Id] = portal;
return;
}
}
}
// Fallback: try any position in the room away from center
var offsets = new[] { (-3, -3), (3, -3), (-3, 3), (3, 3), (-3, 0), (3, 0), (0, -3), (0, 3) };
foreach (var (dx, dy) in offsets)
{
int portalTileX = entranceRoom.CenterX + dx;
int portalTileY = entranceRoom.CenterY + dy;
if (Layout.IsWalkable(portalTileX, portalTileY))
{
var portal = new PortalInstance
{
Id = 1,
X = portalTileX * 32 + 16,
Y = portalTileY * 32 + 16,
Type = PortalType.Exit,
IsActive = true
};
Portals[portal.Id] = portal;
return;
}
}
// Last fallback: spawn at room center
var fallbackPortal = new PortalInstance
{
Id = 1,
X = entranceRoom.CenterX * 32 + 16,
Y = entranceRoom.CenterY * 32 + 16,
Type = PortalType.Exit,
IsActive = true
};
Portals[fallbackPortal.Id] = fallbackPortal;
}
private void SpawnMobs()
{
var rng = new Random(Layout.Seed);
foreach (var mobSpawn in Layout.MobSpawns)
{
// Use specific mob if MobDefinitionId is set, otherwise select randomly
DungeonMobDefinition? mobDef = null;
if (mobSpawn.MobDefinitionId.HasValue)
{
_mobDefinitions.TryGetValue(mobSpawn.MobDefinitionId.Value, out mobDef);
}
// Fall back to random selection if no specific mob or mob not found
if (mobDef == null)
{
mobDef = SelectMobDefinition(mobSpawn.MobType, rng);
}
if (mobDef == null) continue;
// Use bracket-aware stat scaling
var stats = mobDef.GetStatsForBracket(BracketMin);
// Get sprite config - prefer new format from _spriteConfigs, fallback to legacy SpriteConfigJson
string? spriteConfig = null;
if (_spriteConfigs != null && _spriteConfigs.TryGetValue(mobDef.Id, out var newConfig) && !string.IsNullOrEmpty(newConfig))
{
spriteConfig = newConfig;
}
else
{
spriteConfig = mobDef.SpriteConfigJson;
}
var mob = new MobInstance
{
Id = mobSpawn.Id,
DefinitionId = mobDef.Id,
Name = mobDef.Name,
X = mobSpawn.X * 32 + 16,
Y = mobSpawn.Y * 32 + 16,
SpawnX = mobSpawn.X * 32 + 16,
SpawnY = mobSpawn.Y * 32 + 16,
Health = stats.MaxHealth,
MaxHealth = stats.MaxHealth,
Mana = mobDef.BaseMana,
MaxMana = mobDef.BaseMana,
Stats = stats,
State = MobState.Idle,
StateTime = (float)(rng.NextDouble() * 3f), // Randomize so mobs don't all start moving at once
SpriteConfigJson = spriteConfig,
TintColor = mobDef.TintColor,
Scale = mobDef.Scale,
Type = mobDef.Type,
Behavior = mobDef.Behavior,
PreferredRange = mobDef.PreferredRange,
FleeThreshold = mobDef.FleeThreshold,
Phases = mobDef.Phases,
CurrentAnimation = "idle_down",
FacingDirection = "down"
};
InitializeMobAbilities(mob, mobDef, stats);
Mobs[mobSpawn.Id] = mob;
}
}
public void InitializeMobAbilities(MobInstance mob, DungeonMobDefinition mobDef, DungeonMobCombatStats stats)
{
mob.Abilities.Clear();
LoadMobAbilities(mob, mobDef);
bool hasBasicMelee = mob.Abilities.Any(a => a.Definition.AbilityType == MobAbilityType.MeleeAttack);
// Always ensure there is at least one reliable melee fallback.
// This prevents ability setups (mana-gated/unimplemented types) from disabling all mob damage.
if (!hasBasicMelee)
{
if (mobDef.Id == 100 || mobDef.Name == "The Bone Lord")
{
Console.WriteLine(
$"[DungeonSimulation] Bone Lord has no melee fallback; adding Basic Attack.");
}
mob.Abilities.Add(new MobAbilityState
{
AbilityId = 0,
Definition = new MobAbilityDefinition
{
Id = 0,
Name = "Basic Attack",
Key = "basic_attack",
AbilityType = MobAbilityType.MeleeAttack,
BaseDamage = stats.PhysicalDamage,
Range = stats.AttackRange,
Cooldown = 1f / stats.AttackSpeed,
AnimationKey = "attack",
DamageTypeKey = stats.DamageTypeKey
},
ResolvedAnimationKey = "attack",
CooldownRemaining = 0,
Priority = 1
});
}
}
private void InitializeChests()
{
foreach (var chestSpawn in Layout.ChestSpawns)
{
Chests[chestSpawn.Id] = new ChestInstance
{
Id = chestSpawn.Id,
X = chestSpawn.X * 32 + 16,
Y = chestSpawn.Y * 32 + 16,
Type = chestSpawn.ChestType,
IsOpened = false
};
}
}
private DungeonMobDefinition? SelectMobDefinition(DungeonMobSpawnType spawnType, Random rng)
{
var candidates = _mobDefinitions.Values
.Where(m => m.IsEnabled && m.MinTier <= Tier && m.MaxTier >= Tier)
.ToList();
if (candidates.Count == 0) return null;
candidates = spawnType switch
{
DungeonMobSpawnType.Boss => candidates.Where(m => m.Type == MobType.Boss).ToList(),
DungeonMobSpawnType.Elite => candidates.Where(m => m.Type == MobType.Elite || m.Type == MobType.Miniboss).ToList(),
_ => candidates.Where(m => m.Type == MobType.Normal || m.Type == MobType.Swarm).ToList()
};
if (candidates.Count == 0)
{
candidates = _mobDefinitions.Values.Where(m => m.IsEnabled && m.MinTier <= Tier).ToList();
}
return candidates.Count == 0 ? null : candidates[rng.Next(candidates.Count)];
}
/// <summary>
/// Process one simulation tick
/// </summary>
public TickResult Tick(long tick)
{
CurrentTick = tick;
_pendingDamageEvents.Clear();
_pendingDeathEvents.Clear();
_pendingAbilityEvents.Clear();
_pendingProjectileHitEvents.Clear();
_pendingProjectileExpiredEvents.Clear();
// If dungeon is not active, still allow basic updates (movement, corpse cleanup)
// but skip combat/AI
bool skipCombat = Phase != DungeonPhase.Active;
// Only do combat/AI if dungeon is active
if (!skipCombat)
{
// Update all mobs (AI)
foreach (var mob in Mobs.Values.Where(m => m.IsAlive))
{
// Defensive normalization in case persisted/runtime state drifts.
if (mob.State == MobState.Dead)
{
mob.State = MobState.Idle;
}
if (!string.IsNullOrWhiteSpace(mob.CurrentAnimation) &&
mob.CurrentAnimation.StartsWith("death_", StringComparison.OrdinalIgnoreCase))
{
mob.CurrentAnimation = mob.GetDirectionalAnimation("idle");
}
MobAI.UpdateMob(mob, this, TickDelta);
// Process mob attacks if in attacking state
if (mob.State == MobState.Attacking && mob.TargetId.HasValue)
{
float attackInterval = 1f / mob.Stats.AttackSpeed;
if (CurrentTick - mob.LastAttackTick >= (long)(attackInterval * TicksPerSecond))
{
if (Players.TryGetValue(mob.TargetId.Value, out var target) && target.IsAlive)
{
ProcessMobAbility(mob, target);
}
mob.LastAttackTick = CurrentTick;
}
}
}
// Update projectiles
UpdateProjectiles();
// Update hazard zones
UpdateHazardZones();
}
// Always update players (movement, regeneration, status effects) - even when cleared
foreach (var player in Players.Values.Where(p => p.IsAlive))
{
UpdatePlayer(player);
}
// Keep corpses in the world after death (even after loot is emptied).
// We still stamp when loot becomes empty so UI/inspection logic can reference it.
foreach (var mob in Mobs.Values.Where(m => !m.IsAlive))
{
if (mob.State != MobState.Dead)
{
mob.State = MobState.Dead;
}
if (string.IsNullOrWhiteSpace(mob.CurrentAnimation) ||
!mob.CurrentAnimation.StartsWith("death_", StringComparison.OrdinalIgnoreCase))
{
mob.CurrentAnimation = mob.GetDirectionalAnimation("death");
}
if (!mob.HasDeathLoot && !mob.LootEmptiedAtTick.HasValue)
{
mob.LootEmptiedAtTick = CurrentTick;
}
}
// Check dungeon completion (only once when phase is still Active)
if (Phase == DungeonPhase.Active && Mobs.Values.All(m => !m.IsAlive))
{
Phase = DungeonPhase.Cleared;
SpawnExit();
}
// Process pending summons
ProcessPendingSummons();
return new TickResult
{
DamageEvents = new List<DamageEvent>(_pendingDamageEvents),
DeathEvents = new List<DeathEvent>(_pendingDeathEvents),
AbilityEvents = new List<AbilityEvent>(_pendingAbilityEvents),
ProjectileHitEvents = new List<ProjectileHitEvent>(_pendingProjectileHitEvents),
ProjectileExpiredEvents = new List<ProjectileExpiredEvent>(_pendingProjectileExpiredEvents),
Phase = Phase
};
}
/// <summary>
/// Process a mob's ability/attack against a target
/// </summary>
private void ProcessMobAbility(MobInstance mob, PlayerInstance target)
{
// Find the best currently usable ability.
var ability = mob.Abilities
.Where(a => a.IsAvailable(mob.HpPercent))
.Where(a => a.Phase == 0 || a.Phase == mob.CurrentPhase)
.Where(a => IsImplementedAbilityType(a.Definition.AbilityType))
.Where(a => CanUseAbilityNow(mob, target, a.Definition))
.OrderByDescending(a => a.Priority)
.FirstOrDefault();
if (ability == null) return;
int manaCost = Math.Max(0, ability.Definition.ManaCost);
if (manaCost > 0)
{
mob.Mana -= manaCost;
}
// Put ability on cooldown
ability.CooldownRemaining = ability.Definition.Cooldown;
string animationKey = ResolveAbilityAnimationKey(mob, ability);
Console.WriteLine(
$"[AbilityUse] Mob {mob.Id} ({mob.Name}) used {ability.Definition.Key} " +
$"type={ability.Definition.AbilityType} targeting={ability.Definition.Targeting} " +
$"targetPlayer={target.CharacterId} range={ability.Definition.Range} mana={mob.Mana}/{mob.MaxMana}");
// Emit ability event for client animation
_pendingAbilityEvents.Add(new AbilityEvent
{
SourceType = EntityType.Mob,
SourceId = mob.Id,
AbilityKey = ability.Definition.Key,
AnimationKey = animationKey,
TargetX = target.X,
TargetY = target.Y,
TargetId = (int)target.CharacterId
});
// Process ability based on type
switch (ability.Definition.AbilityType)
{
case MobAbilityType.SummonSingle:
case MobAbilityType.SummonBulk:
ProcessSummonAbility(mob, ability.Definition);
break;
case MobAbilityType.MeleeAttack:
case MobAbilityType.Cleave:
ProcessMeleeAbility(mob, ability.Definition, target);
break;
case MobAbilityType.ProjectileSingle:
case MobAbilityType.ProjectileAoe:
SpawnProjectile(mob, ability.Definition, target);
break;
case MobAbilityType.GroundAoe:
case MobAbilityType.ConeAttack:
ProcessAoeAbility(mob, ability.Definition, target.X, target.Y);
break;
case MobAbilityType.Poison:
case MobAbilityType.Bleed:
case MobAbilityType.Burn:
ApplyDotToPlayer(mob, ability.Definition, target);
break;
case MobAbilityType.Stun:
case MobAbilityType.Slow:
case MobAbilityType.Root:
case MobAbilityType.Fear:
ApplyStatusToPlayer(ability.Definition, target);
break;
case MobAbilityType.Knockback:
ApplyKnockback(mob, ability.Definition, target);
break;
case MobAbilityType.Pull:
ApplyPull(mob, ability.Definition, target);
break;
case MobAbilityType.HazardZone:
SpawnHazardZone(mob, ability.Definition, target.X, target.Y);
break;
case MobAbilityType.HealSelf:
ProcessHealSelfAbility(mob, ability.Definition);
break;
}
}
private static bool CanUseAbilityNow(MobInstance mob, PlayerInstance target, MobAbilityDefinition definition)
{
int manaCost = Math.Max(0, definition.ManaCost);
if (manaCost > 0 && mob.Mana < manaCost)
{
return false;
}
bool isSummonAbility = definition.AbilityType is MobAbilityType.SummonSingle or MobAbilityType.SummonBulk;
if (!isSummonAbility && definition.Range > 0)
{
float distance = Distance(mob.X, mob.Y, target.X, target.Y);
if (distance > definition.Range)
{
return false;
}
}
return true;
}
private static bool IsImplementedAbilityType(MobAbilityType type)
{
return type switch
{
MobAbilityType.SummonSingle => true,
MobAbilityType.SummonBulk => true,
MobAbilityType.MeleeAttack => true,
MobAbilityType.Cleave => true,
MobAbilityType.ProjectileSingle => true,
MobAbilityType.ProjectileAoe => true,
MobAbilityType.GroundAoe => true,
MobAbilityType.ConeAttack => true,
MobAbilityType.Poison => true,
MobAbilityType.Bleed => true,
MobAbilityType.Burn => true,
MobAbilityType.Stun => true,
MobAbilityType.Slow => true,
MobAbilityType.Root => true,
MobAbilityType.Fear => true,
MobAbilityType.Knockback => true,
MobAbilityType.Pull => true,
MobAbilityType.HazardZone => true,
MobAbilityType.HealSelf => true,
_ => false
};
}
private static void ProcessHealSelfAbility(MobInstance mob, MobAbilityDefinition ability)
{
if (!mob.IsAlive || mob.MaxHealth <= 0) return;
// HealSelf uses the magnitude of BaseDamage so test rows can use negative
// values (for "negative damage = heal" semantics) without being clamped to 1.
int healAmount = Math.Max(1, Math.Abs(ability.BaseDamage));
int oldHealth = mob.Health;
mob.Health = Math.Min(mob.MaxHealth, mob.Health + healAmount);
int actualHealed = mob.Health - oldHealth;
Console.WriteLine(
$"[MobHeal] Mob {mob.Id} ({mob.Name}) HealSelf {ability.Key}: +{actualHealed} (requested={healAmount}) hp={mob.Health}/{mob.MaxHealth}");
}
private void ProcessSummonAbility(MobInstance mob, MobAbilityDefinition ability)
{
if (!ability.SummonMobId.HasValue)
{
Console.WriteLine($"[DungeonSimulation] Summon ability {ability.Name} has no SummonMobId");
return;
}
int summonCount = ability.SummonCount > 0 ? ability.SummonCount : 1;
int summonMobId = ability.SummonMobId.Value;
float summonDistance = ability.DisplacementDistance > 0 ? ability.DisplacementDistance : 50f;
Console.WriteLine($"[DungeonSimulation] {mob.Name} summoning {summonCount}x mob {summonMobId} at distance {summonDistance}");
// Spawn mobs around the summoner
for (int i = 0; i < summonCount; i++)
{
float angle = (float)(Math.PI * 2 * i / summonCount);
float spawnX = mob.X + (float)Math.Cos(angle) * summonDistance;
float spawnY = mob.Y + (float)Math.Sin(angle) * summonDistance;
if (!CanMoveTo(spawnX, spawnY))
{
spawnX = mob.X + (float)Math.Cos(angle) * (summonDistance * 0.5f);
spawnY = mob.Y + (float)Math.Sin(angle) * (summonDistance * 0.5f);
}
RequestMobSummon(summonMobId, spawnX, spawnY, Tier);
}
}
private void LoadMobAbilities(MobInstance mob, DungeonMobDefinition mobDef)
{
if (mobDef.AbilityAssignments == null) return;
if (mobDef.AbilityAssignments.Count > 0)
{
Console.WriteLine(
$"[DungeonSimulation] Mob assignments: Id={mobDef.Id} Name={mobDef.Name} Total={mobDef.AbilityAssignments.Count} Enabled={mobDef.AbilityAssignments.Count(a => a.IsEnabled)}");
}
if (mobDef.Id == 100 || mobDef.Name == "The Bone Lord")
{
Console.WriteLine(
$"[DungeonSimulation] Bone Lord assignments: Id={mobDef.Id} Name={mobDef.Name} Total={mobDef.AbilityAssignments.Count} Enabled={mobDef.AbilityAssignments.Count(a => a.IsEnabled)}");
}
foreach (var assignment in mobDef.AbilityAssignments.Where(a => a.IsEnabled))
{
MobAbilityDefinition? abilityDef = null;
if (_abilityDefinitions != null)
{
_abilityDefinitions.TryGetValue(assignment.AbilityDefinitionId, out abilityDef);
}
abilityDef ??= assignment.AbilityDefinition;
if (abilityDef == null)
{
Console.WriteLine(
$"[DungeonSimulation] Missing ability definition {assignment.AbilityDefinitionId} for mob {mobDef.Id} ({mobDef.Name})");
continue;
}
if (mobDef.Id == 100 || mobDef.Name == "The Bone Lord")
{
Console.WriteLine(
$"[DungeonSimulation] Bone Lord ability loaded: {abilityDef.Id} {abilityDef.Name} ({abilityDef.AbilityType})");
}
mob.Abilities.Add(new MobAbilityState
{
AbilityId = abilityDef.Id,
Definition = abilityDef,
ResolvedAnimationKey = ResolveMappedAnimationKey(assignment.Id, abilityDef),
CooldownRemaining = 0,
Priority = assignment.PriorityOverride ?? abilityDef.Priority,
Phase = assignment.Phase,
MinHpPercent = assignment.MinHpPercent,
MaxHpPercent = assignment.MaxHpPercent
});
}
}
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)
{
int damage = ability.BaseDamage;
string damageTypeKey = ability.DamageTypeKey ?? "physical";
Console.WriteLine($"[MobAttack] Mob {mob.Id} ({mob.Name}) attacking with {ability.Name}: BaseDamage={damage}, Stats.PhysicalDamage={mob.Stats.PhysicalDamage}, Stats.MagicDamage={mob.Stats.MagicDamage}");
var result = CombatCalculator.CalculateMobToPlayerDamage(
mob, target, damageTypeKey, damage, target.Resistances);
Console.WriteLine($"[MobAttack] After calculation: FinalDamage={result.FinalDamage}, Player Armor={target.Armor}, Player Endurance={target.Endurance}");
ApplyDamageToPlayer(mob, target, result.FinalDamage, damageTypeKey, result.WasResisted, result.WasWeakness);
// Cleave hits other nearby players
if (ability.AbilityType == MobAbilityType.Cleave && ability.AoeRadius > 0)
{
foreach (var other in Players.Values.Where(p => p.IsAlive && p.CharacterId != target.CharacterId))
{
if (Distance(mob.X, mob.Y, other.X, other.Y) <= ability.AoeRadius)
{
var otherResult = CombatCalculator.CalculateMobToPlayerDamage(
mob, other, damageTypeKey, damage, other.Resistances);
ApplyDamageToPlayer(mob, other, otherResult.FinalDamage, damageTypeKey, otherResult.WasResisted, otherResult.WasWeakness);
}
}
}
}
private void SpawnProjectile(MobInstance mob, MobAbilityDefinition ability, PlayerInstance target)
{
var projectile = new ProjectileInstance
{
Id = GetNextProjectileId(),
SpawnTick = CurrentTick,
SourceType = ProjectileSource.Mob,
SourceMobId = mob.Id,
AbilityId = ability.Id,
X = mob.X,
Y = mob.Y,
TargetX = target.X,
TargetY = target.Y,
Speed = ability.ProjectileSpeed,
Damage = ability.BaseDamage,
DamageTypeKey = ability.DamageTypeKey,
AoeRadius = ability.AoeRadius,
SpriteKey = ability.ProjectileSprite ?? "projectile_default",
CanHitPlayers = true,
CanHitMobs = false
};
// Calculate direction
float dx = target.X - mob.X;
float dy = target.Y - mob.Y;
float dist = MathF.Sqrt(dx * dx + dy * dy);
if (dist > 0)
{
projectile.VelocityX = (dx / dist) * ability.ProjectileSpeed;
projectile.VelocityY = (dy / dist) * ability.ProjectileSpeed;
}
Projectiles[projectile.Id] = projectile;
IncrementProjectileDiagnostic(ability.Key, d => d.Spawned++);
}
private void UpdateProjectiles()
{
// Debug logging disabled
// if (Projectiles.Count > 0)
// {
// Console.WriteLine($"[UpdateProjectiles] Updating {Projectiles.Count} projectiles. Mobs alive: {Mobs.Values.Count(m => m.IsAlive)}");
// }
var toRemove = new List<int>();
foreach (var projectile in Projectiles.Values)
{
// Move projectile
projectile.X += projectile.VelocityX * TickDelta;
projectile.Y += projectile.VelocityY * TickDelta;
projectile.DistanceTraveled += MathF.Sqrt(
projectile.VelocityX * projectile.VelocityX +
projectile.VelocityY * projectile.VelocityY) * TickDelta;
// Check max range
if (projectile.MaxRange > 0 && projectile.DistanceTraveled > projectile.MaxRange)
{
_pendingProjectileExpiredEvents.Add(new ProjectileExpiredEvent
{
ProjectileId = projectile.Id,
X = projectile.X,
Y = projectile.Y,
Reason = "range"
});
IncrementProjectileDiagnostic(ResolveProjectileAbilityKey(projectile), d => d.ExpiredRange++);
toRemove.Add(projectile.Id);
continue;
}
// Handle player projectiles hitting mobs
if (projectile.SourceType == ProjectileSource.Player && projectile.CanHitMobs)
{
foreach (var mob in Mobs.Values.Where(m => m.IsAlive))
{
float distance = Distance(projectile.X, projectile.Y, mob.X, mob.Y);
// Debug: Log every projectile-mob distance check
//if (Projectiles.Count > 0 && projectile.Id % 10 == 0) // Log every 10th projectile to reduce spam
//{
// Console.WriteLine($"[Projectile {projectile.Id}] Pos: ({projectile.X:F1}, {projectile.Y:F1}), Mob {mob.Id} Pos: ({mob.X:F1}, {mob.Y:F1}), Distance: {distance:F1}");
//}
if (distance < 50) // Increased from 20 to account for projectile speed (15px/tick movement)
{
//Console.WriteLine($"[Projectile {projectile.Id}] HIT mob {mob.Id} at distance {distance:F1}! Damage: {projectile.Damage}");
// Get player instance for damage calculation
PlayerInstance? sourcePlayer = null;
if (Players.TryGetValue(projectile.SourcePlayerId, out var playerInst))
{
sourcePlayer = playerInst;
}
// Apply damage with resistances
int finalDamage = projectile.Damage;
if (sourcePlayer != null)
{
var result = CombatCalculator.CalculatePlayerToMobDamage(
sourcePlayer, mob, projectile.DamageTypeKey, projectile.Damage);
finalDamage = result.FinalDamage;
_pendingDamageEvents.Add(new DamageEvent
{
SourceType = EntityType.Player,
SourceId = (int)sourcePlayer.CharacterId,
TargetType = EntityType.Mob,
TargetId = mob.Id,
Damage = result.FinalDamage,
DamageTypeKey = projectile.DamageTypeKey,
WasResisted = result.WasResisted,
WasWeakness = result.WasWeakness
});
}
else
{
// Fallback if player not found (they disconnected)
_pendingDamageEvents.Add(new DamageEvent
{
SourceType = EntityType.Player,
SourceId = (int)projectile.SourcePlayerId,
TargetType = EntityType.Mob,
TargetId = mob.Id,
Damage = projectile.Damage,
DamageTypeKey = projectile.DamageTypeKey
});
}
mob.Health -= finalDamage;
// Try to recover ammunition
// TODO: Implement arrow recovery - add to LootService or mob's carried items
// For now, skip recovery - will implement in loot system integration
// Check if mob died
if (mob.Health <= 0 && mob.IsAlive)
{
mob.Health = 0;
mob.IsAlive = false;
mob.State = MobState.Dead;
mob.TargetId = null;
mob.CastingAbility = null;
mob.CastTimeRemaining = 0;
mob.CurrentAnimation = mob.GetDirectionalAnimation("death");
_pendingDeathEvents.Add(new DeathEvent
{
EntityType = EntityType.Mob,
EntityId = mob.Id,
EntityName = mob.Name,
KillerType = EntityType.Player,
KillerId = (int)projectile.SourcePlayerId,
KillerName = sourcePlayer?.CharacterName ?? "Unknown",
XpReward = 0 // Will be calculated in handler
});
}
// Add projectile hit event
_pendingProjectileHitEvents.Add(new ProjectileHitEvent
{
ProjectileId = projectile.Id,
TargetType = EntityType.Mob,
TargetId = mob.Id,
X = projectile.X,
Y = projectile.Y
});
IncrementProjectileDiagnostic(ResolveProjectileAbilityKey(projectile), d => d.HitMob++);
toRemove.Add(projectile.Id);
break;
}
}
}
// Handle mob projectiles hitting players
if (projectile.SourceType == ProjectileSource.Mob && projectile.CanHitPlayers)
{
foreach (var player in Players.Values.Where(p => p.IsAlive))
{
if (CurrentTick <= projectile.SpawnTick)
{
continue;
}
if (Distance(projectile.X, projectile.Y, player.X, player.Y) < 50) // Increased from 20 to account for projectile speed
{
// Hit!
if (projectile.AoeRadius > 0)
{
// AOE explosion
ProcessAoeAbilityAtLocation(projectile, projectile.X, projectile.Y);
}
else
{
// Single target
if (Mobs.TryGetValue(projectile.SourceMobId, out var sourceMob))
{
var result = CombatCalculator.CalculateMobToPlayerDamage(
sourceMob, player, projectile.DamageTypeKey, projectile.Damage, player.Resistances);
Console.WriteLine($"[ProjectileHit] Mob {sourceMob.Id} -> Player {player.CharacterId}: ability={ResolveProjectileAbilityKey(projectile)}, damage={result.FinalDamage}, type={projectile.DamageTypeKey}");
ApplyDamageToPlayer(sourceMob, player, result.FinalDamage, projectile.DamageTypeKey, result.WasResisted, result.WasWeakness);
}
}
// Add projectile hit event
_pendingProjectileHitEvents.Add(new ProjectileHitEvent
{
ProjectileId = projectile.Id,
TargetType = EntityType.Player,
TargetId = (int)player.CharacterId,
X = projectile.X,
Y = projectile.Y
});
IncrementProjectileDiagnostic(ResolveProjectileAbilityKey(projectile), d => d.HitPlayer++);
toRemove.Add(projectile.Id);
break;
}
}
}
// Check wall collision
if (!CanMoveTo(projectile.X, projectile.Y))
{
if (projectile.AoeRadius > 0)
{
ProcessAoeAbilityAtLocation(projectile, projectile.X, projectile.Y);
}
_pendingProjectileExpiredEvents.Add(new ProjectileExpiredEvent
{
ProjectileId = projectile.Id,
X = projectile.X,
Y = projectile.Y,
Reason = "wall"
});
IncrementProjectileDiagnostic(ResolveProjectileAbilityKey(projectile), d => d.ExpiredWall++);
toRemove.Add(projectile.Id);
}
}
foreach (var id in toRemove)
{
Projectiles.TryRemove(id, out _);
}
LogProjectileDiagnosticsIfNeeded();
}
private void IncrementProjectileDiagnostic(string abilityKey, Action<ProjectileAbilityDiagnostics> increment)
{
string key = string.IsNullOrWhiteSpace(abilityKey) ? "unknown" : abilityKey;
if (!_projectileDiagnostics.TryGetValue(key, out var diag))
{
diag = new ProjectileAbilityDiagnostics();
_projectileDiagnostics[key] = diag;
}
increment(diag);
}
private string ResolveProjectileAbilityKey(ProjectileInstance projectile)
{
if (projectile.AbilityId > 0 &&
_abilityDefinitions != null &&
_abilityDefinitions.TryGetValue(projectile.AbilityId, out var def))
{
return string.IsNullOrWhiteSpace(def.Key) ? $"ability_{projectile.AbilityId}" : def.Key;
}
return projectile.SourceType == ProjectileSource.Player ? "player_projectile" : "mob_projectile";
}
private void LogProjectileDiagnosticsIfNeeded()
{
if (CurrentTick - _lastProjectileDiagnosticsLogTick < TicksPerSecond * 5) return;
_lastProjectileDiagnosticsLogTick = CurrentTick;
if (_projectileDiagnostics.Count == 0) return;
var parts = _projectileDiagnostics
.OrderBy(kvp => kvp.Key)
.Select(kvp =>
{
var d = kvp.Value;
return $"{kvp.Key}: spawned={d.Spawned}, hitP={d.HitPlayer}, hitM={d.HitMob}, expWall={d.ExpiredWall}, expRange={d.ExpiredRange}";
});
Console.WriteLine($"[ProjectileDiag][Tick {CurrentTick}] {string.Join(" | ", parts)}");
}
private void ProcessAoeAbility(MobInstance mob, MobAbilityDefinition ability, float targetX, float targetY)
{
foreach (var player in Players.Values.Where(p => p.IsAlive))
{
if (Distance(targetX, targetY, player.X, player.Y) <= ability.AoeRadius)
{
var result = CombatCalculator.CalculateMobToPlayerDamage(
mob, player, ability.DamageTypeKey, ability.BaseDamage, player.Resistances);
ApplyDamageToPlayer(mob, player, result.FinalDamage, ability.DamageTypeKey, result.WasResisted, result.WasWeakness);
}
}
}
private void ProcessAoeAbilityAtLocation(ProjectileInstance projectile, float x, float y)
{
if (!Mobs.TryGetValue(projectile.SourceMobId, out var sourceMob)) return;
foreach (var player in Players.Values.Where(p => p.IsAlive))
{
if (Distance(x, y, player.X, player.Y) <= projectile.AoeRadius)
{
var result = CombatCalculator.CalculateMobToPlayerDamage(
sourceMob, player, projectile.DamageTypeKey, projectile.Damage, player.Resistances);
ApplyDamageToPlayer(sourceMob, player, result.FinalDamage, projectile.DamageTypeKey, result.WasResisted, result.WasWeakness);
}
}
}
private void ApplyDotToPlayer(MobInstance mob, MobAbilityDefinition ability, PlayerInstance target)
{
// First apply initial hit if any
if (ability.BaseDamage > 0)
{
var result = CombatCalculator.CalculateMobToPlayerDamage(
mob, target, ability.DamageTypeKey, ability.BaseDamage, target.Resistances);
ApplyDamageToPlayer(mob, target, result.FinalDamage, ability.DamageTypeKey, result.WasResisted, result.WasWeakness);
}
// Apply DOT status effect
string effectType = ability.AbilityType switch
{
MobAbilityType.Poison => "poison",
MobAbilityType.Bleed => "bleed",
MobAbilityType.Burn => "burn",
_ => "dot"
};
target.StatusEffects.Add(new PlayerStatusEffect
{
EffectType = effectType,
Duration = ability.EffectDuration,
TickInterval = ability.DotTickInterval,
NextTickIn = ability.DotTickInterval,
DamagePerTick = ability.DotDamagePerTick,
SourceMobId = mob.Id
});
}
private void ApplyStatusToPlayer(MobAbilityDefinition ability, PlayerInstance target)
{
string effectType = ability.AbilityType switch
{
MobAbilityType.Stun => "stun",
MobAbilityType.Slow => "slow",
MobAbilityType.Root => "root",
MobAbilityType.Fear => "fear",
MobAbilityType.Silence => "silence",
_ => "debuff"
};
target.StatusEffects.Add(new PlayerStatusEffect
{
EffectType = effectType,
Duration = ability.EffectDuration,
Modifier = ability.SpeedModifier
});
}
private void ApplyKnockback(MobInstance mob, MobAbilityDefinition ability, PlayerInstance target)
{
// Apply damage first
if (ability.BaseDamage > 0)
{
var result = CombatCalculator.CalculateMobToPlayerDamage(
mob, target, ability.DamageTypeKey, ability.BaseDamage, target.Resistances);
ApplyDamageToPlayer(mob, target, result.FinalDamage, ability.DamageTypeKey, result.WasResisted, result.WasWeakness);
}
// Calculate knockback direction (away from mob)
float dx = target.X - mob.X;
float dy = target.Y - mob.Y;
float dist = MathF.Sqrt(dx * dx + dy * dy);
if (dist > 0)
{
float newX = target.X + (dx / dist) * ability.DisplacementDistance;
float newY = target.Y + (dy / dist) * ability.DisplacementDistance;
if (CanMoveTo(newX, target.Y)) target.X = newX;
if (CanMoveTo(target.X, newY)) target.Y = newY;
}
}
private void ApplyPull(MobInstance mob, MobAbilityDefinition ability, PlayerInstance target)
{
// Calculate pull direction (toward mob)
float dx = mob.X - target.X;
float dy = mob.Y - target.Y;
float dist = MathF.Sqrt(dx * dx + dy * dy);
if (dist > 0)
{
float pullDist = Math.Min(ability.DisplacementDistance, dist - 30); // Don't pull on top of mob
if (pullDist > 0)
{
float newX = target.X + (dx / dist) * pullDist;
float newY = target.Y + (dy / dist) * pullDist;
if (CanMoveTo(newX, target.Y)) target.X = newX;
if (CanMoveTo(target.X, newY)) target.Y = newY;
}
}
}
private void SpawnHazardZone(MobInstance mob, MobAbilityDefinition ability, float x, float y)
{
var hazard = new HazardZone
{
Id = GetNextHazardId(),
SourceMobId = mob.Id,
X = x,
Y = y,
Radius = ability.AoeRadius,
DamagePerTick = ability.DotDamagePerTick,
TickInterval = ability.DotTickInterval,
Duration = ability.EffectDuration,
NextTickIn = ability.DotTickInterval,
DamageTypeKey = ability.DamageTypeKey,
VisualKey = ability.VisualEffectKey ?? "hazard_default"
};
HazardZones[hazard.Id] = hazard;
}
private void UpdateHazardZones()
{
var toRemove = new List<int>();
foreach (var hazard in HazardZones.Values)
{
hazard.Duration -= TickDelta;
hazard.NextTickIn -= TickDelta;
if (hazard.Duration <= 0)
{
toRemove.Add(hazard.Id);
continue;
}
if (hazard.NextTickIn <= 0)
{
hazard.NextTickIn = hazard.TickInterval;
// Damage players in zone
MobInstance? sourceMob = null;
Mobs.TryGetValue(hazard.SourceMobId, out sourceMob);
foreach (var player in Players.Values.Where(p => p.IsAlive))
{
if (Distance(hazard.X, hazard.Y, player.X, player.Y) <= hazard.Radius)
{
if (sourceMob != null)
{
var result = CombatCalculator.CalculateMobToPlayerDamage(
sourceMob, player, hazard.DamageTypeKey, hazard.DamagePerTick, player.Resistances);
ApplyDamageToPlayer(sourceMob, player, result.FinalDamage, hazard.DamageTypeKey, result.WasResisted, result.WasWeakness);
}
else
{
ApplyDamageToPlayer(null, player, hazard.DamagePerTick, hazard.DamageTypeKey, false, false);
}
}
}
}
}
foreach (var id in toRemove)
{
HazardZones.TryRemove(id, out _);
}
}
private void ApplyDamageToPlayer(MobInstance? mob, PlayerInstance player, int damage, string damageTypeKey, bool wasResisted, bool wasWeakness)
{
if (player.IsInvulnerable) return;
player.Health -= damage;
player.IsInCombat = true;
player.LastCombatTick = CurrentTick;
var damageEvent = new DamageEvent
{
SourceType = EntityType.Mob,
SourceId = mob?.Id ?? 0,
TargetType = EntityType.Player,
TargetId = (int)player.CharacterId,
Damage = damage,
DamageTypeKey = damageTypeKey,
WasResisted = wasResisted,
WasWeakness = wasWeakness
};
Console.WriteLine($"[DamageEvent] Mob {mob?.Id ?? 0} -> Player {player.CharacterId}: {damage} damage ({damageTypeKey})");
_pendingDamageEvents.Add(damageEvent);
if (player.Health <= 0)
{
player.Health = 0;
player.IsAlive = false;
_pendingDeathEvents.Add(new DeathEvent
{
EntityType = EntityType.Player,
EntityId = (int)player.CharacterId,
EntityName = player.CharacterName,
KillerType = EntityType.Mob,
KillerId = mob?.Id ?? 0,
KillerName = mob?.Name ?? "Hazard"
});
}
}
private void UpdatePlayer(PlayerInstance player)
{
// Update status effects first
UpdatePlayerStatusEffects(player);
// If stunned, can't do anything
if (player.IsStunned) return;
// Process movement input (unless rooted or feared)
if (!player.IsRooted && !player.IsFeared)
{
if (player.InputX != 0 || player.InputY != 0)
{
float speedMod = player.GetSpeedModifier();
float speed = player.MoveSpeed * speedMod * TickDelta;
float newX = player.X + player.InputX * speed;
float newY = player.Y + player.InputY * speed;
if (CanMoveTo(newX, player.Y)) player.X = newX;
if (CanMoveTo(player.X, newY)) player.Y = newY;
if (player.InputX != 0 || player.InputY != 0)
{
player.Rotation = MathF.Atan2(player.InputY, player.InputX);
}
}
}
// If feared, run away from nearest mob
if (player.IsFeared)
{
var nearestMob = Mobs.Values
.Where(m => m.IsAlive)
.OrderBy(m => Distance(player.X, player.Y, m.X, m.Y))
.FirstOrDefault();
if (nearestMob != null)
{
float dx = player.X - nearestMob.X;
float dy = player.Y - nearestMob.Y;
float dist = MathF.Sqrt(dx * dx + dy * dy);
if (dist > 0)
{
float speed = player.MoveSpeed * 1.2f * TickDelta; // Run faster when feared
float newX = player.X + (dx / dist) * speed;
float newY = player.Y + (dy / dist) * speed;
if (CanMoveTo(newX, player.Y)) player.X = newX;
if (CanMoveTo(player.X, newY)) player.Y = newY;
}
}
}
// Process attack (unless stunned or silenced for abilities)
if (!player.IsStunned && player.WantsToAttack && player.AttackTargetId.HasValue)
{
TryPlayerAttack(player, player.AttackTargetId.Value);
player.WantsToAttack = false;
}
// Regeneration (out of combat)
if (CurrentTick - player.LastCombatTick > TicksPerSecond * 5)
{
player.IsInCombat = false;
player.Health = Math.Min(player.MaxHealth, player.Health + 0.5f);
player.Mana = Math.Min(player.MaxMana, player.Mana + 0.3f);
player.Stamina = Math.Min(player.MaxStamina, player.Stamina + 1f);
}
}
private void UpdatePlayerStatusEffects(PlayerInstance player)
{
var expired = new List<PlayerStatusEffect>();
foreach (var effect in player.StatusEffects)
{
effect.Duration -= TickDelta;
// Handle DOT
if (effect.DamagePerTick > 0)
{
effect.NextTickIn -= TickDelta;
if (effect.NextTickIn <= 0)
{
if (!player.IsInvulnerable)
{
player.Health -= effect.DamagePerTick;
player.IsInCombat = true;
player.LastCombatTick = CurrentTick;
}
effect.NextTickIn = effect.TickInterval;
if (!player.IsInvulnerable)
{
_pendingDamageEvents.Add(new DamageEvent
{
SourceType = EntityType.Mob,
SourceId = effect.SourceMobId,
TargetType = EntityType.Player,
TargetId = (int)player.CharacterId,
Damage = effect.DamagePerTick,
DamageTypeKey = effect.EffectType
});
}
if (!player.IsInvulnerable && player.Health <= 0)
{
player.Health = 0;
player.IsAlive = false;
string killerName = "DOT";
if (Mobs.TryGetValue(effect.SourceMobId, out var mob))
killerName = mob.Name;
_pendingDeathEvents.Add(new DeathEvent
{
EntityType = EntityType.Player,
EntityId = (int)player.CharacterId,
EntityName = player.CharacterName,
KillerType = EntityType.Mob,
KillerId = effect.SourceMobId,
KillerName = killerName
});
}
}
}
if (effect.Duration <= 0)
expired.Add(effect);
}
foreach (var e in expired)
player.StatusEffects.Remove(e);
}
private void TryPlayerAttack(PlayerInstance player, ulong targetId)
{
if (!Mobs.TryGetValue((int)targetId, out var mob) || !mob.IsAlive)
return;
float dist = Distance(player.X, player.Y, mob.X, mob.Y);
if (dist > 60) return; // Out of range
// Use player's weapon damage type (set when loading equipped weapon)
string damageTypeKey = player.WeaponDamageTypeKey ?? "physical";
int baseDamage = 10 + (int)(player.Strength * 0.5f);
// Calculate damage with mob resistances
var result = CombatCalculator.CalculatePlayerToMobDamage(
player, mob, damageTypeKey, baseDamage);
if (result.WasImmune)
{
// Mob is immune, still add event for client feedback
_pendingDamageEvents.Add(new DamageEvent
{
SourceType = EntityType.Player,
SourceId = (int)player.CharacterId,
TargetType = EntityType.Mob,
TargetId = mob.Id,
Damage = 0,
DamageTypeKey = damageTypeKey,
WasImmune = true
});
return;
}
mob.Health -= result.FinalDamage;
player.IsInCombat = true;
player.LastCombatTick = CurrentTick;
var damageEvent = new DamageEvent
{
SourceType = EntityType.Player,
SourceId = (int)player.CharacterId,
TargetType = EntityType.Mob,
TargetId = mob.Id,
Damage = result.FinalDamage,
DamageTypeKey = damageTypeKey,
WasResisted = result.WasResisted,
WasWeakness = result.WasWeakness
};
Console.WriteLine($"[DamageEvent] Player {player.CharacterId} -> Mob {mob.Id}: {result.FinalDamage} damage ({damageTypeKey})");
_pendingDamageEvents.Add(damageEvent);
if (mob.Health <= 0)
{
mob.Health = 0;
mob.IsAlive = false;
mob.State = MobState.Dead;
mob.TargetId = null;
mob.CastingAbility = null;
mob.CastTimeRemaining = 0;
mob.CurrentAnimation = mob.GetDirectionalAnimation("death");
player.XpGained += mob.Stats.XpReward;
player.MobsKilled++;
_pendingDeathEvents.Add(new DeathEvent
{
EntityType = EntityType.Mob,
EntityId = mob.Id,
EntityName = mob.Name,
KillerType = EntityType.Player,
KillerId = (int)player.CharacterId,
KillerName = player.CharacterName,
XpReward = mob.Stats.XpReward
});
}
}
private void SpawnExit()
{
// Spawn exit at boss room location
if (Layout.Rooms.Count > 0)
{
var bossRoom = Layout.Rooms.LastOrDefault(r => r.Type == DungeonRoomType.Boss)
?? Layout.Rooms[^1];
Layout.ExitPosition = new DungeonPoint(bossRoom.CenterX, bossRoom.CenterY);
}
}
public bool CanMoveTo(float x, float y)
{
int tileX = (int)(x / 32);
int tileY = (int)(y / 32);
return Layout.IsWalkable(tileX, tileY);
}
private void MoveToward(MobInstance mob, float targetX, float targetY, float speed)
{
float dx = targetX - mob.X;
float dy = targetY - mob.Y;
float dist = MathF.Sqrt(dx * dx + dy * dy);
if (dist < 1) return;
float moveAmount = speed * TickDelta;
if (moveAmount > dist) moveAmount = dist;
float newX = mob.X + (dx / dist) * moveAmount;
float newY = mob.Y + (dy / dist) * moveAmount;
if (CanMoveTo(newX, mob.Y)) mob.X = newX;
if (CanMoveTo(mob.X, newY)) mob.Y = newY;
mob.Rotation = MathF.Atan2(dy, dx);
}
private static float Distance(float x1, float y1, float x2, float y2)
{
float dx = x2 - x1;
float dy = y2 - y1;
return MathF.Sqrt(dx * dx + dy * dy);
}
/// <summary>
/// Request a mob to be summoned (will be processed at end of tick)
/// </summary>
public void RequestMobSummon(int mobDefinitionId, float x, float y, int tier)
{
_pendingSummons.Add((mobDefinitionId, x, y, tier));
}
public int AllocateRuntimeMobId()
{
lock (_mobIdLock)
{
if (_nextMobId < 10000)
{
_nextMobId = 10000;
}
while (Mobs.ContainsKey(_nextMobId))
{
_nextMobId++;
}
return _nextMobId++;
}
}
/// <summary>
/// Process all pending summon requests
/// </summary>
private void ProcessPendingSummons()
{
if (_pendingSummons.Count == 0) return;
foreach (var summon in _pendingSummons)
{
SpawnSummonedMob(summon.MobDefinitionId, summon.X, summon.Y, summon.Tier);
}
_pendingSummons.Clear();
}
/// <summary>
/// Spawn a summoned mob at runtime
/// </summary>
private void SpawnSummonedMob(int mobDefinitionId, float x, float y, int tier)
{
if (!_mobDefinitions.TryGetValue(mobDefinitionId, out var mobDef))
{
Console.WriteLine($"[DungeonSimulation] Cannot summon mob {mobDefinitionId} - definition not found");
return;
}
// Use bracket-aware stat scaling
var stats = mobDef.GetStatsForBracket(BracketMin);
// Get sprite config
string? spriteConfig = null;
if (_spriteConfigs != null && _spriteConfigs.TryGetValue(mobDef.Id, out var config) && !string.IsNullOrEmpty(config))
{
spriteConfig = config;
}
else
{
spriteConfig = mobDef.SpriteConfigJson;
}
var mob = new MobInstance
{
Id = AllocateRuntimeMobId(),
DefinitionId = mobDef.Id,
Name = mobDef.Name,
X = x,
Y = y,
SpawnX = x,
SpawnY = y,
Health = stats.MaxHealth,
MaxHealth = stats.MaxHealth,
Mana = mobDef.BaseMana,
MaxMana = mobDef.BaseMana,
IsAlive = true,
Type = mobDef.Type,
Behavior = mobDef.Behavior,
PreferredRange = mobDef.PreferredRange,
FleeThreshold = mobDef.FleeThreshold,
Stats = stats,
State = MobState.Idle,
StateTime = 0,
SpriteConfigJson = spriteConfig,
TintColor = mobDef.TintColor,
Scale = mobDef.Scale,
CurrentAnimation = "idle_down",
FacingDirection = "down",
Phases = mobDef.Phases
};
InitializeMobAbilities(mob, mobDef, stats);
Mobs[mob.Id] = mob;
Console.WriteLine($"[DungeonSimulation] Summoned {mob.Name} (ID {mob.Id}) at ({x}, {y})");
}
/// <summary>
/// Recreate a persisted mob state that is not part of static layout spawns (for example, admin/runtime-spawned mobs).
/// </summary>
public bool TrySpawnMobFromPersistedState(PersistedMobState mobState)
{
if (!_mobDefinitions.TryGetValue(mobState.DefinitionId, out var mobDef))
return false;
var stats = mobDef.GetStatsForBracket(BracketMin);
string? spriteConfig = null;
if (_spriteConfigs != null && _spriteConfigs.TryGetValue(mobDef.Id, out var config) && !string.IsNullOrEmpty(config))
{
spriteConfig = config;
}
else
{
spriteConfig = mobDef.SpriteConfigJson;
}
var mob = new MobInstance
{
Id = mobState.Id,
DefinitionId = mobDef.Id,
Name = mobDef.Name,
X = mobState.X,
Y = mobState.Y,
SpawnX = mobState.X,
SpawnY = mobState.Y,
Health = mobState.IsAlive ? Math.Clamp(mobState.Health, 1, stats.MaxHealth) : 0,
MaxHealth = stats.MaxHealth,
Mana = mobDef.BaseMana,
MaxMana = mobDef.BaseMana,
IsAlive = mobState.IsAlive,
Type = mobDef.Type,
Behavior = mobDef.Behavior,
PreferredRange = mobDef.PreferredRange,
FleeThreshold = mobDef.FleeThreshold,
Stats = stats,
State = mobState.IsAlive ? MobState.Idle : MobState.Dead,
StateTime = 0,
SpriteConfigJson = spriteConfig,
TintColor = mobDef.TintColor,
Scale = mobDef.Scale,
CurrentAnimation = "idle_down",
FacingDirection = "down",
Phases = mobDef.Phases
};
InitializeMobAbilities(mob, mobDef, stats);
Mobs[mob.Id] = mob;
lock (_mobIdLock)
{
if (mob.Id >= _nextMobId)
_nextMobId = mob.Id + 1;
}
return true;
}
private sealed class ProjectileAbilityDiagnostics
{
public long Spawned { get; set; }
public long HitPlayer { get; set; }
public long HitMob { get; set; }
public long ExpiredWall { get; set; }
public long ExpiredRange { get; set; }
}
}