Breakdown DungeonHandler Monolith to sealed partials

This commit is contained in:
dingo
2026-01-26 14:41:10 -05:00
parent 39920c81a2
commit 73ff3d8694
8 changed files with 1970 additions and 499 deletions
+205
View File
@@ -0,0 +1,205 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using DataServer.Data;
using DataServer.Data.Enums;
using Server.Networking;
using GameServer.Networking.DTOs;
using Server.Networking.Messages;
using DataServer.Data.Entities;
namespace GameServer.Dungeon;
public sealed partial class DungeonHandler
{
#region Crafting
private async Task HandleCraftingSkillsRequest(IConnection connection, DungeonPlayerSession session, CancellationToken ct)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var skills = await _craftingHandler.GetAllCraftingSkillsAsync(db, session.CharacterId);
var skillsData = skills.ToDictionary(
kvp => (int)kvp.Key,
kvp => new
{
level = kvp.Value.Level,
xp = kvp.Value.Experience,
xpForNext = kvp.Value.ExperienceForNextLevel,
totalCrafted = kvp.Value.TotalItemsCrafted
}
);
await SendAsync(connection, DungeonOpCodes.CRAFTING_SKILLS_STATE, new { skills = skillsData }, ct);
}
private async Task HandleCraftingRecipesRequest(IConnection connection, DungeonPlayerSession session, CancellationToken ct)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var recipes = await _craftingHandler.GetKnownRecipesAsync(db, session.CharacterId);
// Get item definitions for names
var itemDefIds = recipes.SelectMany(r => r.Ingredients.Select(i => i.ItemDefinitionId))
.Concat(recipes.Select(r => r.OutputItemDefinitionId))
.Concat(recipes.Where(r => r.BonusOutputItemDefinitionId.HasValue).Select(r => r.BonusOutputItemDefinitionId!.Value))
.Distinct()
.ToList();
var itemDefs = await db.DungeonItemDefinitions
.Where(d => itemDefIds.Contains(d.Id))
.ToDictionaryAsync(d => d.Id, ct);
var recipesData = recipes.Select(r => new
{
id = r.Id,
name = r.Name,
description = r.Description,
skillType = (int)r.SkillType,
requiredLevel = r.RequiredLevel,
tier = r.Tier,
outputItemDefinitionId = r.OutputItemDefinitionId,
outputName = itemDefs.TryGetValue(r.OutputItemDefinitionId, out var outDef) ? outDef.Name : "Unknown",
outputQuantity = r.OutputQuantity,
hasStatRolls = r.HasStatRolls,
bonusOutputName = r.BonusOutputItemDefinitionId.HasValue && itemDefs.TryGetValue(r.BonusOutputItemDefinitionId.Value, out var bonusDef)
? bonusDef.Name
: null,
bonusOutputMinLevel = r.BonusOutputMinLevel,
ingredients = r.Ingredients.Select(i => new
{
itemDefinitionId = i.ItemDefinitionId,
itemName = itemDefs.TryGetValue(i.ItemDefinitionId, out var ingDef) ? ingDef.Name : "Unknown",
quantity = i.Quantity
}).ToList()
});
await SendAsync(connection, DungeonOpCodes.CRAFTING_RECIPES_STATE, new { recipes = recipesData }, ct);
}
private async Task HandleCraftingAttempt(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var request = _ser.Deserialize<CraftingAttemptRequest>(payload);
if (request == null) return;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Load character
var character = await db.DungeonCharacters.FindAsync(new object[] { session.CharacterId }, ct);
if (character == null)
{
await SendAsync(connection, DungeonOpCodes.CRAFTING_RESULT, new { success = false, error = "Character not found" }, ct);
return;
}
if (request.Discover && request.Ingredients != null && request.Ingredients.Count > 0)
{
// Recipe discovery attempt with optional skill type filter
var ingredients = request.Ingredients.Select(i => (i.ItemDefinitionId, i.Quantity)).ToList();
CraftingSkillType? skillFilter = request.SkillType.HasValue
? (CraftingSkillType)request.SkillType.Value
: null;
var (recipe, alreadyKnown, error) = await _craftingHandler.TryDiscoverRecipeAsync(
db, session.CharacterId, ingredients, skillFilter);
if (recipe == null)
{
// Failed discovery - 65% chance to lose materials
var (materialsLost, lostItems) = await _craftingHandler.TryConsumeMaterialsOnFailedDiscoveryAsync(
db, session.CharacterId, ingredients);
var errorMsg = error ?? "No recipe found for these ingredients";
if (materialsLost)
{
errorMsg += $"\nMaterials lost: {string.Join(", ", lostItems)}";
}
else
{
errorMsg += "\nMaterials saved!";
}
await SendAsync(connection, DungeonOpCodes.CRAFTING_RESULT, new
{
success = false,
error = errorMsg,
materialsLost = materialsLost,
lostItems = lostItems
}, ct);
}
else if (alreadyKnown)
{
await SendAsync(connection, DungeonOpCodes.CRAFTING_RESULT, new
{
success = false,
error = "You already know this recipe!",
recipeName = recipe.Name
}, ct);
}
else
{
// New recipe discovered!
await SendAsync(connection, DungeonOpCodes.RECIPE_DISCOVERED, new
{
id = recipe.Id,
name = recipe.Name,
skillType = (int)recipe.SkillType
}, ct);
await SendAsync(connection, DungeonOpCodes.CRAFTING_RESULT, new
{
success = true,
discovered = true,
recipeName = recipe.Name
}, ct);
}
}
else
{
// Normal crafting from known recipe
var result = await _craftingHandler.CraftItemAsync(db, session.CharacterId, request.RecipeId, character);
if (result.Success)
{
await SendAsync(connection, DungeonOpCodes.CRAFTING_RESULT, new
{
success = true,
outputName = result.OutputItem?.Name ?? "Unknown",
quantity = result.OutputQuantity,
xpGained = result.XpGained,
newSkillLevel = result.NewSkillLevel,
leveledUp = result.LeveledUp,
gotBonusOutput = result.GotBonusOutput,
slotIndex = result.SlotIndex,
rollResults = result.RollResults.Select(r => new { stat = r.Stat, value = r.Value }),
qualityRating = result.CraftedItem?.QualityRating
}, ct);
if (result.LeveledUp)
{
await SendAsync(connection, DungeonOpCodes.CRAFTING_SKILL_LEVELUP, new
{
skillType = (int)result.OutputItem?.Type, // We'd need to get the skill type from recipe
newLevel = result.NewSkillLevel
}, ct);
}
}
else
{
await SendAsync(connection, DungeonOpCodes.CRAFTING_RESULT, new
{
success = false,
error = result.ErrorMessage
}, ct);
}
}
}
#endregion
}
+680
View File
@@ -0,0 +1,680 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DataServer.Data;
using DataServer.Data.Entities;
using DataServer.Data.Enums;
using Server.Networking;
using GameServer.Networking.DTOs;
using Server.Networking.Messages;
namespace GameServer.Dungeon;
public sealed partial class DungeonHandler
{
#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();
// Try V3 generator with DungeonBuilder templates first
DungeonLayout layout;
DungeonLayoutV2? layoutV2 = null;
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var generator = new DungeonGeneratorV3(db, seed, tier);
layoutV2 = await generator.GenerateAsync();
// Check if V3 actually produced tiles
if (layoutV2.TileDetails.Count == 0)
{
_log.LogWarning("V3 generator produced no tiles, falling back to V2");
var generatorV2 = new DungeonGeneratorV2(db, seed, tier);
layoutV2 = await generatorV2.GenerateAsync();
}
layout = layoutV2;
_log.LogInformation("Generated dungeon - {RoomCount} rooms, {TileCount} visual tiles",
layoutV2.Rooms.Count, layoutV2.TileDetails?.Count ?? 0);
}
catch (Exception ex)
{
_log.LogWarning(ex, "Dungeon generator failed, falling back to V2");
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var generatorV2 = new DungeonGeneratorV2(db, seed, tier);
layoutV2 = await generatorV2.GenerateAsync();
layout = layoutV2;
}
catch (Exception ex2)
{
_log.LogWarning(ex2, "V2 generator also failed, using V1");
layout = DungeonGenerator.Generate(seed, tier);
}
}
var simulation = new DungeonSimulation(layout, tier, _mobDefinitions, bracketMin, null, _mobSpriteConfigs);
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,
LayoutV2 = layoutV2 // Store V2 layout for visual tile data
};
_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)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var layout = instance.Simulation.Layout;
var spawnPos = layout.Rooms[0]; // Entrance room
// Load equipped items for stat calculations
var equippedCharacterItems = await db.Set<DungeonCharacterItem>()
.Include(i => i.ItemDefinition)
.Include(i => i.CraftedItem)
.Where(i => i.CharacterId == session.CharacterId && i.IsEquipped)
.ToListAsync(ct);
// Calculate combat stats with equipment bonuses (including crafted)
var combatStats = DungeonCharacterStats.GetCombatStats(session.Character, equippedCharacterItems);
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 = Math.Min(session.Character.CurrentHealth, combatStats.MaxHealth),
MaxHealth = combatStats.MaxHealth,
Mana = Math.Min(session.Character.CurrentMana, combatStats.MaxMana),
MaxMana = combatStats.MaxMana,
Stamina = combatStats.MaxStamina,
MaxStamina = combatStats.MaxStamina,
MoveSpeed = combatStats.MoveSpeed,
AttackSpeed = combatStats.AttackSpeed,
Strength = combatStats.Strength,
Intelligence = combatStats.Intelligence,
Wisdom = combatStats.Wisdom,
Endurance = combatStats.Endurance,
Dexterity = combatStats.Dexterity,
Armor = combatStats.Armor
};
instance.Simulation.Players[session.CharacterId] = player;
instance.LastPlayerActivity = DateTime.UtcNow;
session.State = PlayerState.InDungeon;
session.CurrentDungeonId = instance.Id;
session.PlayerInstance = player;
// Build visual tile data if V2 layout available
object? tileSheets = null;
object? visualTiles = null;
object? placedObjects = null;
if (instance.LayoutV2 != null && instance.LayoutV2.TileDetails.Count > 0)
{
tileSheets = instance.LayoutV2.TileMapSheets.Select(s => new
{
id = s.Id,
path = s.CdnPath,
tileW = s.TileWidth,
tileH = s.TileHeight,
sheetW = s.SheetWidth,
sheetH = s.SheetHeight,
cols = s.Columns
}).ToArray();
visualTiles = instance.LayoutV2.TileDetails.Select(t => new
{
x = t.X,
y = t.Y,
tid = t.TileDefinitionId,
sid = t.SheetId,
frame = t.FrameIndex,
l = t.Layer,
r = t.Rotation,
fx = t.FlipX,
fy = t.FlipY
}).ToArray();
// V3: Include placed objects (decorations, containers, traps)
if (instance.LayoutV2.Objects?.Count > 0)
{
placedObjects = instance.LayoutV2.Objects.Select(o => new
{
x = o.X,
y = o.Y,
id = o.ObjectTemplateId,
name = o.Name,
type = o.Type,
sheetId = o.SpriteSheetId,
frame = o.FrameIndex,
blocks = o.BlocksMovement,
interact = o.IsInteractable,
trap = o.IsTrap,
damage = o.TrapDamage,
loot = o.LootTableId
}).ToArray();
}
_log.LogInformation("Sending {SheetCount} sheets, {TileCount} visual tiles, {ObjectCount} objects to client",
instance.LayoutV2.TileMapSheets.Count, instance.LayoutV2.TileDetails.Count, instance.LayoutV2.Objects?.Count ?? 0);
}
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,
rotation = m.Rotation,
health = m.Health,
maxHealth = m.MaxHealth,
state = m.State.ToString().ToLower(),
spriteConfig = string.IsNullOrEmpty(m.SpriteConfigJson) ? null :
System.Text.Json.JsonSerializer.Deserialize<object>(m.SpriteConfigJson),
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()
}),
// V3 visual tile data
tileSheets,
visualTiles,
placedObjects
}, 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, null, _mobSpriteConfigs);
// 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)
/// Preserves mobs that are carrying player loot from kills
/// </summary>
private void RespawnAllMobs(DungeonInstance instance)
{
// Check if any existing mobs have carried player loot - don't respawn those
var mobsWithLoot = instance.Simulation.Mobs.Values
.Where(m => m.HasCarriedLoot)
.ToDictionary(m => m.Id, m => m);
if (mobsWithLoot.Count > 0)
{
_log.LogInformation("Preserving {Count} mobs with carried player loot during respawn", mobsWithLoot.Count);
}
// IMPORTANT: Reuse the existing layout to preserve mob spawn positions!
// Using DungeonGenerator.Generate() would create a V1 layout which has different
// room geometry than V2/V3, causing mobs to spawn in wrong positions.
var layout = instance.Simulation.Layout;
var freshSimulation = new DungeonSimulation(layout, instance.Tier, _mobDefinitions, instance.LevelBracketMin, null, _mobSpriteConfigs);
// Clear and rebuild mobs, keeping those with loot
instance.Simulation.Mobs.Clear();
foreach (var mob in freshSimulation.Mobs)
{
// If we have a preserved mob with this ID (same spawn point), use the preserved one
if (mobsWithLoot.TryGetValue(mob.Key, out var preservedMob))
{
// Restore the preserved mob (keeps carried loot)
instance.Simulation.Mobs.TryAdd(mob.Key, preservedMob);
}
else
{
// Use the fresh mob
instance.Simulation.Mobs.TryAdd(mob.Key, mob.Value);
}
}
// Reset chest states (they respawn closed) - but NOT loot chests
foreach (var chest in instance.Simulation.Chests.Values)
{
chest.IsOpened = false;
}
// DON'T clear loot chests - these contain player death drops!
// instance.Simulation.LootChests.Clear();
// DON'T clear dropped items - these might be important!
// 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} (preserved {PreservedCount} with loot)",
instance.Simulation.Mobs.Count, instance.Id, mobsWithLoot.Count);
}
/// <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
}
+392
View File
@@ -0,0 +1,392 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DataServer.Data;
using DataServer.Data.Entities;
using Server.Networking;
using GameServer.Networking.DTOs;
using Server.Networking.Messages;
namespace GameServer.Dungeon;
public sealed partial class DungeonHandler
{
#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,
spritePath = def.SpritePath,
tintColor = def.TintColor
};
}
}
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
}
+45
View File
@@ -0,0 +1,45 @@
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DataServer.Data;
using DataServer.Data.Entities;
namespace GameServer.Dungeon;
public sealed partial class DungeonHandler
{
private async Task LoadMobDefinitionsAsync()
{
await RefreshMobCacheAsync();
}
/// <summary>
/// Refresh mob definitions cache. Call this after mobs are modified in admin.
/// </summary>
public async Task RefreshMobCacheAsync()
{
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)
{
_log.LogCritical("Dungeon Mobs Table EMPTY");
}
_mobDefinitions = mobs.ToDictionary(m => m.Id);
// Build sprite configs from animation assignments
var spriteConfigBuilder = new MobSpriteConfigBuilder(db);
_mobSpriteConfigs = await spriteConfigBuilder.BuildSpriteConfigsAsync(mobs.Select(m => m.Id));
// Count animation assignments for debugging
var assignmentCount = await db.Set<MobAnimationAssignment>().CountAsync();
_log.LogInformation("Refreshed mob cache: {MobCount} mobs, {AssignmentCount} animation assignments", mobs.Count, assignmentCount);
}
}
+184
View File
@@ -0,0 +1,184 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Server.Networking;
using GameServer.Networking.DTOs;
using Server.Networking.Messages;
namespace GameServer.Dungeon;
public sealed partial class DungeonHandler
{
#region Mob Loot Handlers
private async Task HandleMobLootRequest(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<MobLootRequest>(json);
if (request == null) return;
if (!session.CurrentDungeonId.HasValue ||
!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
return;
if (!dungeon.Simulation.Mobs.TryGetValue(request.MobId, out var mob))
{
await SendErrorAsync(connection, "Mob not found", ct);
return;
}
// Check if mob is dead
if (mob.IsAlive)
{
await SendErrorAsync(connection, "Mob is still alive", ct);
return;
}
// Check distance
if (session.PlayerInstance != null)
{
float dist = MathF.Sqrt(
MathF.Pow(session.PlayerInstance.X - mob.X, 2) +
MathF.Pow(session.PlayerInstance.Y - mob.Y, 2));
if (dist > 96) // Interaction range
{
await SendErrorAsync(connection, "Too far from mob", ct);
return;
}
}
// Send mob loot state
var lootItems = new List<object>();
if (mob.DeathLoot != null)
{
foreach (var loot in mob.DeathLoot)
{
lootItems.Add(new
{
definitionId = loot.ItemDefinitionId,
name = loot.Item.Name,
description = loot.Item.Description,
type = loot.Item.Type.ToString(),
rarity = loot.Item.Rarity.ToString(),
quantity = loot.Quantity,
spritePath = loot.Item.SpritePath,
tintColor = loot.Item.TintColor
});
}
}
await SendAsync(connection, DungeonOpCodes.MOB_LOOT_STATE, new
{
mobId = mob.Id,
mobName = mob.Name,
gold = mob.DeathLootGold,
items = lootItems
}, ct);
}
private async Task HandleMobLootTakeItem(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<MobLootTakeItemRequest>(json);
if (request == null) return;
if (!session.CurrentDungeonId.HasValue ||
!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
return;
if (!dungeon.Simulation.Mobs.TryGetValue(request.MobId, out var mob))
return;
if (!mob.IsAlive && mob.DeathLoot != null && request.ItemIndex >= 0 && request.ItemIndex < mob.DeathLoot.Count)
{
var lootItem = mob.DeathLoot[request.ItemIndex];
// Try to add to inventory
var (addedItems, overflowItems, _) = await AddLootToInventoryWithOverflowAsync(
session, new List<LootDrop> { lootItem }, 0);
if (addedItems.Count > 0)
{
// Remove from mob loot
mob.DeathLoot.RemoveAt(request.ItemIndex);
// Send updated inventory
await HandleInventoryRequest(connection, session, ct);
// Send updated mob loot state so client knows what's left
await HandleMobLootRequest(connection, session, System.Text.Encoding.UTF8.GetBytes(
System.Text.Json.JsonSerializer.Serialize(new { mobId = request.MobId })), ct);
_log.LogDebug("Player {Player} looted {Item} x{Qty} from mob {Mob}",
session.Character.Name, lootItem.Item.Name, lootItem.Quantity, mob.Name);
}
else if (overflowItems.Count > 0)
{
await SendErrorAsync(connection, "Inventory full", ct);
}
}
}
private async Task HandleMobLootTakeAll(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<MobLootTakeAllRequest>(json);
if (request == null) return;
if (!session.CurrentDungeonId.HasValue ||
!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
return;
if (!dungeon.Simulation.Mobs.TryGetValue(request.MobId, out var mob))
return;
if (!mob.IsAlive && mob.HasDeathLoot)
{
long goldToTake = mob.DeathLootGold;
var itemsToTake = mob.DeathLoot != null ? new List<LootDrop>(mob.DeathLoot) : new List<LootDrop>();
// Try to add all loot to inventory
var (addedItems, overflowItems, overflowGold) = await AddLootToInventoryWithOverflowAsync(
session, itemsToTake, goldToTake);
// Remove successfully added items from mob loot
if (mob.DeathLoot != null)
{
foreach (var added in addedItems)
{
var toRemove = mob.DeathLoot.FirstOrDefault(l =>
l.ItemDefinitionId == added.ItemDefinitionId &&
l.Quantity == added.Quantity);
if (toRemove != null)
{
mob.DeathLoot.Remove(toRemove);
}
}
}
// Remove taken gold
long goldTaken = goldToTake - overflowGold;
mob.DeathLootGold = overflowGold;
// If there's overflow, spawn a loot chest
if (overflowItems.Count > 0 || overflowGold > 0)
{
await SpawnLootChestAsync(dungeon, session, overflowItems, overflowGold,
mob.X, mob.Y, null, mob.DefinitionId);
}
// Send updated inventory
await HandleInventoryRequest(connection, session, ct);
_log.LogDebug("Player {Player} looted all from mob {Mob}: {Items} items, {Gold} gold",
session.Character.Name, mob.Name, addedItems.Count, goldTaken);
}
}
#endregion
}
+103
View File
@@ -0,0 +1,103 @@
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Server.Networking.Messages;
namespace GameServer.Dungeon;
public sealed partial class DungeonHandler
{
private async Task SubscribeToBroadcastChannelAsync()
{
try
{
// Subscribe to server:broadcast channel
await _redis.Bus.SubscribeAsync("server:broadcast", (channel, message) =>
{
try
{
if (message.IsNullOrEmpty) return;
var payload = JsonSerializer.Deserialize<BroadcastPayload>(message.ToString());
if (payload == null) return;
_log.LogInformation("Received broadcast from Redis: [{Type}] {Message}", payload.Type, payload.Message);
// Send to all local player sessions
foreach (var session in _playerSessions.Values)
{
_ = SendAsync(session.Connection, DungeonOpCodes.SERVER_BROADCAST, new
{
message = payload.Message,
type = payload.Type
}, CancellationToken.None);
}
}
catch (Exception ex)
{
_log.LogError(ex, "Error processing broadcast message");
}
});
// Subscribe to server:command channel for asset refresh, force reconnect, etc.
await _redis.Bus.SubscribeAsync("server:command", (channel, message) =>
{
try
{
if (message.IsNullOrEmpty) return;
var payload = JsonSerializer.Deserialize<CommandPayload>(message.ToString());
if (payload == null) return;
_log.LogInformation("Received command from Redis: {Command}", payload.Command);
switch (payload.Command)
{
case "refresh_assets":
// Queue asset refresh for all local players
_broadcastService.QueueAssetRefresh();
break;
case "force_reconnect":
// Could implement force disconnect here
break;
}
}
catch (Exception ex)
{
_log.LogError(ex, "Error processing command message");
}
});
_log.LogInformation("Subscribed to Redis broadcast channels");
}
catch (Exception ex)
{
_log.LogError(ex, "Failed to subscribe to Redis broadcast channels");
}
}
// Payload classes for Redis pub/sub
private class BroadcastPayload
{
[System.Text.Json.Serialization.JsonPropertyName("type")]
public string Type { get; set; } = "system";
[System.Text.Json.Serialization.JsonPropertyName("message")]
public string Message { get; set; } = "";
[System.Text.Json.Serialization.JsonPropertyName("duration")]
public int Duration { get; set; } = 10;
[System.Text.Json.Serialization.JsonPropertyName("timestamp")]
public long Timestamp { get; set; }
}
private class CommandPayload
{
[System.Text.Json.Serialization.JsonPropertyName("command")]
public string Command { get; set; } = "";
public long Timestamp { get; set; }
}
}
+355
View File
@@ -0,0 +1,355 @@
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using DataServer.Data;
using DataServer.Data.Entities;
using DataServer.Data.Enums;
using Server.Networking;
using GameServer.Networking.DTOs;
using Server.Networking.Messages;
namespace GameServer.Dungeon;
#region Stash System (VIP Feature)
public sealed partial class DungeonHandler
{
private const int STASH_SLOTS = 50; // Number of stash slots for VIP
/// <summary>
/// Handle request to view stash contents
/// </summary>
private async Task HandleStashRequest(IConnection connection, DungeonPlayerSession session, CancellationToken ct)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Check VIP status
var account = await db.Accounts.FindAsync(new object[] { session.AccountId }, ct);
if (account == null || account.Role < AccountRole.Vip)
{
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = false,
error = "vip_required",
message = "Stash is a VIP feature. Upgrade your account to access it!"
}, ct);
return;
}
// Get stash items
var stashItems = await db.DungeonStashItems
.Where(s => s.CharacterId == session.CharacterId)
.Include(s => s.Definition)
.OrderBy(s => s.SlotIndex)
.ToListAsync(ct);
await SendAsync(connection, DungeonOpCodes.STASH_STATE, new
{
slots = STASH_SLOTS,
items = stashItems.Select(s => new
{
id = s.Id,
slotIndex = s.SlotIndex,
itemDefinitionId = s.ItemDefinitionId,
quantity = s.Quantity,
storedAt = s.StoredAt,
definition = s.Definition == null ? null : new
{
id = s.Definition.Id,
name = s.Definition.Name,
description = s.Definition.Description,
type = s.Definition.Type.ToString(),
rarity = s.Definition.Rarity.ToString(),
spritePath = s.Definition.SpritePath,
stackable = s.Definition.Stackable,
maxStack = s.Definition.MaxStack
}
})
}, ct);
}
/// <summary>
/// Handle depositing an item from inventory to stash
/// </summary>
private async Task HandleStashDeposit(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Check VIP status
var account = await db.Accounts.FindAsync(new object[] { session.AccountId }, ct);
if (account == null || account.Role < AccountRole.Vip)
{
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = false,
error = "vip_required",
message = "Stash is a VIP feature."
}, ct);
return;
}
// Must be in hub to use stash
if (session.State != PlayerState.InHub)
{
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = false,
error = "not_in_hub",
message = "You must be in the hub to access your stash."
}, ct);
return;
}
var request = _ser.Deserialize<StashDepositRequest>(payload);
var inventorySlot = request.InventorySlot;
var quantity = request.Quantity > 0 ? request.Quantity : 1;
var targetSlot = request.TargetSlot;
// Find the inventory item
var invItem = await db.DungeonCharacterItems
.Include(i => i.ItemDefinition)
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId && i.SlotIndex == inventorySlot && !i.IsEquipped, ct);
if (invItem == null)
{
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = false,
error = "item_not_found",
message = "Item not found in inventory."
}, ct);
return;
}
// Find target slot
if (targetSlot < 0)
{
// Auto-find empty slot
var usedSlots = await db.DungeonStashItems
.Where(s => s.CharacterId == session.CharacterId)
.Select(s => s.SlotIndex)
.ToListAsync(ct);
for (int i = 0; i < STASH_SLOTS; i++)
{
if (!usedSlots.Contains(i))
{
targetSlot = i;
break;
}
}
if (targetSlot < 0)
{
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = false,
error = "stash_full",
message = "Your stash is full!"
}, ct);
return;
}
}
// Validate quantity
quantity = Math.Min(quantity, invItem.Quantity);
// Check if stacking with existing stash item
DungeonStashItem? existingStash = null;
if (invItem.ItemDefinition?.Stackable == true)
{
existingStash = await db.DungeonStashItems
.Include(s => s.Definition)
.FirstOrDefaultAsync(s => s.CharacterId == session.CharacterId &&
s.ItemDefinitionId == invItem.ItemDefinitionId, ct);
}
if (existingStash != null && invItem.ItemDefinition?.Stackable == true)
{
// Stack with existing
var maxAdd = (invItem.ItemDefinition?.MaxStack ?? 99) - existingStash.Quantity;
var toAdd = Math.Min(quantity, maxAdd);
if (toAdd > 0)
{
existingStash.Quantity += toAdd;
invItem.Quantity -= toAdd;
if (invItem.Quantity <= 0)
db.DungeonCharacterItems.Remove(invItem);
}
}
else
{
// Create new stash entry
var stashItem = new DungeonStashItem
{
CharacterId = session.CharacterId,
ItemDefinitionId = invItem.ItemDefinitionId,
Quantity = quantity,
SlotIndex = targetSlot,
StoredAt = DateTime.UtcNow
};
db.DungeonStashItems.Add(stashItem);
invItem.Quantity -= quantity;
if (invItem.Quantity <= 0)
db.DungeonCharacterItems.Remove(invItem);
}
await db.SaveChangesAsync(ct);
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = true,
message = "Item deposited to stash."
}, ct);
// Send updated inventory and stash
await HandleInventoryRequest(connection, session, ct);
await HandleStashRequest(connection, session, ct);
}
/// <summary>
/// Handle withdrawing an item from stash to inventory
/// </summary>
private async Task HandleStashWithdraw(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Check VIP status
var account = await db.Accounts.FindAsync(new object[] { session.AccountId }, ct);
if (account == null || account.Role < AccountRole.Vip)
{
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = false,
error = "vip_required",
message = "Stash is a VIP feature."
}, ct);
return;
}
// Must be in hub to use stash
if (session.State != PlayerState.InHub)
{
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = false,
error = "not_in_hub",
message = "You must be in the hub to access your stash."
}, ct);
return;
}
var request = _ser.Deserialize<StashWithdrawRequest>(payload);
var stashSlot = request.StashSlot;
var quantity = request.Quantity > 0 ? request.Quantity : 1;
// Find the stash item
var stashItem = await db.DungeonStashItems
.Include(s => s.Definition)
.FirstOrDefaultAsync(s => s.CharacterId == session.CharacterId && s.SlotIndex == stashSlot, ct);
if (stashItem == null)
{
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = false,
error = "item_not_found",
message = "Item not found in stash."
}, ct);
return;
}
// Validate quantity
quantity = Math.Min(quantity, stashItem.Quantity);
// Find empty inventory slot or stackable slot
var invItems = await db.DungeonCharacterItems
.Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped)
.Include(i => i.ItemDefinition)
.ToListAsync(ct);
// Check for stackable existing
DungeonCharacterItem? targetItem = null;
if (stashItem.Definition?.Stackable == true)
{
targetItem = invItems.FirstOrDefault(i =>
i.ItemDefinitionId == stashItem.ItemDefinitionId &&
i.Quantity < (i.ItemDefinition?.MaxStack ?? 99));
}
if (targetItem != null)
{
// Stack with existing
var maxAdd = (stashItem.Definition?.MaxStack ?? 99) - targetItem.Quantity;
var toAdd = Math.Min(quantity, maxAdd);
targetItem.Quantity += toAdd;
stashItem.Quantity -= toAdd;
if (stashItem.Quantity <= 0)
db.DungeonStashItems.Remove(stashItem);
}
else
{
// Find empty slot (starting from slot 0 for inventory)
var usedSlots = invItems.Select(i => i.SlotIndex).ToHashSet();
int emptySlot = -1;
for (int i = 0; i < 30; i++)
{
if (!usedSlots.Contains(i))
{
emptySlot = i;
break;
}
}
if (emptySlot < 0)
{
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = false,
error = "inventory_full",
message = "Your inventory is full!"
}, ct);
return;
}
// Create new inventory item
var newItem = new DungeonCharacterItem
{
CharacterId = session.CharacterId,
ItemDefinitionId = stashItem.ItemDefinitionId,
Quantity = quantity,
SlotIndex = emptySlot
};
db.DungeonCharacterItems.Add(newItem);
stashItem.Quantity -= quantity;
if (stashItem.Quantity <= 0)
db.DungeonStashItems.Remove(stashItem);
}
await db.SaveChangesAsync(ct);
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = true,
message = "Item withdrawn from stash."
}, ct);
// Send updated inventory and stash
await HandleInventoryRequest(connection, session, ct);
await HandleStashRequest(connection, session, ct);
}
}
#endregion
+6 -499
View File
@@ -146,131 +146,6 @@ public sealed partial class DungeonHandler : IClientMessageHandler
_log.LogInformation("DungeonHandler initialized on pod {PodId} with {MobCount} mob definitions", _podId, _mobDefinitions.Count);
}
private async Task SubscribeToBroadcastChannelAsync()
{
try
{
// Subscribe to server:broadcast channel
await _redis.Bus.SubscribeAsync("server:broadcast", (channel, message) =>
{
try
{
if (message.IsNullOrEmpty) return;
var payload = JsonSerializer.Deserialize<BroadcastPayload>(message.ToString());
if (payload == null) return;
_log.LogInformation("Received broadcast from Redis: [{Type}] {Message}", payload.Type, payload.Message);
// Send to all local player sessions
foreach (var session in _playerSessions.Values)
{
_ = SendAsync(session.Connection, DungeonOpCodes.SERVER_BROADCAST, new
{
message = payload.Message,
type = payload.Type
}, CancellationToken.None);
}
}
catch (Exception ex)
{
_log.LogError(ex, "Error processing broadcast message");
}
});
// Subscribe to server:command channel for asset refresh, force reconnect, etc.
await _redis.Bus.SubscribeAsync("server:command", (channel, message) =>
{
try
{
if (message.IsNullOrEmpty) return;
var payload = JsonSerializer.Deserialize<CommandPayload>(message.ToString());
if (payload == null) return;
_log.LogInformation("Received command from Redis: {Command}", payload.Command);
switch (payload.Command)
{
case "refresh_assets":
// Queue asset refresh for all local players
_broadcastService.QueueAssetRefresh();
break;
case "force_reconnect":
// Could implement force disconnect here
break;
}
}
catch (Exception ex)
{
_log.LogError(ex, "Error processing command message");
}
});
_log.LogInformation("Subscribed to Redis broadcast channels");
}
catch (Exception ex)
{
_log.LogError(ex, "Failed to subscribe to Redis broadcast channels");
}
}
// Payload classes for Redis pub/sub
private class BroadcastPayload
{
[System.Text.Json.Serialization.JsonPropertyName("type")]
public string Type { get; set; } = "system";
[System.Text.Json.Serialization.JsonPropertyName("message")]
public string Message { get; set; } = "";
[System.Text.Json.Serialization.JsonPropertyName("duration")]
public int Duration { get; set; } = 10;
[System.Text.Json.Serialization.JsonPropertyName("timestamp")]
public long Timestamp { get; set; }
}
private class CommandPayload
{
[System.Text.Json.Serialization.JsonPropertyName("command")]
public string Command { get; set; } = "";
public long Timestamp { get; set; }
}
private async Task LoadMobDefinitionsAsync()
{
await RefreshMobCacheAsync();
}
/// <summary>
/// Refresh mob definitions cache. Call this after mobs are modified in admin.
/// </summary>
public async Task RefreshMobCacheAsync()
{
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)
{
_log.LogCritical("Dungeon Mobs Table EMPTY");
}
_mobDefinitions = mobs.ToDictionary(m => m.Id);
// Build sprite configs from animation assignments
var spriteConfigBuilder = new MobSpriteConfigBuilder(db);
_mobSpriteConfigs = await spriteConfigBuilder.BuildSpriteConfigsAsync(mobs.Select(m => m.Id));
// Count animation assignments for debugging
var assignmentCount = await db.Set<MobAnimationAssignment>().CountAsync();
_log.LogInformation("Refreshed mob cache: {MobCount} mobs, {AssignmentCount} animation assignments", mobs.Count, assignmentCount);
}
public async Task HandleAsync(int opCode, IConnection connection, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
// Ensure initialized
@@ -2163,380 +2038,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler
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,
spritePath = def.SpritePath,
tintColor = def.TintColor
};
}
}
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
#if false // moved to DungeonHandler.Dungeons.cs
#region Dungeon Browser Handlers
/// <summary>
@@ -3208,6 +2710,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler
}
#endregion
#endif
/// <summary>
/// Sends loot popup to client showing what they received
@@ -4321,6 +3824,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler
}
}
#if false // moved to DungeonHandler.Crafting.cs
#region Crafting
private async Task HandleCraftingSkillsRequest(IConnection connection, DungeonPlayerSession session, CancellationToken ct)
@@ -4497,11 +4001,13 @@ public sealed partial class DungeonHandler : IClientMessageHandler
}
#endregion
#endif
}
// Request/Input DTOs
#if false // moved to DungeonHandler.Stash.cs and DungeonHandler.MobLoot.cs
#region Stash System (VIP Feature)
public partial class DungeonHandler
@@ -5013,3 +4519,4 @@ public partial class DungeonHandler
#endregion
#endif