Files
systemrevivalserver/Game/Dungeon/DungeonHandler.cs
T
2025-12-19 10:12:17 -05:00

2906 lines
107 KiB
C#

using System.Collections.Concurrent;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Server.Data;
using Server.Data.Entities;
using Server.Data.Enums;
using Server.Networking;
using Server.Networking.Handling;
using Server.Networking.Messages;
using Server.Services.Auth;
namespace Server.Game.Dungeon;
/// <summary>
/// Handles dungeon crawler game messages via the server's message router
/// Implements IClientMessageHandler for integration with existing infrastructure
/// </summary>
public sealed class DungeonHandler : IClientMessageHandler
{
private readonly ILogger<DungeonHandler> _log;
private readonly ISessionRegistry _sessions;
private readonly IMessageSerializer _ser;
private readonly IServiceScopeFactory _scopeFactory;
// Player state tracking (keyed by connection ID)
private readonly ConcurrentDictionary<Guid, DungeonPlayerSession> _playerSessions = new();
// Active dungeon instances
private readonly ConcurrentDictionary<Guid, DungeonInstance> _dungeons = new();
// Mob definitions cache
private Dictionary<int, DungeonMobDefinition> _mobDefinitions = new();
private bool _initialized = false;
// Tick management
private Timer? _tickTimer;
private long _currentTick = 0;
//LootSystem
private LootService _lootService = null!;
public DungeonHandler(
ILogger<DungeonHandler> log,
ISessionRegistry sessions,
IMessageSerializer ser,
IServiceScopeFactory scopeFactory, LootService lootService)
{
_log = log;
_sessions = sessions;
_ser = ser;
_scopeFactory = scopeFactory;
_lootService = lootService;
}
public IReadOnlyCollection<int> SupportedOpCodes => new[]
{
DungeonOpCodes.HUB_STATE,
DungeonOpCodes.STAT_ALLOCATE,
DungeonOpCodes.DUNGEON_ENTER,
DungeonOpCodes.DUNGEON_LEAVE,
DungeonOpCodes.DUNGEON_INPUT_MOVE,
DungeonOpCodes.DUNGEON_INPUT_ATTACK,
DungeonOpCodes.DUNGEON_INPUT_PICKUP,
DungeonOpCodes.DUNGEON_INPUT_CHEST,
DungeonOpCodes.DUNGEON_INPUT_PORTAL,
DungeonOpCodes.INVENTORY_REQUEST,
DungeonOpCodes.EQUIP_ITEM,
DungeonOpCodes.UNEQUIP_ITEM,
DungeonOpCodes.USE_ITEM,
DungeonOpCodes.DROP_ITEM,
DungeonOpCodes.CHAT_SEND,
DungeonOpCodes.HOTBAR_ASSIGN,
// Loot chest operations
DungeonOpCodes.LOOT_CHEST_OPEN,
DungeonOpCodes.LOOT_CHEST_TAKE_ITEM,
DungeonOpCodes.LOOT_CHEST_TAKE_ALL,
DungeonOpCodes.LOOT_CHEST_CLOSE,
// Dungeon browser
DungeonOpCodes.DUNGEON_LIST_REQUEST,
DungeonOpCodes.DUNGEON_CREATE,
DungeonOpCodes.DUNGEON_JOIN,
// Asset management
DungeonOpCodes.ASSET_MANIFEST_REQUEST
};
public async Task InitializeAsync()
{
if (_initialized) return;
await LoadMobDefinitionsAsync();
await _lootService.InitializeAsync();
// Start tick loop (20 ticks per second)
_tickTimer = new Timer(TickAll, null, 0, 50);
_initialized = true;
_log.LogInformation("DungeonHandler initialized with {MobCount} mob definitions", _mobDefinitions.Count);
}
private async Task LoadMobDefinitionsAsync()
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var mobs = await db.Set<DungeonMobDefinition>()
.Where(m => m.IsEnabled)
.ToListAsync();
if (mobs.Count == 0)
{
// Seed default mobs
var defaults = DefaultDungeonMobs.GetDefaultMobs();
db.Set<DungeonMobDefinition>().AddRange(defaults);
await db.SaveChangesAsync();
mobs = defaults;
_log.LogInformation("Seeded {Count} default mob definitions", defaults.Count);
}
_mobDefinitions = mobs.ToDictionary(m => m.Id);
}
public async Task HandleAsync(int opCode, IConnection connection, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
// Ensure initialized
if (!_initialized)
{
await InitializeAsync();
}
// All dungeon operations require authentication
if (!_sessions.TryGet(connection.Id, out var accountId, out _))
{
await SendErrorAsync(connection, "auth_required", ct);
return;
}
// Get or create player session
var session = await GetOrCreateSessionAsync(connection, accountId, ct);
if (session == null)
{
await SendErrorAsync(connection, "no_character", ct);
return;
}
try
{
switch (opCode)
{
case DungeonOpCodes.HUB_STATE:
await HandleHubStateRequest(connection, session, ct);
break;
case DungeonOpCodes.STAT_ALLOCATE:
await HandleStatAllocate(connection, session, payload, ct);
break;
case DungeonOpCodes.DUNGEON_ENTER:
await HandleDungeonEnter(connection, session, payload, ct);
break;
case DungeonOpCodes.DUNGEON_LEAVE:
await HandleDungeonLeave(connection, session, ct);
break;
case DungeonOpCodes.DUNGEON_INPUT_MOVE:
HandleInputMove(session, payload);
break;
case DungeonOpCodes.DUNGEON_INPUT_ATTACK:
HandleInputAttack(session, payload);
break;
case DungeonOpCodes.DUNGEON_INPUT_PICKUP:
HandleInputPickup(session, payload);
break;
case DungeonOpCodes.DUNGEON_INPUT_CHEST:
HandleInputChest(session, payload);
break;
case DungeonOpCodes.DUNGEON_INPUT_PORTAL:
await HandlePortalUse(connection, session, payload, ct);
break;
case DungeonOpCodes.INVENTORY_REQUEST:
await HandleInventoryRequest(connection, session, ct);
break;
case DungeonOpCodes.EQUIP_ITEM:
await HandleEquipItem(connection, session, payload, ct);
break;
case DungeonOpCodes.UNEQUIP_ITEM:
await HandleUnequipItem(connection, session, payload, ct);
break;
case DungeonOpCodes.USE_ITEM:
await HandleUseItem(connection, session, payload, ct);
break;
case DungeonOpCodes.CHAT_SEND:
await HandleChatSend(connection, session, payload, ct);
break;
case DungeonOpCodes.HOTBAR_ASSIGN:
await HandleHotbarAssign(connection, session, payload, ct);
break;
// Loot chest operations
case DungeonOpCodes.LOOT_CHEST_OPEN:
await HandleLootChestOpen(connection, session, payload, ct);
break;
case DungeonOpCodes.LOOT_CHEST_TAKE_ITEM:
await HandleLootChestTakeItem(connection, session, payload, ct);
break;
case DungeonOpCodes.LOOT_CHEST_TAKE_ALL:
await HandleLootChestTakeAll(connection, session, payload, ct);
break;
case DungeonOpCodes.LOOT_CHEST_CLOSE:
await HandleLootChestClose(connection, session, payload, ct);
break;
// Dungeon browser
case DungeonOpCodes.DUNGEON_LIST_REQUEST:
await HandleDungeonListRequest(connection, session, ct);
break;
case DungeonOpCodes.DUNGEON_CREATE:
await HandleDungeonCreate(connection, session, payload, ct);
break;
case DungeonOpCodes.DUNGEON_JOIN:
await HandleDungeonJoin(connection, session, payload, ct);
break;
case DungeonOpCodes.ASSET_MANIFEST_REQUEST:
await HandleAssetManifestRequest(connection, ct);
break;
}
}
catch (Exception ex)
{
_log.LogError(ex, "Error handling dungeon opcode {OpCode} for account {AccountId}", opCode, accountId);
await SendErrorAsync(connection, "internal_error", ct);
}
}
private async Task<DungeonPlayerSession?> GetOrCreateSessionAsync(IConnection connection, ulong accountId, CancellationToken ct)
{
if (_playerSessions.TryGetValue(connection.Id, out var existing))
{
return existing;
}
// Load character from database
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var character = await db.Set<DungeonCharacter>()
.FirstOrDefaultAsync(c => c.AccountId == accountId && !c.IsDeleted, ct);
if (character == null)
{
// Auto-create a character for this account
character = new DungeonCharacter
{
AccountId = accountId,
Name = $"Hero_{accountId}",
Level = 1,
UnspentStatPoints = 5,
Strength = 1,
Intelligence = 1,
Wisdom = 1,
Endurance = 1,
Dexterity = 1
};
db.Set<DungeonCharacter>().Add(character);
await db.SaveChangesAsync(ct);
_log.LogInformation("Created new dungeon character for account {AccountId}", accountId);
}
var session = new DungeonPlayerSession
{
ConnectionId = connection.Id,
Connection = connection,
AccountId = accountId,
CharacterId = character.Id,
Character = character,
State = PlayerState.InHub
};
_playerSessions[connection.Id] = session;
return session;
}
private async Task HandleHubStateRequest(IConnection connection, DungeonPlayerSession session, CancellationToken ct)
{
var hubState = GetHubState(session.Character);
await SendAsync(connection, DungeonOpCodes.HUB_STATE, hubState, ct);
}
private async Task HandleStatAllocate(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var request = _ser.Deserialize<StatAllocateRequest>(payload);
if (string.IsNullOrEmpty(request.Stat)) return;
var character = session.Character;
if (character.UnspentStatPoints <= 0) return;
switch (request.Stat.ToLower())
{
case "strength": character.Strength++; break;
case "str": character.Strength++; break;
case "intelligence": character.Intelligence++; break;
case "int": character.Intelligence++; break;
case "wisdom": character.Wisdom++; break;
case "wis": character.Wisdom++; break;
case "endurance": character.Endurance++; break;
case "end": character.Endurance++; break;
case "dexterity": character.Dexterity++; break;
case "dex": character.Dexterity++; break;
default: return;
}
character.UnspentStatPoints--;
// Save to database
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
db.Attach(character);
db.Entry(character).Property(c => c.Strength).IsModified = true;
db.Entry(character).Property(c => c.Intelligence).IsModified = true;
db.Entry(character).Property(c => c.Wisdom).IsModified = true;
db.Entry(character).Property(c => c.Endurance).IsModified = true;
db.Entry(character).Property(c => c.Dexterity).IsModified = true;
db.Entry(character).Property(c => c.UnspentStatPoints).IsModified = true;
await db.SaveChangesAsync(ct);
await SendAsync(connection, DungeonOpCodes.HUB_STATE, GetHubState(character), ct);
}
private async Task HandleDungeonEnter(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
if (session.State == PlayerState.InDungeon)
{
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "already_in_dungeon" }, ct);
return;
}
var request = _ser.Deserialize<DungeonEnterRequest>(payload);
int tier = Math.Clamp(request.Tier, 1, 10);
int playerLevel = session.Character.Level;
var (bracketMin, bracketMax) = DungeonInstance.GetLevelBracket(playerLevel);
const int maxPlayersPerDungeon = 20;
// Try to find an existing dungeon of the same tier AND bracket that isn't full
DungeonInstance? instance = null;
Guid dungeonId = Guid.Empty;
foreach (var (id, dungeon) in _dungeons)
{
if (dungeon.Tier == tier &&
dungeon.LevelBracketMin == bracketMin && // Must match bracket
dungeon.Simulation.Phase == DungeonPhase.Active &&
dungeon.Simulation.Players.Count < maxPlayersPerDungeon &&
dungeon.IsJoinWindowOpen) // Use join window instead of hardcoded time
{
instance = dungeon;
dungeonId = id;
_log.LogInformation("Player {Name} joining existing dungeon {Id} (tier {Tier}, bracket {Min}-{Max}, {Players}/{Max} players)",
session.Character.Name, id, tier, bracketMin, bracketMax, dungeon.Simulation.Players.Count, maxPlayersPerDungeon);
// If dungeon is empty, respawn all mobs
if (dungeon.Simulation.Players.Count == 0)
{
RespawnAllMobs(dungeon);
_log.LogInformation("Respawned all mobs in dungeon {Id} (was empty when player joined via Quick Join)", id);
}
break;
}
}
// Create new dungeon if none found
if (instance == null)
{
dungeonId = Guid.NewGuid();
int seed = Random.Shared.Next();
var layout = DungeonGenerator.Generate(seed, tier);
var simulation = new DungeonSimulation(layout, tier, _mobDefinitions, bracketMin);
instance = new DungeonInstance
{
Id = dungeonId,
Tier = tier,
Seed = seed,
Simulation = simulation,
CreatedAt = DateTime.UtcNow,
LevelBracketMin = bracketMin,
LevelBracketMax = bracketMax,
CreatorLevel = playerLevel,
CreatorCharacterId = session.CharacterId,
CreatorName = session.Character.Name
};
_dungeons[dungeonId] = instance;
_log.LogInformation("Player {Name} (Level {Level}) created new dungeon {Id} (tier {Tier}, bracket {Min}-{Max})",
session.Character.Name, playerLevel, dungeonId, tier, bracketMin, bracketMax);
}
// Update last activity
instance.LastPlayerActivity = DateTime.UtcNow;
var layout2 = instance.Simulation.Layout;
// Add player to dungeon
var spawnPos = layout2.Rooms[0]; // Entrance room
var player = new PlayerInstance
{
CharacterId = session.CharacterId,
CharacterName = session.Character.Name,
X = spawnPos.CenterX * 32 + Random.Shared.Next(-20, 20), // Slight offset to avoid stacking
Y = spawnPos.CenterY * 32 + Random.Shared.Next(-20, 20),
Health = session.Character.CurrentHealth,
MaxHealth = DungeonCharacterStats.GetMaxHealth(session.Character),
Mana = session.Character.CurrentMana,
MaxMana = DungeonCharacterStats.GetMaxMana(session.Character),
Stamina = DungeonCharacterStats.GetMaxStamina(session.Character),
MaxStamina = DungeonCharacterStats.GetMaxStamina(session.Character),
MoveSpeed = DungeonCharacterStats.GetMoveSpeed(session.Character),
AttackSpeed = DungeonCharacterStats.GetAttackSpeed(session.Character),
Strength = session.Character.Strength,
Intelligence = session.Character.Intelligence
};
instance.Simulation.Players[session.CharacterId] = player;
// Update session state
session.State = PlayerState.InDungeon;
session.CurrentDungeonId = dungeonId;
session.PlayerInstance = player;
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new
{
ok = true,
dungeonId = dungeonId.ToString(),
tier = instance.Tier,
seed = instance.Seed,
width = layout2.Width,
height = layout2.Height,
tilesRLE = layout2.SerializeTilesRLE(),
spawn = new { x = player.X, y = player.Y },
players = instance.Simulation.Players.Values.Select(p => new
{
id = p.CharacterId,
name = p.CharacterName,
x = p.X,
y = p.Y
}),
mobs = instance.Simulation.Mobs.Values.Select(m => new
{
id = m.Id,
name = m.Name,
x = m.X,
y = m.Y,
health = m.Health,
maxHealth = m.MaxHealth
}),
chests = instance.Simulation.Chests.Values.Select(c => new
{
id = c.Id,
x = c.X,
y = c.Y,
type = c.Type.ToString().ToLower(),
opened = c.IsOpened
}),
portals = instance.Simulation.Portals.Values.Where(p => p.IsActive).Select(p => new
{
id = p.Id,
x = p.X,
y = p.Y,
type = p.Type.ToString().ToLower()
})
}, ct);
}
private async Task HandleDungeonLeave(IConnection connection, DungeonPlayerSession session, CancellationToken ct)
{
if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue)
{
return;
}
await RemoveFromDungeonAsync(session, false, ct);
await SendAsync(connection, DungeonOpCodes.HUB_STATE, GetHubState(session.Character), ct);
}
private void HandleInputMove(DungeonPlayerSession session, ReadOnlyMemory<byte> payload)
{
if (session.PlayerInstance == null) return;
var input = _ser.Deserialize<MoveInput>(payload);
session.PlayerInstance.InputX = input.Dx;
session.PlayerInstance.InputY = input.Dy;
session.PlayerInstance.Rotation = input.AimAngle;
}
private void HandleInputAttack(DungeonPlayerSession session, ReadOnlyMemory<byte> payload)
{
if (session.PlayerInstance == null) return;
if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue) return;
if (!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return;
var input = _ser.Deserialize<AttackInput>(payload);
var player = session.PlayerInstance;
// Find nearest mob in attack direction (within attack range and angle tolerance)
const float attackRange = 60f;
const float angleToleranceRad = 0.8f; // ~45 degrees
MobInstance? bestTarget = null;
float bestDist = float.MaxValue;
foreach (var mob in dungeon.Simulation.Mobs.Values.Where(m => m.IsAlive))
{
float dx = mob.X - player.X;
float dy = mob.Y - player.Y;
float dist = MathF.Sqrt(dx * dx + dy * dy);
if (dist > attackRange) continue;
float angleToMob = MathF.Atan2(dy, dx);
float angleDiff = MathF.Abs(NormalizeAngle(angleToMob - input.AimAngle));
if (angleDiff <= angleToleranceRad && dist < bestDist)
{
bestDist = dist;
bestTarget = mob;
}
}
if (bestTarget != null)
{
player.AttackTargetId = (ulong)bestTarget.Id;
player.WantsToAttack = true;
}
}
private static float NormalizeAngle(float angle)
{
while (angle > MathF.PI) angle -= 2 * MathF.PI;
while (angle < -MathF.PI) angle += 2 * MathF.PI;
return angle;
}
private void HandleInputPickup(DungeonPlayerSession session, ReadOnlyMemory<byte> payload)
{
if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue) return;
if (!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return;
var input = _ser.Deserialize<PickupInput>(payload);
if (dungeon.Simulation.DroppedItems.TryRemove((int)input.ItemId, out var item))
{
// TODO: Add to player inventory
_log.LogDebug("Player {Name} picked up item {ItemId}", session.Character.Name, item.ItemDefinitionId);
}
}
private void HandleInputChest(DungeonPlayerSession session, ReadOnlyMemory<byte> payload)
{
if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue) return;
if (!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return;
var input = _ser.Deserialize<ChestInput>(payload);
if (dungeon.Simulation.Chests.TryGetValue((int)input.ChestId, out var chest) && !chest.IsOpened)
{
chest.IsOpened = true;
// TODO: Generate loot
_log.LogDebug("Player {Name} opened chest {ChestId}", session.Character.Name, chest.Id);
}
}
/// <summary>
/// Handle portal use - instant extraction when player clicks/walks into portal
/// </summary>
private async Task HandlePortalUse(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue) return;
if (!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return;
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
var request = System.Text.Json.JsonSerializer.Deserialize<PortalUseRequest>(json);
if (request == null) return;
// Find the portal
if (!dungeon.Simulation.Portals.TryGetValue(request.PortalId, out var portal))
{
_log.LogWarning("Player {Name} tried to use non-existent portal {Id}", session.Character.Name, request.PortalId);
return;
}
if (!portal.IsActive)
{
_log.LogWarning("Player {Name} tried to use inactive portal {Id}", session.Character.Name, request.PortalId);
return;
}
var player = session.PlayerInstance;
if (player == null) return;
// Check distance to portal (must be within 64 pixels)
float dx = player.X - portal.X;
float dy = player.Y - portal.Y;
float dist = MathF.Sqrt(dx * dx + dy * dy);
if (dist > 64)
{
_log.LogDebug("Player {Name} too far from portal ({Dist})", session.Character.Name, dist);
return;
}
_log.LogInformation("Player {Name} using exit portal", session.Character.Name);
// Send portal used confirmation
await SendAsync(connection, DungeonOpCodes.PORTAL_USED, new
{
portalId = portal.Id,
type = portal.Type.ToString().ToLower()
}, ct);
// Extract player (keep loot, save progress)
await RemoveFromDungeonAsync(session, true, ct);
// Return to hub
await SendAsync(connection, DungeonOpCodes.HUB_STATE, GetHubState(session.Character), ct);
}
/// <summary>
/// Handle hotbar slot assignment - links a hotbar slot to an inventory slot
/// </summary>
private async Task HandleHotbarAssign(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
var request = System.Text.Json.JsonSerializer.Deserialize<HotbarAssignRequest>(json);
if (request == null) return;
// Validate slots
if (request.HotbarSlot < 0 || request.HotbarSlot >= 8) return;
if (request.InventorySlot < 0 || request.InventorySlot >= 30) return;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Check if the inventory slot has a consumable item
var invItem = await db.Set<DungeonCharacterItem>()
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId &&
i.SlotIndex == request.InventorySlot &&
!i.IsEquipped, ct);
if (invItem != null)
{
var itemDef = await db.Set<DungeonItemDefinition>()
.FirstOrDefaultAsync(d => d.Id == invItem.ItemDefinitionId, ct);
// Only allow consumables in hotbar
if (itemDef == null || itemDef.Type != ItemType.Consumable)
{
_log.LogDebug("Cannot assign non-consumable item to hotbar");
return;
}
}
// Find existing hotbar entry for this slot
var existingEntry = await db.Set<DungeonBeltItem>()
.FirstOrDefaultAsync(b => b.CharacterId == session.CharacterId &&
b.SlotIndex == request.HotbarSlot, ct);
if (existingEntry != null)
{
// Update existing
existingEntry.InventorySlotIndex = request.InventorySlot;
}
else
{
// Create new
var newEntry = new DungeonBeltItem
{
CharacterId = session.CharacterId,
SlotIndex = request.HotbarSlot,
InventorySlotIndex = request.InventorySlot
};
db.Set<DungeonBeltItem>().Add(newEntry);
}
await db.SaveChangesAsync(ct);
// Send updated inventory state (includes hotbar)
await HandleInventoryRequest(connection, session, ct);
_log.LogDebug("Player {Name} assigned inventory slot {InvSlot} to hotbar slot {HotbarSlot}",
session.Character.Name, request.InventorySlot, request.HotbarSlot);
}
private void TickAll(object? state)
{
_currentTick++;
foreach (var (dungeonId, instance) in _dungeons)
{
try
{
var result = instance.Simulation.Tick(_currentTick);
// Process death events for loot generation
if (result.DeathEvents != null)
{
foreach (var death in result.DeathEvents)
{
if (death.EntityType == EntityType.Mob && death.KillerType == EntityType.Player)
{
// Fire and forget loot generation (async in sync context)
_ = ProcessMobDeathLootAsync(instance, death);
// Check if this was a boss kill
if (instance.Simulation.Mobs.TryGetValue(death.EntityId, out var killedMob))
{
if (killedMob.Type == MobType.Boss)
{
instance.BossKilled = true;
_log.LogInformation("Boss killed in dungeon {Id}! Dungeon is now cleared.", dungeonId);
}
}
}
else if (death.EntityType == EntityType.Player)
{
// Player died - transfer loot to killer
_ = ProcessPlayerDeathLootTransferAsync(instance, death);
}
}
}
// Send state to all players in this dungeon
var playersInDungeon = _playerSessions.Values
.Where(s => s.CurrentDungeonId == dungeonId && s.State == PlayerState.InDungeon)
.ToList();
// Check if dungeon was just cleared
if (result.Phase == DungeonPhase.Cleared && !instance.ClearedHandled)
{
instance.ClearedHandled = true;
foreach (var session in playersInDungeon)
{
_ = HandleDungeonClearedAsync(session);
}
continue; // Skip normal state updates since we're returning everyone to hub
}
foreach (var session in playersInDungeon)
{
// Check escape completion (5 seconds = 100 ticks)
if (session.IsEscaping && _currentTick - session.EscapeStartTick >= 400)
{
_ = CompleteEscapeAsync(session);
continue;
}
// Check if player died
if (session.PlayerInstance != null && !session.PlayerInstance.IsAlive)
{
_ = HandlePlayerDeathAsync(session);
continue;
}
_ = SendDungeonStateAsync(session, result);
}
// Update last activity if players present
if (playersInDungeon.Count > 0)
{
instance.LastPlayerActivity = DateTime.UtcNow;
}
// Handle empty dungeon logic
if (playersInDungeon.Count == 0)
{
var emptyTime = DateTime.UtcNow - instance.LastPlayerActivity;
// If boss not killed and empty for 10+ minutes, persist to database
if (!instance.BossKilled && !instance.IsPersisted && emptyTime.TotalMinutes >= 10)
{
_ = PersistDungeonAsync(instance, CancellationToken.None);
_dungeons.TryRemove(dungeonId, out _);
_log.LogInformation("Dungeon {Id} persisted after 10 minutes empty", dungeonId);
}
// If boss killed and empty for 5+ minutes, just remove (cleared)
else if (instance.BossKilled && emptyTime.TotalMinutes >= 5)
{
_dungeons.TryRemove(dungeonId, out _);
_log.LogInformation("Cleared dungeon {Id} removed after 5 minutes empty", dungeonId);
}
}
}
catch (Exception ex)
{
_log.LogError(ex, "Error ticking dungeon {DungeonId}", dungeonId);
}
}
}
/// <summary>
/// Process loot when a mob dies - includes normal loot roll plus any carried player loot
/// </summary>
private async Task ProcessMobDeathLootAsync(DungeonInstance dungeon, DeathEvent death)
{
try
{
// Find the mob that died (it's still in the dictionary but marked dead)
if (!dungeon.Simulation.Mobs.TryGetValue(death.EntityId, out var mob))
return;
// Find the player who killed it
var killerSession = _playerSessions.Values
.FirstOrDefault(s => s.CharacterId == (ulong)death.KillerId);
if (killerSession == null)
return;
// Generate loot from the mob's loot tables
var loot = _lootService.GenerateMobLoot(
mob.DefinitionId,
dungeon.Tier,
1.0f
);
// Collect all items to give (normal loot + carried player loot)
var allItems = new List<LootDrop>(loot);
long totalGold = 0;
// Add any carried player loot from player kills
if (mob.HasCarriedLoot)
{
_log.LogInformation("Mob {MobName} was carrying loot from {Count} player kills",
mob.Name, mob.CarriedPlayerLoot.Count);
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
foreach (var carried in mob.CarriedPlayerLoot)
{
totalGold += carried.Gold;
// Convert carried items to LootDrops
foreach (var item in carried.Items)
{
var itemDef = await db.Set<DungeonItemDefinition>()
.FirstOrDefaultAsync(d => d.Id == item.ItemDefinitionId);
if (itemDef != null)
{
allItems.Add(new LootDrop
{
ItemDefinitionId = item.ItemDefinitionId,
Item = itemDef,
Quantity = item.Quantity
});
}
}
}
// Clear the carried loot from the mob
mob.CarriedPlayerLoot.Clear();
}
if (allItems.Count == 0 && totalGold == 0)
return;
// Try to add loot to player's inventory, get overflow
var (addedItems, overflowItems, overflowGold) = await AddLootToInventoryWithOverflowAsync(
killerSession, allItems, totalGold);
// Send loot popup for items that were added directly
if (addedItems.Count > 0)
{
await SendLootPopupAsync(killerSession, addedItems);
}
// If there's overflow, spawn a personal loot chest
if (overflowItems.Count > 0 || overflowGold > 0)
{
await SpawnLootChestAsync(dungeon, killerSession, overflowItems, overflowGold,
mob.X, mob.Y, null, mob.DefinitionId);
}
_log.LogDebug("Player {Player} received {Count} items and {Gold} gold from {Mob}",
killerSession.Character.Name, addedItems.Count, totalGold - overflowGold, mob.Name);
}
catch (Exception ex)
{
_log.LogError(ex, "Error processing loot for mob death");
}
}
/// <summary>
/// Process player death - transfer inventory and 10% gold to killer
/// </summary>
private async Task ProcessPlayerDeathLootTransferAsync(DungeonInstance dungeon, DeathEvent death)
{
try
{
var victimSession = _playerSessions.Values
.FirstOrDefault(s => s.CharacterId == (ulong)death.EntityId);
if (victimSession == null)
return;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Get victim's inventory (non-equipped items only)
var victimInventory = await db.Set<DungeonCharacterItem>()
.Include(i => i.ItemDefinition)
.Where(i => i.CharacterId == victimSession.CharacterId && !i.IsEquipped)
.ToListAsync();
// Calculate gold to transfer (10%)
var victim = await db.DungeonCharacters.FindAsync(victimSession.CharacterId);
if (victim == null) return;
long goldToTransfer = (long)(victim.Gold * 0.10);
// Build the loot package
var lootItems = victimInventory.Select(i => new CarriedLootItem
{
ItemDefinitionId = i.ItemDefinitionId,
Quantity = i.Quantity
}).ToList();
var carriedLoot = new CarriedLoot
{
VictimCharacterId = victimSession.CharacterId,
VictimName = victim.Name,
Items = lootItems,
Gold = goldToTransfer
};
// Remove items from victim's inventory
db.Set<DungeonCharacterItem>().RemoveRange(victimInventory);
// Deduct gold from victim
victim.Gold -= goldToTransfer;
await db.SaveChangesAsync();
// Send notification to victim about what they lost
await SendDeathLootLostNotificationAsync(victimSession, victimInventory, goldToTransfer);
_log.LogInformation("Player {Victim} died to {KillerType} {KillerId}. Lost {ItemCount} items and {Gold} gold",
victim.Name, death.KillerType, death.KillerId, victimInventory.Count, goldToTransfer);
// Transfer loot based on killer type
if (death.KillerType == EntityType.Mob)
{
// Mob killed player - mob now carries the loot
if (dungeon.Simulation.Mobs.TryGetValue(death.KillerId, out var killerMob))
{
killerMob.CarriedPlayerLoot.Add(carriedLoot);
_log.LogInformation("Mob {MobName} is now carrying loot from {Victim}",
killerMob.Name, victim.Name);
}
}
else if (death.KillerType == EntityType.Player)
{
// Player killed player - transfer directly
var killerSession = _playerSessions.Values
.FirstOrDefault(s => s.CharacterId == (ulong)death.KillerId);
if (killerSession != null)
{
await TransferPlayerLootToPlayerAsync(dungeon, killerSession, carriedLoot,
victimSession.PlayerInstance?.X ?? 0, victimSession.PlayerInstance?.Y ?? 0);
}
}
}
catch (Exception ex)
{
_log.LogError(ex, "Error processing player death loot transfer");
}
}
/// <summary>
/// Transfer carried loot directly to a player (from PvP kill)
/// </summary>
private async Task TransferPlayerLootToPlayerAsync(DungeonInstance dungeon, DungeonPlayerSession killer,
CarriedLoot loot, float x, float y)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Convert carried items to LootDrops
var lootDrops = new List<LootDrop>();
foreach (var item in loot.Items)
{
var itemDef = await db.Set<DungeonItemDefinition>()
.FirstOrDefaultAsync(d => d.Id == item.ItemDefinitionId);
if (itemDef != null)
{
lootDrops.Add(new LootDrop
{
ItemDefinitionId = item.ItemDefinitionId,
Item = itemDef,
Quantity = item.Quantity
});
}
}
// Try to add to killer's inventory
var (addedItems, overflowItems, overflowGold) = await AddLootToInventoryWithOverflowAsync(
killer, lootDrops, loot.Gold);
if (addedItems.Count > 0)
{
await SendLootPopupAsync(killer, addedItems);
}
// Spawn chest for overflow
if (overflowItems.Count > 0 || overflowGold > 0)
{
await SpawnLootChestAsync(dungeon, killer, overflowItems, overflowGold, x, y,
loot.VictimCharacterId, null);
}
_log.LogInformation("Player {Killer} received loot from killing {Victim}: {Items} items, {Gold} gold",
killer.Character.Name, loot.VictimName, loot.Items.Count, loot.Gold);
}
/// <summary>
/// Send notification to victim about what they lost on death
/// </summary>
private async Task SendDeathLootLostNotificationAsync(DungeonPlayerSession victim,
List<DungeonCharacterItem> lostItems, long lostGold)
{
var itemsData = lostItems.Select(i => new
{
name = i.ItemDefinition?.Name ?? "Unknown",
quantity = i.Quantity,
rarity = i.ItemDefinition?.Rarity.ToString() ?? "Common"
});
await SendAsync(victim.Connection, DungeonOpCodes.PLAYER_DEATH_LOOT_LOST, new
{
items = itemsData,
gold = lostGold,
message = $"You died and lost {lostItems.Count} items and {lostGold} gold!"
}, CancellationToken.None);
}
/// <summary>
/// Add loot to inventory, returning what was added and what overflowed
/// </summary>
private async Task<(List<LootDrop> added, List<LootDrop> overflow, long overflowGold)>
AddLootToInventoryWithOverflowAsync(DungeonPlayerSession session, List<LootDrop> loot, long gold)
{
var added = new List<LootDrop>();
var overflow = new List<LootDrop>();
long overflowGold = 0;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Get existing inventory items
var existingItems = await db.Set<DungeonCharacterItem>()
.Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped)
.ToListAsync();
// Find used slots
var usedSlots = existingItems.Select(i => i.SlotIndex).ToHashSet();
// Find next available slot
int FindNextSlot()
{
for (int i = 0; i < 30; i++)
{
if (!usedSlots.Contains(i))
{
usedSlots.Add(i);
return i;
}
}
return -1; // Full
}
foreach (var drop in loot)
{
// Check if item is stackable and already exists in inventory
var existingStack = existingItems.FirstOrDefault(i =>
i.ItemDefinitionId == drop.ItemDefinitionId &&
drop.Item.Stackable);
if (existingStack != null && drop.Item.Stackable)
{
int spaceInStack = drop.Item.MaxStack - existingStack.Quantity;
int toAdd = Math.Min(drop.Quantity, spaceInStack);
if (toAdd > 0)
{
existingStack.Quantity += toAdd;
added.Add(new LootDrop
{
ItemDefinitionId = drop.ItemDefinitionId,
Item = drop.Item,
Quantity = toAdd
});
}
int remaining = drop.Quantity - toAdd;
if (remaining > 0)
{
// Overflow the rest
overflow.Add(new LootDrop
{
ItemDefinitionId = drop.ItemDefinitionId,
Item = drop.Item,
Quantity = remaining
});
}
}
else
{
int nextSlot = FindNextSlot();
if (nextSlot >= 0)
{
// Create new inventory entry
var newItem = new DungeonCharacterItem
{
CharacterId = session.CharacterId,
ItemDefinitionId = drop.ItemDefinitionId,
Quantity = drop.Quantity,
SlotIndex = nextSlot
};
db.Set<DungeonCharacterItem>().Add(newItem);
existingItems.Add(newItem);
added.Add(drop);
}
else
{
// Inventory full - overflow
overflow.Add(drop);
}
}
}
// Handle gold
var character = await db.DungeonCharacters.FindAsync(session.CharacterId);
if (character != null)
{
character.Gold += gold;
}
await db.SaveChangesAsync();
return (added, overflow, overflowGold);
}
/// <summary>
/// Spawn a personal loot chest for overflow items
/// </summary>
private async Task SpawnLootChestAsync(DungeonInstance dungeon, DungeonPlayerSession owner,
List<LootDrop> items, long gold, float x, float y, ulong? victimCharacterId, int? victimMobId)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Create database record for auditing
var deathChest = new DeathChest
{
DungeonInstanceId = dungeon.Id,
OwnerCharacterId = owner.CharacterId,
VictimCharacterId = victimCharacterId,
VictimMobDefinitionId = victimMobId,
X = x,
Y = y,
GoldAmount = gold,
CreatedAt = DateTime.UtcNow
};
db.DeathChests.Add(deathChest);
await db.SaveChangesAsync();
// Add items to chest
int slotIndex = 0;
foreach (var item in items)
{
var chestItem = new DeathChestItem
{
DeathChestId = deathChest.Id,
ItemDefinitionId = item.ItemDefinitionId,
Quantity = item.Quantity,
SlotIndex = slotIndex++
};
db.DeathChestItems.Add(chestItem);
}
await db.SaveChangesAsync();
// Create runtime instance
var lootChest = new LootChestInstance
{
Id = dungeon.Simulation.GetNextLootChestId(),
DatabaseId = deathChest.Id,
X = x,
Y = y,
OwnerCharacterId = owner.CharacterId,
Gold = gold,
Items = items.Select((item, idx) => new LootChestItem
{
SlotIndex = idx,
ItemDefinitionId = item.ItemDefinitionId,
Quantity = item.Quantity
}).ToList()
};
dungeon.Simulation.LootChests.TryAdd(lootChest.Id, lootChest);
// Notify the owner about the chest
await SendAsync(owner.Connection, DungeonOpCodes.LOOT_CHEST_SPAWNED, new
{
chestId = lootChest.Id,
x = lootChest.X,
y = lootChest.Y,
itemCount = lootChest.Items.Count,
gold = lootChest.Gold,
message = "A loot chest appeared with your overflow items!"
}, CancellationToken.None);
_log.LogInformation("Spawned loot chest {ChestId} for player {Player} with {Items} items and {Gold} gold at ({X}, {Y})",
lootChest.Id, owner.Character.Name, items.Count, gold, x, y);
}
/// <summary>
/// Adds loot directly to player's inventory in the database (legacy - kept for compatibility)
/// </summary>
private async Task AddLootToInventoryAsync(DungeonPlayerSession session, List<LootDrop> loot)
{
var (_, _, _) = await AddLootToInventoryWithOverflowAsync(session, loot, 0);
}
#region Loot Chest Handlers
/// <summary>
/// Handle opening a loot chest
/// </summary>
private async Task HandleLootChestOpen(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
var request = System.Text.Json.JsonSerializer.Deserialize<LootChestOpenRequest>(json);
if (request == null) return;
if (!session.CurrentDungeonId.HasValue ||
!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
return;
if (!dungeon.Simulation.LootChests.TryGetValue(request.ChestId, out var chest))
{
await SendErrorAsync(connection, "Chest not found", ct);
return;
}
// Check ownership
if (chest.OwnerCharacterId != session.CharacterId)
{
await SendErrorAsync(connection, "This chest doesn't belong to you", ct);
return;
}
// Check distance
if (session.PlayerInstance != null)
{
float dist = MathF.Sqrt(
MathF.Pow(session.PlayerInstance.X - chest.X, 2) +
MathF.Pow(session.PlayerInstance.Y - chest.Y, 2));
if (dist > 96) // Interaction range
{
await SendErrorAsync(connection, "Too far from chest", ct);
return;
}
}
chest.IsOpen = true;
// Load item definitions for display
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var itemDefIds = chest.Items.Select(i => i.ItemDefinitionId).Distinct().ToList();
var itemDefs = await db.Set<DungeonItemDefinition>()
.Where(d => itemDefIds.Contains(d.Id))
.ToDictionaryAsync(d => d.Id, ct);
// Build chest state
var chestItems = new object?[100];
foreach (var item in chest.Items)
{
if (itemDefs.TryGetValue(item.ItemDefinitionId, out var def))
{
chestItems[item.SlotIndex] = new
{
slotIndex = item.SlotIndex,
definitionId = def.Id,
name = def.Name,
description = def.Description,
type = def.Type.ToString(),
rarity = def.Rarity.ToString(),
quantity = item.Quantity,
spriteId = def.SpriteId
};
}
}
await SendAsync(connection, DungeonOpCodes.LOOT_CHEST_STATE, new
{
chestId = chest.Id,
gold = chest.Gold,
items = chestItems,
slots = 100
}, ct);
}
/// <summary>
/// Handle taking a single item from loot chest
/// </summary>
private async Task HandleLootChestTakeItem(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
var request = System.Text.Json.JsonSerializer.Deserialize<LootChestTakeItemRequest>(json);
if (request == null) return;
if (!session.CurrentDungeonId.HasValue ||
!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
return;
if (!dungeon.Simulation.LootChests.TryGetValue(request.ChestId, out var chest))
return;
if (chest.OwnerCharacterId != session.CharacterId)
return;
// Find the item in chest
var chestItem = chest.Items.FirstOrDefault(i => i.SlotIndex == request.SlotIndex);
if (chestItem == null)
{
await SendErrorAsync(connection, "Item not found in chest", ct);
return;
}
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Get item definition
var itemDef = await db.Set<DungeonItemDefinition>()
.FirstOrDefaultAsync(d => d.Id == chestItem.ItemDefinitionId, ct);
if (itemDef == null) return;
// Get player's current inventory
var existingItems = await db.Set<DungeonCharacterItem>()
.Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped)
.ToListAsync(ct);
// Find an available slot
var usedSlots = existingItems.Select(i => i.SlotIndex).ToHashSet();
int targetSlot = request.TargetSlotIndex;
if (targetSlot < 0 || targetSlot >= 30 || usedSlots.Contains(targetSlot))
{
// Find first available slot
targetSlot = -1;
for (int i = 0; i < 30; i++)
{
if (!usedSlots.Contains(i))
{
targetSlot = i;
break;
}
}
}
if (targetSlot < 0)
{
await SendErrorAsync(connection, "Inventory full", ct);
return;
}
// Add to player inventory
var newItem = new DungeonCharacterItem
{
CharacterId = session.CharacterId,
ItemDefinitionId = chestItem.ItemDefinitionId,
Quantity = chestItem.Quantity,
SlotIndex = targetSlot
};
db.Set<DungeonCharacterItem>().Add(newItem);
// Update database chest item as taken
var dbChestItem = await db.DeathChestItems
.FirstOrDefaultAsync(i => i.DeathChestId == chest.DatabaseId &&
i.SlotIndex == request.SlotIndex &&
!i.IsTaken, ct);
if (dbChestItem != null)
{
dbChestItem.IsTaken = true;
dbChestItem.TakenAt = DateTime.UtcNow;
}
await db.SaveChangesAsync(ct);
// Remove from runtime chest
chest.Items.Remove(chestItem);
// Check if chest is now empty
await CheckAndRemoveEmptyChestAsync(db, dungeon, chest, session, ct);
// Send updated states
await HandleInventoryRequest(connection, session, ct);
// Only resend chest state if it still exists
if (!chest.IsEmpty)
{
await HandleLootChestOpen(connection, session, payload, ct);
}
}
/// <summary>
/// Handle taking all items from loot chest
/// </summary>
private async Task HandleLootChestTakeAll(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
var request = System.Text.Json.JsonSerializer.Deserialize<LootChestTakeAllRequest>(json);
if (request == null) return;
if (!session.CurrentDungeonId.HasValue ||
!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
return;
if (!dungeon.Simulation.LootChests.TryGetValue(request.ChestId, out var chest))
return;
if (chest.OwnerCharacterId != session.CharacterId)
return;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Get player's current inventory
var existingItems = await db.Set<DungeonCharacterItem>()
.Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped)
.ToListAsync(ct);
var usedSlots = existingItems.Select(i => i.SlotIndex).ToHashSet();
var itemsTaken = new List<LootChestItem>();
var takenLoot = new List<LootDrop>();
// Try to take each item
foreach (var chestItem in chest.Items.ToList())
{
// Find available slot
int targetSlot = -1;
for (int i = 0; i < 30; i++)
{
if (!usedSlots.Contains(i))
{
targetSlot = i;
usedSlots.Add(i);
break;
}
}
if (targetSlot < 0)
break; // Inventory full
// Get item definition for popup
var itemDef = await db.Set<DungeonItemDefinition>()
.FirstOrDefaultAsync(d => d.Id == chestItem.ItemDefinitionId, ct);
// Add to player inventory
var newItem = new DungeonCharacterItem
{
CharacterId = session.CharacterId,
ItemDefinitionId = chestItem.ItemDefinitionId,
Quantity = chestItem.Quantity,
SlotIndex = targetSlot
};
db.Set<DungeonCharacterItem>().Add(newItem);
// Update database chest item as taken
var dbChestItem = await db.DeathChestItems
.FirstOrDefaultAsync(i => i.DeathChestId == chest.DatabaseId &&
i.SlotIndex == chestItem.SlotIndex &&
!i.IsTaken, ct);
if (dbChestItem != null)
{
dbChestItem.IsTaken = true;
dbChestItem.TakenAt = DateTime.UtcNow;
}
itemsTaken.Add(chestItem);
if (itemDef != null)
{
takenLoot.Add(new LootDrop
{
ItemDefinitionId = chestItem.ItemDefinitionId,
Item = itemDef,
Quantity = chestItem.Quantity
});
}
}
// Take gold
if (chest.Gold > 0)
{
var character = await db.DungeonCharacters.FindAsync(new object[] { session.CharacterId }, ct);
if (character != null)
{
character.Gold += chest.Gold;
// Update database chest
var dbChest = await db.DeathChests.FindAsync(new object[] { chest.DatabaseId }, ct);
if (dbChest != null)
{
dbChest.GoldAmount = 0;
}
chest.Gold = 0;
}
}
await db.SaveChangesAsync(ct);
// Remove taken items from runtime chest
foreach (var item in itemsTaken)
{
chest.Items.Remove(item);
}
// Send loot popup
if (takenLoot.Count > 0)
{
await SendLootPopupAsync(session, takenLoot);
}
// Check if chest is now empty
await CheckAndRemoveEmptyChestAsync(db, dungeon, chest, session, ct);
// Send updated inventory
await HandleInventoryRequest(connection, session, ct);
// If chest still has items, send updated state
if (!chest.IsEmpty)
{
var openPayload = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(
new LootChestOpenRequest { ChestId = request.ChestId });
await HandleLootChestOpen(connection, session, openPayload, ct);
}
}
/// <summary>
/// Handle closing a loot chest
/// </summary>
private async Task HandleLootChestClose(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
var request = System.Text.Json.JsonSerializer.Deserialize<LootChestCloseRequest>(json);
if (request == null) return;
if (!session.CurrentDungeonId.HasValue ||
!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
return;
if (dungeon.Simulation.LootChests.TryGetValue(request.ChestId, out var chest))
{
if (chest.OwnerCharacterId == session.CharacterId)
{
chest.IsOpen = false;
}
}
}
/// <summary>
/// Check if a chest is empty and remove it if so
/// </summary>
private async Task CheckAndRemoveEmptyChestAsync(GameDbContext db, DungeonInstance dungeon, LootChestInstance chest, DungeonPlayerSession owner, CancellationToken ct)
{
if (chest.IsEmpty)
{
// Update database
var dbChest = await db.DeathChests.FindAsync(new object[] { chest.DatabaseId }, ct);
if (dbChest != null)
{
dbChest.IsEmpty = true;
dbChest.EmptiedAt = DateTime.UtcNow;
await db.SaveChangesAsync(ct);
}
// Notify owner that chest is removed
await SendAsync(owner.Connection, DungeonOpCodes.LOOT_CHEST_REMOVED, new
{
chestId = chest.Id
}, ct);
// Remove from runtime
dungeon.Simulation.LootChests.TryRemove(chest.Id, out _);
_log.LogInformation("Loot chest {ChestId} emptied and removed", chest.Id);
}
}
#endregion
#region Dungeon Browser Handlers
/// <summary>
/// Handle request for asset manifest (list of all CDN files for hot-update)
/// </summary>
private async Task HandleAssetManifestRequest(IConnection connection, CancellationToken ct)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var assets = await db.ClientAssets
.Where(a => a.IsEnabled)
.Select(a => new
{
filePath = a.FilePath,
assetType = (int)a.AssetType,
fileHash = a.FileHash,
fileSize = a.FileSize,
version = a.Version,
isRequired = a.IsRequired,
minClientVersion = a.MinClientVersion,
cdnPath = a.CdnPath ?? a.FilePath
})
.ToListAsync(ct);
await SendAsync(connection, DungeonOpCodes.ASSET_MANIFEST_RESPONSE, new
{
cdnBaseUrl = "https://assets.aeternalisgames.com/downloads/",
assets = assets
}, ct);
_log.LogInformation("Sent asset manifest with {Count} files", assets.Count);
}
/// <summary>
/// Handle request for list of available dungeons
/// </summary>
private async Task HandleDungeonListRequest(IConnection connection, DungeonPlayerSession session, CancellationToken ct)
{
var playerLevel = session.Character.Level;
var (bracketMin, bracketMax) = DungeonInstance.GetLevelBracket(playerLevel);
// Get active dungeons in player's bracket
var availableDungeons = _dungeons.Values
.Where(d => d.Simulation.Phase == DungeonPhase.Active &&
!d.BossKilled)
.Select(d => new
{
id = d.Id.ToString(),
tier = d.Tier,
levelBracket = $"{d.LevelBracketMin}-{d.LevelBracketMax}",
bracketMin = d.LevelBracketMin,
bracketMax = d.LevelBracketMax,
creatorName = d.CreatorName,
creatorLevel = d.CreatorLevel,
playerCount = d.Simulation.Players.Count,
maxPlayers = 20,
isJoinWindowOpen = d.IsJoinWindowOpen,
createdAt = d.CreatedAt,
secondsRemaining = d.IsJoinWindowOpen ? (int)(d.JoinWindowEnd - DateTime.UtcNow).TotalSeconds : 0
})
.OrderByDescending(d => d.isJoinWindowOpen)
.ThenByDescending(d => d.createdAt)
.ToList();
// Also load persisted dungeons from database (all of them, not filtered by bracket)
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var persistedDungeons = await db.Set<DungeonPersistence>()
.Where(d => !d.IsCleared)
.Select(d => new
{
id = d.Id.ToString(),
tier = d.Tier,
levelBracket = $"{d.LevelBracketMin}-{d.LevelBracketMax}",
bracketMin = d.LevelBracketMin,
bracketMax = d.LevelBracketMax,
creatorName = d.CreatorName,
creatorLevel = d.CreatorLevel,
playerCount = 0,
maxPlayers = 20,
isJoinWindowOpen = false,
isPersisted = true,
createdAt = d.CreatedAt
})
.ToListAsync(ct);
await SendAsync(connection, DungeonOpCodes.DUNGEON_LIST_RESPONSE, new
{
playerLevel = playerLevel,
bracket = new { min = bracketMin, max = bracketMax },
activeDungeons = availableDungeons,
persistedDungeons = persistedDungeons
}, ct);
}
/// <summary>
/// Handle creating a new dungeon
/// </summary>
private async Task HandleDungeonCreate(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
if (session.State == PlayerState.InDungeon)
{
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "already_in_dungeon" }, ct);
return;
}
var request = _ser.Deserialize<DungeonCreateRequest>(payload);
int tier = Math.Clamp(request.Tier, 1, 10);
int playerLevel = session.Character.Level;
// Get player's natural bracket, but allow them to select different ones within ±50 levels
var (naturalBracketMin, naturalBracketMax) = DungeonInstance.GetLevelBracket(playerLevel);
int bracketMin, bracketMax;
if (request.BracketMin > 0)
{
// Player specified a bracket - validate it's within ±50 levels of player
bracketMin = request.BracketMin;
(bracketMin, bracketMax) = DungeonInstance.GetLevelBracket(bracketMin); // Normalize to valid bracket
// Check if bracket start is within ±50 of player level
if (Math.Abs(bracketMin - playerLevel) > 50)
{
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new
{
ok = false,
error = "bracket_out_of_range",
message = $"You can only create dungeons for brackets within 50 levels of your level ({playerLevel})"
}, ct);
return;
}
}
else
{
// Use player's natural bracket
bracketMin = naturalBracketMin;
bracketMax = naturalBracketMax;
}
var dungeonId = Guid.NewGuid();
int seed = Random.Shared.Next();
var layout = DungeonGenerator.Generate(seed, tier);
var simulation = new DungeonSimulation(layout, tier, _mobDefinitions, bracketMin);
var instance = new DungeonInstance
{
Id = dungeonId,
Tier = tier,
Seed = seed,
Simulation = simulation,
CreatedAt = DateTime.UtcNow,
LevelBracketMin = bracketMin,
LevelBracketMax = bracketMax,
CreatorLevel = playerLevel,
CreatorCharacterId = session.CharacterId,
CreatorName = session.Character.Name
};
_dungeons[dungeonId] = instance;
_log.LogInformation("Player {Name} (Level {Level}) created dungeon {Id} (tier {Tier}, bracket {Min}-{Max})",
session.Character.Name, playerLevel, dungeonId, tier, bracketMin, bracketMax);
// Add player to dungeon
await AddPlayerToDungeonAsync(connection, session, instance, ct);
}
/// <summary>
/// Handle joining an existing dungeon
/// </summary>
private async Task HandleDungeonJoin(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
if (session.State == PlayerState.InDungeon)
{
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "already_in_dungeon" }, ct);
return;
}
var request = _ser.Deserialize<DungeonJoinRequest>(payload);
if (!Guid.TryParse(request.DungeonId, out var dungeonId))
{
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "invalid_dungeon_id" }, ct);
return;
}
int playerLevel = session.Character.Level;
// Check if dungeon is in memory
if (_dungeons.TryGetValue(dungeonId, out var instance))
{
// Validate level bracket
if (!instance.IsLevelInBracket(playerLevel))
{
// Players can join any bracket - just log a warning
_log.LogInformation("Player {Name} (Level {Level}) joining dungeon outside their bracket ({Min}-{Max})",
session.Character.Name, playerLevel, instance.LevelBracketMin, instance.LevelBracketMax);
}
// Check if full
if (instance.Simulation.Players.Count >= 20)
{
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "dungeon_full" }, ct);
return;
}
// Check if boss killed
if (instance.BossKilled)
{
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "dungeon_cleared" }, ct);
return;
}
// If dungeon is currently empty (no players), respawn all mobs
if (instance.Simulation.Players.Count == 0)
{
RespawnAllMobs(instance);
_log.LogInformation("Respawned all mobs in dungeon {Id} (was empty when player joined)", dungeonId);
}
await AddPlayerToDungeonAsync(connection, session, instance, ct);
return;
}
// Try to restore from persistence
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var persisted = await db.Set<DungeonPersistence>().FindAsync(new object[] { dungeonId }, ct);
if (persisted == null)
{
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "dungeon_not_found" }, ct);
return;
}
if (persisted.IsCleared)
{
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "dungeon_cleared" }, ct);
return;
}
// Players can join any bracket - just log if outside their level
if (playerLevel < persisted.LevelBracketMin || playerLevel > persisted.LevelBracketMax)
{
_log.LogInformation("Player {Name} (Level {Level}) joining persisted dungeon outside their bracket ({Min}-{Max})",
session.Character.Name, playerLevel, persisted.LevelBracketMin, persisted.LevelBracketMax);
}
// Restore dungeon from persistence
instance = await RestoreDungeonFromPersistenceAsync(persisted, ct);
if (instance == null)
{
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "restore_failed" }, ct);
return;
}
_dungeons[dungeonId] = instance;
// Remove from persistence table (it's active now)
db.Set<DungeonPersistence>().Remove(persisted);
await db.SaveChangesAsync(ct);
await AddPlayerToDungeonAsync(connection, session, instance, ct);
}
/// <summary>
/// Add a player to a dungeon and send the result
/// </summary>
private async Task AddPlayerToDungeonAsync(IConnection connection, DungeonPlayerSession session, DungeonInstance instance, CancellationToken ct)
{
var layout = instance.Simulation.Layout;
var spawnPos = layout.Rooms[0]; // Entrance room
var player = new PlayerInstance
{
CharacterId = session.CharacterId,
CharacterName = session.Character.Name,
X = spawnPos.CenterX * 32 + Random.Shared.Next(-20, 20),
Y = spawnPos.CenterY * 32 + Random.Shared.Next(-20, 20),
Health = session.Character.CurrentHealth,
MaxHealth = DungeonCharacterStats.GetMaxHealth(session.Character),
Mana = session.Character.CurrentMana,
MaxMana = DungeonCharacterStats.GetMaxMana(session.Character),
Stamina = DungeonCharacterStats.GetMaxStamina(session.Character),
MaxStamina = DungeonCharacterStats.GetMaxStamina(session.Character),
MoveSpeed = DungeonCharacterStats.GetMoveSpeed(session.Character),
AttackSpeed = DungeonCharacterStats.GetAttackSpeed(session.Character),
Strength = session.Character.Strength,
Intelligence = session.Character.Intelligence
};
instance.Simulation.Players[session.CharacterId] = player;
instance.LastPlayerActivity = DateTime.UtcNow;
session.State = PlayerState.InDungeon;
session.CurrentDungeonId = instance.Id;
session.PlayerInstance = player;
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new
{
ok = true,
dungeonId = instance.Id.ToString(),
tier = instance.Tier,
seed = instance.Seed,
levelBracket = new { min = instance.LevelBracketMin, max = instance.LevelBracketMax },
width = layout.Width,
height = layout.Height,
tilesRLE = layout.SerializeTilesRLE(),
spawn = new { x = player.X, y = player.Y },
players = instance.Simulation.Players.Values.Select(p => new
{
id = p.CharacterId,
name = p.CharacterName,
x = p.X,
y = p.Y
}),
mobs = instance.Simulation.Mobs.Values.Where(m => m.IsAlive).Select(m => new
{
id = m.Id,
name = m.Name,
x = m.X,
y = m.Y,
health = m.Health,
maxHealth = m.MaxHealth,
scenePath = m.ScenePath,
tintColor = m.TintColor,
scale = m.Scale
}),
chests = instance.Simulation.Chests.Values.Select(c => new
{
id = c.Id,
x = c.X,
y = c.Y,
type = c.Type.ToString().ToLower(),
opened = c.IsOpened
}),
portals = instance.Simulation.Portals.Values.Where(p => p.IsActive).Select(p => new
{
id = p.Id,
x = p.X,
y = p.Y,
type = p.Type.ToString().ToLower()
})
}, ct);
_log.LogInformation("Player {Name} (Level {Level}) joined dungeon {Id}",
session.Character.Name, session.Character.Level, instance.Id);
}
/// <summary>
/// Restore a dungeon from persistence
/// </summary>
private async Task<DungeonInstance?> RestoreDungeonFromPersistenceAsync(DungeonPersistence persisted, CancellationToken ct)
{
try
{
var layout = DungeonGenerator.Generate(persisted.Seed, persisted.Tier);
var simulation = new DungeonSimulation(layout, persisted.Tier, _mobDefinitions, persisted.LevelBracketMin);
// NOTE: We intentionally do NOT restore mob state here.
// When a dungeon is restored (all players left), ALL mobs respawn fresh.
// This gives the dungeon a "reset" behavior when empty.
// The mob state is preserved in persistence for potential future use,
// but on restore we use the freshly generated mobs from DungeonSimulation.
_log.LogInformation("Dungeon {Id} restored with all mobs respawned (was persisted with {MobCount} mob states)",
persisted.Id,
string.IsNullOrEmpty(persisted.MobStateJson) ? 0 : "saved");
// Restore chest state if available (chests stay opened)
if (!string.IsNullOrEmpty(persisted.ChestStateJson))
{
var chestStates = System.Text.Json.JsonSerializer.Deserialize<List<PersistedChestState>>(persisted.ChestStateJson);
if (chestStates != null)
{
foreach (var chestState in chestStates)
{
if (simulation.Chests.TryGetValue(chestState.Id, out var chest))
{
chest.IsOpened = chestState.IsOpened;
}
}
}
}
var instance = new DungeonInstance
{
Id = persisted.Id,
Tier = persisted.Tier,
Seed = persisted.Seed,
Simulation = simulation,
CreatedAt = persisted.CreatedAt,
LevelBracketMin = persisted.LevelBracketMin,
LevelBracketMax = persisted.LevelBracketMax,
CreatorLevel = persisted.CreatorLevel,
CreatorCharacterId = persisted.CreatorCharacterId,
CreatorName = persisted.CreatorName,
BossKilled = persisted.BossKilled,
IsPersisted = false,
LastPlayerActivity = DateTime.UtcNow
};
_log.LogInformation("Restored dungeon {Id} from persistence with fresh mobs", persisted.Id);
return instance;
}
catch (Exception ex)
{
_log.LogError(ex, "Failed to restore dungeon {Id} from persistence", persisted.Id);
return null;
}
}
/// <summary>
/// Respawn all mobs in a dungeon (called when dungeon was empty and player rejoins)
/// </summary>
private void RespawnAllMobs(DungeonInstance instance)
{
// Create a fresh simulation with the same parameters
var layout = DungeonGenerator.Generate(instance.Seed, instance.Tier);
var freshSimulation = new DungeonSimulation(layout, instance.Tier, _mobDefinitions, instance.LevelBracketMin);
// Copy fresh mobs to the existing simulation
instance.Simulation.Mobs.Clear();
foreach (var mob in freshSimulation.Mobs)
{
instance.Simulation.Mobs.TryAdd(mob.Key, mob.Value);
}
// Reset chest states (they respawn closed)
foreach (var chest in instance.Simulation.Chests.Values)
{
chest.IsOpened = false;
}
// Clear any loot chests (personal drops don't persist through respawn)
instance.Simulation.LootChests.Clear();
// Clear dropped items
instance.Simulation.DroppedItems.Clear();
// Reset portals (exit portal should be inactive until boss killed)
foreach (var portal in instance.Simulation.Portals.Values)
{
if (portal.Type == PortalType.Exit)
{
portal.IsActive = false;
}
}
_log.LogDebug("Respawned {MobCount} mobs in dungeon {Id}", instance.Simulation.Mobs.Count, instance.Id);
}
/// <summary>
/// Persist a dungeon to SQL (called when empty for 10 minutes)
/// </summary>
private async Task PersistDungeonAsync(DungeonInstance instance, CancellationToken ct)
{
if (instance.IsPersisted || instance.BossKilled) return;
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Serialize mob state
var mobStates = instance.Simulation.Mobs.Values.Select(m => new PersistedMobState
{
Id = m.Id,
DefinitionId = m.DefinitionId,
X = m.X,
Y = m.Y,
Health = m.Health,
IsAlive = m.IsAlive
}).ToList();
// Serialize chest state
var chestStates = instance.Simulation.Chests.Values.Select(c => new PersistedChestState
{
Id = c.Id,
IsOpened = c.IsOpened
}).ToList();
var persisted = new DungeonPersistence
{
Id = instance.Id,
Tier = instance.Tier,
Seed = instance.Seed,
LevelBracketMin = instance.LevelBracketMin,
LevelBracketMax = instance.LevelBracketMax,
CreatorCharacterId = instance.CreatorCharacterId,
CreatorName = instance.CreatorName,
CreatorLevel = instance.CreatorLevel,
CreatedAt = instance.CreatedAt,
LastActivity = instance.LastPlayerActivity,
PersistedAt = DateTime.UtcNow,
BossKilled = instance.BossKilled,
MobStateJson = System.Text.Json.JsonSerializer.Serialize(mobStates),
ChestStateJson = System.Text.Json.JsonSerializer.Serialize(chestStates)
};
db.Set<DungeonPersistence>().Add(persisted);
await db.SaveChangesAsync(ct);
instance.IsPersisted = true;
_log.LogInformation("Persisted dungeon {Id} to database", instance.Id);
}
catch (Exception ex)
{
_log.LogError(ex, "Failed to persist dungeon {Id}", instance.Id);
}
}
#endregion
/// <summary>
/// Sends loot popup to client showing what they received
/// </summary>
private async Task SendLootPopupAsync(DungeonPlayerSession session, List<LootDrop> loot)
{
var lootData = loot.Select(l => new
{
id = l.ItemDefinitionId,
name = l.Item.Name,
description = l.Item.Description,
type = l.Item.Type.ToString(),
rarity = l.Item.Rarity.ToString(),
quantity = l.Quantity,
spriteId = l.Item.SpriteId,
// Include stats for display
armor = l.Item.Armor,
minDamage = l.Item.MinDamage,
maxDamage = l.Item.MaxDamage,
bonusHealth = l.Item.BonusHealth,
bonusMana = l.Item.BonusMana,
healAmount = l.Item.HealAmount,
manaRestore = l.Item.ManaRestore
});
await SendAsync(session.Connection, DungeonOpCodes.LOOT_RECEIVED, new
{
items = lootData
}, CancellationToken.None);
}
/// <summary>
/// Handle inventory request - sends current inventory and equipment
/// </summary>
private async Task HandleInventoryRequest(IConnection connection, DungeonPlayerSession session, CancellationToken ct)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Get all inventory items
var inventoryItems = await db.Set<DungeonCharacterItem>()
.Where(i => i.CharacterId == session.CharacterId)
.ToListAsync(ct);
// Get item definitions for all items
var itemDefIds = inventoryItems.Select(i => i.ItemDefinitionId).Distinct().ToList();
var itemDefs = await db.Set<DungeonItemDefinition>()
.Where(d => itemDefIds.Contains(d.Id))
.ToDictionaryAsync(d => d.Id, ct);
// Build inventory array (30 slots, null for empty)
var items = new object?[30];
foreach (var invItem in inventoryItems.Where(i => !i.IsEquipped))
{
if (invItem.SlotIndex >= 0 && invItem.SlotIndex < 30 && itemDefs.TryGetValue(invItem.ItemDefinitionId, out var def))
{
items[invItem.SlotIndex] = new
{
id = invItem.Id,
definitionId = def.Id,
name = def.Name,
description = def.Description,
type = def.Type.ToString(),
rarity = def.Rarity.ToString(),
quantity = invItem.Quantity,
minDamage = def.MinDamage,
maxDamage = def.MaxDamage,
armor = def.Armor,
bonusHealth = def.BonusHealth,
bonusMana = def.BonusMana,
healAmount = def.HealAmount,
manaRestore = def.ManaRestore,
spriteId = def.SpriteId
};
}
}
// Load hotbar assignments
var hotbarItems = await db.Set<DungeonBeltItem>()
.Where(b => b.CharacterId == session.CharacterId)
.OrderBy(b => b.SlotIndex)
.ToListAsync(ct);
var hotbar = new object?[8];
foreach (var belt in hotbarItems)
{
if (belt.SlotIndex >= 0 && belt.SlotIndex < 8)
{
hotbar[belt.SlotIndex] = new
{
inventory_slot = belt.InventorySlotIndex
};
}
}
// Build equipment map - using your actual enum names
var equipment = new Dictionary<string, object?>();
foreach (var equippedItem in inventoryItems.Where(i => i.IsEquipped))
{
if (itemDefs.TryGetValue(equippedItem.ItemDefinitionId, out var def))
{
// Map enum to client slot names
var slotName = equippedItem.EquipSlot switch
{
DungeonEquipmentSlot.MainHand => "weapon",
DungeonEquipmentSlot.OffHand => "offhand",
DungeonEquipmentSlot.Head => "helm",
DungeonEquipmentSlot.Chest => "chest",
DungeonEquipmentSlot.Legs => "legs",
DungeonEquipmentSlot.Boots => "boots",
DungeonEquipmentSlot.Gloves => "gloves",
DungeonEquipmentSlot.Accessory1 => "ring1",
DungeonEquipmentSlot.Accessory2 => "ring2",
_ => "unknown"
};
equipment[slotName] = new
{
id = equippedItem.Id,
definitionId = def.Id,
name = def.Name,
description = def.Description,
type = def.Type.ToString(),
rarity = def.Rarity.ToString(),
minDamage = def.MinDamage,
maxDamage = def.MaxDamage,
armor = def.Armor,
bonusHealth = def.BonusHealth,
bonusMana = def.BonusMana
};
}
}
await SendAsync(connection, DungeonOpCodes.INVENTORY_STATE, new
{
items,
equipment,
hotbar,
}, ct);
}
/// <summary>
/// Handle equip item request
/// </summary>
private async Task HandleEquipItem(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
var request = System.Text.Json.JsonSerializer.Deserialize<EquipItemRequest>(json);
if (request == null) return;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Get the item to equip
var item = await db.Set<DungeonCharacterItem>()
.Include(i => i.ItemDefinition)
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId && i.SlotIndex == request.SlotIndex && !i.IsEquipped, ct);
if (item?.ItemDefinition == null) return;
// Determine equipment slot based on item type
var equipSlot = GetEquipSlotForItem(item.ItemDefinition);
if (equipSlot == null)
{
_log.LogWarning("Cannot equip item {ItemName} - no valid equip slot", item.ItemDefinition.Name);
return;
}
// Unequip any existing item in that slot
var existingEquipped = await db.Set<DungeonCharacterItem>()
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId && i.IsEquipped && i.EquipSlot == equipSlot, ct);
if (existingEquipped != null)
{
existingEquipped.IsEquipped = false;
existingEquipped.EquipSlot = null;
// Find first empty inventory slot
var usedSlots = await db.Set<DungeonCharacterItem>()
.Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped)
.Select(i => i.SlotIndex)
.ToListAsync(ct);
existingEquipped.SlotIndex = Enumerable.Range(0, 30).FirstOrDefault(s => !usedSlots.Contains(s));
}
// Equip the new item
item.IsEquipped = true;
item.EquipSlot = equipSlot;
item.SlotIndex = -1; // Not in regular inventory
await db.SaveChangesAsync(ct);
// Send updated inventory
await HandleInventoryRequest(connection, session, ct);
}
/// <summary>
/// Handle unequip item request
/// </summary>
private async Task HandleUnequipItem(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
var request = System.Text.Json.JsonSerializer.Deserialize<UnequipItemRequest>(json);
if (request == null) return;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Map client slot name to enum
var equipSlot = request.Slot?.ToLower() switch
{
"weapon" => DungeonEquipmentSlot.MainHand,
"offhand" => DungeonEquipmentSlot.OffHand,
"helm" => DungeonEquipmentSlot.Head,
"chest" => DungeonEquipmentSlot.Chest,
"legs" => DungeonEquipmentSlot.Legs,
"boots" => DungeonEquipmentSlot.Boots,
"gloves" => DungeonEquipmentSlot.Gloves,
"ring1" => DungeonEquipmentSlot.Accessory1,
"ring2" => DungeonEquipmentSlot.Accessory2,
_ => (DungeonEquipmentSlot?)null
};
if (equipSlot == null) return;
var equippedItem = await db.Set<DungeonCharacterItem>()
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId && i.IsEquipped && i.EquipSlot == equipSlot, ct);
if (equippedItem == null) return;
// Find first empty inventory slot
var usedSlots = await db.Set<DungeonCharacterItem>()
.Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped)
.Select(i => i.SlotIndex)
.ToListAsync(ct);
if (usedSlots.Count >= 30)
{
_log.LogWarning("Cannot unequip - inventory full");
return;
}
var emptySlot = Enumerable.Range(0, 30).FirstOrDefault(s => !usedSlots.Contains(s));
equippedItem.IsEquipped = false;
equippedItem.EquipSlot = null;
equippedItem.SlotIndex = emptySlot;
await db.SaveChangesAsync(ct);
// Send updated inventory
await HandleInventoryRequest(connection, session, ct);
}
/// <summary>
/// Handle use item request (consumables)
/// </summary>
private async Task HandleUseItem(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
var request = System.Text.Json.JsonSerializer.Deserialize<UseItemRequest>(json);
if (request == null) return;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var item = await db.Set<DungeonCharacterItem>()
.Include(i => i.ItemDefinition)
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId && i.SlotIndex == request.SlotIndex && !i.IsEquipped, ct);
if (item?.ItemDefinition == null) return;
// Only consumables can be used
if (item.ItemDefinition.Type != ItemType.Consumable) return;
// Apply effects
if (session.PlayerInstance != null)
{
if (item.ItemDefinition.HealAmount > 0)
{
session.PlayerInstance.Health = Math.Min(
session.PlayerInstance.Health + item.ItemDefinition.HealAmount,
session.PlayerInstance.MaxHealth
);
}
if (item.ItemDefinition.ManaRestore > 0)
{
session.PlayerInstance.Mana = Math.Min(
session.PlayerInstance.Mana + item.ItemDefinition.ManaRestore,
session.PlayerInstance.MaxMana
);
}
}
// Decrease quantity or remove
item.Quantity--;
if (item.Quantity <= 0)
{
db.Set<DungeonCharacterItem>().Remove(item);
}
await db.SaveChangesAsync(ct);
// Send updated inventory
await HandleInventoryRequest(connection, session, ct);
}
private DungeonEquipmentSlot? GetEquipSlotForItem(DungeonItemDefinition item)
{
return item.Type switch
{
ItemType.Weapon => item.EquipSlot ?? DungeonEquipmentSlot.MainHand,
ItemType.Armor => item.EquipSlot ?? DungeonEquipmentSlot.Chest,
ItemType.Accessory => DungeonEquipmentSlot.Accessory1,
_ => null
};
}
// Request DTOs
private class EquipItemRequest { public int SlotIndex { get; set; } }
private class UnequipItemRequest { public string Slot { get; set; } = ""; }
private class UseItemRequest { public int SlotIndex { get; set; } }
private async Task SendDungeonStateAsync(DungeonPlayerSession session, TickResult? tickResult)
{
var dungeon = _dungeons.GetValueOrDefault(session.CurrentDungeonId!.Value);
if (dungeon == null) return;
var sim = dungeon.Simulation;
var state = new
{
tick = _currentTick,
phase = sim.Phase.ToString().ToLower(),
// NOTE: tiles are NOT sent every tick - they're static and sent once on DUNGEON_ENTER_RESULT
players = sim.Players.Values.Select(p => new
{
id = p.CharacterId,
name = p.CharacterName,
x = p.X,
y = p.Y,
rotation = p.Rotation,
health = (int)p.Health,
maxHealth = (int)p.MaxHealth,
mana = (int)p.Mana,
maxMana = (int)p.MaxMana,
stamina = (int)p.Stamina,
maxStamina = (int)p.MaxStamina,
isAlive = p.IsAlive,
isInCombat = p.IsInCombat
}),
mobs = sim.Mobs.Values.Where(m => m.IsAlive).Select(m => new
{
id = m.Id,
name = m.Name,
x = m.X,
y = m.Y,
rotation = m.Rotation,
health = m.Health,
maxHealth = m.MaxHealth,
state = m.State.ToString().ToLower(),
scenePath = m.ScenePath,
tintColor = m.TintColor,
scale = m.Scale
}),
chests = sim.Chests.Values.Select(c => new
{
id = c.Id,
x = c.X,
y = c.Y,
opened = c.IsOpened
}),
droppedItems = sim.DroppedItems.Values.Select(i => new
{
id = i.Id,
itemId = i.ItemDefinitionId,
quantity = i.Quantity,
x = i.X,
y = i.Y
}),
portals = sim.Portals.Values.Where(p => p.IsActive).Select(p => new
{
id = p.Id,
x = p.X,
y = p.Y,
type = p.Type.ToString().ToLower()
}),
// Loot chests are only visible to their owner
lootChests = sim.LootChests.Values
.Where(c => c.OwnerCharacterId == session.CharacterId)
.Select(c => new
{
id = c.Id,
x = c.X,
y = c.Y,
itemCount = c.Items.Count,
gold = c.Gold,
isOpen = c.IsOpen
}),
events = tickResult == null ? null : new
{
damage = tickResult.DamageEvents.Select(e => new
{
sourceType = e.SourceType.ToString().ToLower(),
sourceId = e.SourceId,
targetType = e.TargetType.ToString().ToLower(),
targetId = e.TargetId,
damage = e.Damage
}),
deaths = tickResult.DeathEvents.Select(e => new
{
entityType = e.EntityType.ToString().ToLower(),
entityId = e.EntityId,
entityName = e.EntityName,
killerType = e.KillerType.ToString().ToLower(),
killerId = e.KillerId,
killerName = e.KillerName,
xp = e.XpReward
})
},
exitPosition = sim.Layout.ExitPosition != null ? new
{
x = sim.Layout.ExitPosition.Value.X * 32 + 16,
y = sim.Layout.ExitPosition.Value.Y * 32 + 16
} : null
};
await SendAsync(session.Connection, DungeonOpCodes.DUNGEON_STATE, state, CancellationToken.None);
}
private async Task CompleteEscapeAsync(DungeonPlayerSession session)
{
session.IsEscaping = false;
await SendAsync(session.Connection, DungeonOpCodes.ESCAPE_SUCCESS, new { }, CancellationToken.None);
await RemoveFromDungeonAsync(session, true, CancellationToken.None);
await SendAsync(session.Connection, DungeonOpCodes.HUB_STATE, GetHubState(session.Character), CancellationToken.None);
}
/// <summary>
/// Handle dungeon cleared - return player to hub with all loot
/// </summary>
private async Task HandleDungeonClearedAsync(DungeonPlayerSession session)
{
_log.LogInformation("Dungeon cleared! Returning player {Name} to hub", session.Character.Name);
// Send dungeon cleared notification
await SendAsync(session.Connection, DungeonOpCodes.DUNGEON_STATE, new
{
phase = "cleared",
message = "Dungeon cleared! All enemies defeated."
}, CancellationToken.None);
// Small delay to let client see the message
await Task.Delay(2000);
// Remove from dungeon (extracted = true, so they keep XP and loot)
await RemoveFromDungeonAsync(session, true, CancellationToken.None);
// Send hub state
await SendAsync(session.Connection, DungeonOpCodes.HUB_STATE, GetHubState(session.Character), CancellationToken.None);
}
private async Task HandlePlayerDeathAsync(DungeonPlayerSession session)
{
await RemoveFromDungeonAsync(session, false, CancellationToken.None);
// Reset health on death
session.Character.CurrentHealth = DungeonCharacterStats.GetMaxHealth(session.Character);
session.Character.CurrentMana = DungeonCharacterStats.GetMaxMana(session.Character);
session.Character.TotalDeaths++;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
db.Attach(session.Character);
db.Entry(session.Character).State = EntityState.Modified;
await db.SaveChangesAsync();
await SendAsync(session.Connection, DungeonOpCodes.HUB_STATE, GetHubState(session.Character), CancellationToken.None);
}
private async Task RemoveFromDungeonAsync(DungeonPlayerSession session, bool extracted, CancellationToken ct)
{
if (!session.CurrentDungeonId.HasValue) return;
if (_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
{
dungeon.Simulation.Players.TryRemove(session.CharacterId, out var player);
if (player != null)
{
await SaveCharacterStateAsync(session.Character, player, extracted, ct);
}
}
session.State = PlayerState.InHub;
session.CurrentDungeonId = null;
session.PlayerInstance = null;
session.IsEscaping = false;
}
private async Task SaveCharacterStateAsync(DungeonCharacter character, PlayerInstance player, bool extracted, CancellationToken ct)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Add XP earned
character.Experience += player.XpGained;
character.TotalKills += player.MobsKilled;
character.PlayersKilled += player.PlayersKilled;
if (extracted)
{
character.DungeonsCompleted++;
character.CurrentHealth = (int)player.Health;
character.CurrentMana = (int)player.Mana;
}
else
{
character.TotalDeaths++;
character.CurrentHealth = DungeonCharacterStats.GetMaxHealth(character);
character.CurrentMana = DungeonCharacterStats.GetMaxMana(character);
}
// Check for level up
while (character.Experience >= LevelSystem.GetTotalXpForLevel(character.Level + 1))
{
character.Level++;
character.UnspentStatPoints += 5;
}
character.LastPlayedAt = DateTime.UtcNow;
db.Attach(character);
db.Entry(character).State = EntityState.Modified;
await db.SaveChangesAsync(ct);
_log.LogInformation("Saved character {Name}: Level {Level}, XP {Xp}, Extracted={Extracted}",
character.Name, character.Level, character.Experience, extracted);
}
private object GetHubState(DungeonCharacter character)
{
return new
{
character = new
{
id = character.Id,
name = character.Name,
level = character.Level,
xp = character.Experience,
xpNext = LevelSystem.GetXpForLevel(character.Level + 1),
unspentPoints = character.UnspentStatPoints,
strength = character.Strength,
intelligence = character.Intelligence,
wisdom = character.Wisdom,
endurance = character.Endurance,
dexterity = character.Dexterity,
maxHealth = DungeonCharacterStats.GetMaxHealth(character),
maxMana = DungeonCharacterStats.GetMaxMana(character),
maxStamina = DungeonCharacterStats.GetMaxStamina(character),
gold = character.Gold
}
};
}
private async Task SendAsync(IConnection connection, int opCode, object payload, CancellationToken ct)
{
try
{
var payloadBytes = _ser.Serialize(payload);
var msg = new ServerMessage(opCode, payloadBytes);
var wire = _ser.Serialize(msg);
await connection.SendAsync(wire, ct);
}
catch (Exception ex)
{
_log.LogWarning(ex, "Failed to send message to connection {Id}", connection.Id);
}
}
private async Task SendErrorAsync(IConnection connection, string error, CancellationToken ct)
{
await SendAsync(connection, OpCodes.ERROR, new { error }, ct);
}
/// <summary>
/// Called when a connection is closed - cleanup session
/// </summary>
public void OnDisconnect(Guid connectionId)
{
if (_playerSessions.TryRemove(connectionId, out var session))
{
if (session.CurrentDungeonId.HasValue)
{
_ = RemoveFromDungeonAsync(session, false, CancellationToken.None);
}
_log.LogInformation("Dungeon session cleaned up for connection {Id}", connectionId);
}
}
/// <summary>
/// Handle chat message from player
/// </summary>
private async Task HandleChatSend(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
var request = System.Text.Json.JsonSerializer.Deserialize<ChatSendRequest>(json);
if (request == null || string.IsNullOrWhiteSpace(request.Message)) return;
// Sanitize message (basic - remove excessive whitespace, limit length)
var message = request.Message.Trim();
if (message.Length > 200) message = message.Substring(0, 200);
var senderName = session.Character?.Name ?? "Unknown";
// Determine chat scope based on player state
if (session.CurrentDungeonId.HasValue && _dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
{
// In dungeon - broadcast to all players in same dungeon
foreach (var player in dungeon.Simulation.Players.Values)
{
await SendAsync(_playerSessions.Values.Where(p => p.CharacterId == player.CharacterId).FirstOrDefault().Connection, DungeonOpCodes.CHAT_MESSAGE, new
{
sender = senderName,
message = message,
type = "normal"
}, ct);
}
}
else
{
// In hub - broadcast to all connected players in hub
foreach (var playerSession in _playerSessions.Values.Where(p => !p.CurrentDungeonId.HasValue))
{
await SendAsync(playerSession.Connection, DungeonOpCodes.CHAT_MESSAGE, new
{
sender = senderName,
message = message,
type = "normal"
}, ct);
}
}
_log.LogDebug("Chat from {Player}: {Message}", senderName, message);
}
/// <summary>
/// Broadcast a system message to all players in a dungeon
/// </summary>
private async Task BroadcastSystemMessage(DungeonInstance dungeon, string message, CancellationToken ct)
{
foreach (var player in dungeon.Simulation.Players.Values)
{
await SendAsync(_playerSessions.Values.Where(p => p.CharacterId == player.CharacterId).FirstOrDefault().Connection, DungeonOpCodes.CHAT_MESSAGE, new
{
sender = "System",
message = message,
type = "system"
}, ct);
}
}
/// <summary>
/// Broadcast a system message to all connected players
/// </summary>
private async Task BroadcastGlobalSystemMessage(string message, CancellationToken ct)
{
foreach (var session in _playerSessions.Values)
{
await SendAsync(session.Connection, DungeonOpCodes.CHAT_MESSAGE, new
{
sender = "System",
message = message,
type = "system"
}, ct);
}
}
}
// Request/Input DTOs
public class StatAllocateRequest
{
public string Stat { get; set; } = "";
}
public class DungeonEnterRequest
{
public int Tier { get; set; } = 1;
}
public class MoveInput
{
public float Dx { get; set; }
public float Dy { get; set; }
public float AimAngle { get; set; }
}
public class AttackInput
{
public float AimAngle { get; set; }
}
public class PickupInput
{
public ulong ItemId { get; set; }
}
public class ChestInput
{
public ulong ChestId { get; set; }
}
public class EquipItemRequest
{
public int SlotIndex { get; set; }
}
public class UnequipItemRequest
{
public string Slot { get; set; } = "";
}
public class UseItemRequest
{
public int SlotIndex { get; set; }
}
public class ChatSendRequest
{
public string Message { get; set; } = "";
}
public class PortalUseRequest
{
public int PortalId { get; set; }
}
public class LootChestOpenRequest
{
public int ChestId { get; set; }
}
public class LootChestTakeItemRequest
{
public int ChestId { get; set; }
public int SlotIndex { get; set; }
public int TargetSlotIndex { get; set; } // Where to put it in player inventory (-1 for auto)
}
public class LootChestTakeAllRequest
{
public int ChestId { get; set; }
}
public class LootChestCloseRequest
{
public int ChestId { get; set; }
}
public class DungeonCreateRequest
{
public int Tier { get; set; }
public int BracketMin { get; set; } // 0 = use player's natural bracket, otherwise specify bracket start level
}
public class DungeonJoinRequest
{
public string DungeonId { get; set; } = "";
}