From b4affac20352e852dc4f98e84c945e9735446ecf Mon Sep 17 00:00:00 2001 From: dingo Date: Sat, 14 Feb 2026 00:37:56 -0500 Subject: [PATCH] Add NPC system scaffold, loot-table gold drops, and remove stash VIP gate --- Game/Dungeon/DungeonHandler.Dungeons.cs | 6 +- Game/Dungeon/DungeonHandler.MobCache.cs | 5 + Game/Dungeon/DungeonHandler.Npcs.cs | 564 ++++++++++++++++++ Game/Dungeon/DungeonHandler.Stash.cs | 43 +- Game/Dungeon/DungeonHandler.cs | 60 +- Game/Dungeon/DungeonLayout.cs | 10 + Game/Dungeon/DungeonNpcSpawn.cs | 13 + Game/Dungeon/DungeonSimulation.cs | 80 ++- Game/Dungeon/LootService.cs | 45 +- Game/Dungeon/NpcInstance.cs | 75 +++ ...0260214153000_NpcSystemAndLootTableGold.cs | 285 +++++++++ Networking/Messages/DungeonOpCodes.cs | 12 +- Services/Admin/Pages/LootTables/Edit.cshtml | 14 +- .../Admin/Pages/LootTables/Edit.cshtml.cs | 6 + data/GameDbContext.cs | 8 + data/entities/LootEntities.cs | 16 +- data/entities/NpcEntities.cs | 188 ++++++ data/enums/NpcEnums.cs | 28 + pending-clientChanges.md | 79 ++- 19 files changed, 1448 insertions(+), 89 deletions(-) create mode 100644 Game/Dungeon/DungeonHandler.Npcs.cs create mode 100644 Game/Dungeon/DungeonNpcSpawn.cs create mode 100644 Game/Dungeon/NpcInstance.cs create mode 100644 Migrations/20260214153000_NpcSystemAndLootTableGold.cs create mode 100644 data/entities/NpcEntities.cs create mode 100644 data/enums/NpcEnums.cs diff --git a/Game/Dungeon/DungeonHandler.Dungeons.cs b/Game/Dungeon/DungeonHandler.Dungeons.cs index de8ebba..33e93d3 100644 --- a/Game/Dungeon/DungeonHandler.Dungeons.cs +++ b/Game/Dungeon/DungeonHandler.Dungeons.cs @@ -165,7 +165,7 @@ public sealed partial class DungeonHandler var (layout, layoutV2) = await GenerateDungeonLayoutWithFallbackAsync(seed, tier, ct); - var simulation = new DungeonSimulation(layout, tier, _mobDefinitions, bracketMin, _abilityDefinitions, _mobSpriteConfigs, _abilityAnimationMappings); + var simulation = new DungeonSimulation(layout, tier, _mobDefinitions, bracketMin, _abilityDefinitions, _mobSpriteConfigs, _abilityAnimationMappings, _npcDefinitions); var instance = new DungeonInstance { @@ -476,7 +476,7 @@ public sealed partial class DungeonHandler var db = scope.ServiceProvider.GetRequiredService(); var vnext = new DungeonGeneratorVNext(db, persisted.Seed, persisted.Tier); var layout = await vnext.GenerateAsync(); - var simulation = new DungeonSimulation(layout, persisted.Tier, _mobDefinitions, persisted.LevelBracketMin, _abilityDefinitions, _mobSpriteConfigs, _abilityAnimationMappings); + var simulation = new DungeonSimulation(layout, persisted.Tier, _mobDefinitions, persisted.LevelBracketMin, _abilityDefinitions, _mobSpriteConfigs, _abilityAnimationMappings, _npcDefinitions); var mobStatePayload = DeserializePersistedMobPayload(persisted.MobStateJson); var persistedMobStates = mobStatePayload?.Mobs; @@ -623,7 +623,7 @@ public sealed partial class DungeonHandler // IMPORTANT: Reuse the existing layout to preserve mob spawn positions. var layout = instance.Simulation.Layout; - var freshSimulation = new DungeonSimulation(layout, instance.Tier, _mobDefinitions, instance.LevelBracketMin, _abilityDefinitions, _mobSpriteConfigs, _abilityAnimationMappings); + var freshSimulation = new DungeonSimulation(layout, instance.Tier, _mobDefinitions, instance.LevelBracketMin, _abilityDefinitions, _mobSpriteConfigs, _abilityAnimationMappings, _npcDefinitions); // Clear and rebuild mobs, keeping those with loot instance.Simulation.Mobs.Clear(); diff --git a/Game/Dungeon/DungeonHandler.MobCache.cs b/Game/Dungeon/DungeonHandler.MobCache.cs index c59cdb4..3dccadf 100644 --- a/Game/Dungeon/DungeonHandler.MobCache.cs +++ b/Game/Dungeon/DungeonHandler.MobCache.cs @@ -50,6 +50,11 @@ public sealed partial class DungeonHandler var spriteConfigBuilder = new MobSpriteConfigBuilder(db); _mobSpriteConfigs = await spriteConfigBuilder.BuildSpriteConfigsAsync(mobs.Select(m => m.Id)); + var npcs = await db.Set() + .Where(n => n.IsEnabled) + .ToListAsync(); + _npcDefinitions = npcs.ToDictionary(n => n.Id); + // Count animation assignments for debugging var assignmentCount = await db.Set().CountAsync(); var abilityAssignmentsCount = mobs.Sum(m => m.AbilityAssignments?.Count ?? 0); diff --git a/Game/Dungeon/DungeonHandler.Npcs.cs b/Game/Dungeon/DungeonHandler.Npcs.cs new file mode 100644 index 0000000..189f096 --- /dev/null +++ b/Game/Dungeon/DungeonHandler.Npcs.cs @@ -0,0 +1,564 @@ +using DataServer.Data; +using DataServer.Data.Entities; +using DataServer.Data.Enums; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Server.Networking; +using Server.Networking.Messages; + +namespace GameServer.Dungeon; + +public sealed partial class DungeonHandler +{ + private sealed class NpcInteractRequest + { + public int NpcId { get; set; } + } + + private sealed class NpcDialogSelectRequest + { + public int NpcId { get; set; } + public int OptionId { get; set; } + } + + private sealed class NpcShopActionRequest + { + public int NpcId { get; set; } + public string Action { get; set; } = "buy"; + public int SlotIndex { get; set; } + public int Quantity { get; set; } = 1; + } + + private async Task HandleNpcInteract(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory payload, CancellationToken ct) + { + if (!session.CurrentDungeonId.HasValue || !_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) + { + await SendErrorAsync(connection, "not_in_dungeon", ct); + return; + } + + var req = _ser.Deserialize(payload); + if (!dungeon.Simulation.Npcs.TryGetValue(req.NpcId, out var npc)) + { + await SendAsync(connection, DungeonOpCodes.NPC_INTERACT_STATE, new + { + success = false, + error = "npc_not_found" + }, ct); + return; + } + + await SendAsync(connection, DungeonOpCodes.NPC_INTERACT_STATE, new + { + success = true, + npc = new + { + id = npc.Id, + definitionId = npc.DefinitionId, + name = npc.Name, + canShop = npc.CanShop, + hasDialog = npc.HasDialog, + isKillable = npc.IsKillable, + behavior = npc.BehaviorMode.ToString().ToLower(), + onAttackBehavior = npc.OnAttackBehavior.ToString().ToLower(), + shopId = npc.ShopId, + dialogTreeId = npc.DialogTreeId + } + }, ct); + + if (npc.HasDialog && npc.DialogTreeId.HasValue) + { + await SendNpcDialogNodeAsync(connection, session, npc, null, ct); + } + + if (npc.CanShop && npc.ShopId.HasValue) + { + await SendNpcShopStateAsync(connection, npc.ShopId.Value, ct); + } + } + + private async Task HandleNpcDialogSelect(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory payload, CancellationToken ct) + { + if (!session.CurrentDungeonId.HasValue || !_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) + { + await SendErrorAsync(connection, "not_in_dungeon", ct); + return; + } + + var req = _ser.Deserialize(payload); + if (!dungeon.Simulation.Npcs.TryGetValue(req.NpcId, out var npc) || !npc.HasDialog || !npc.DialogTreeId.HasValue) + { + await SendAsync(connection, DungeonOpCodes.NPC_DIALOG_RESULT, new + { + success = false, + error = "npc_dialog_unavailable" + }, ct); + return; + } + + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var option = await db.DungeonNpcDialogOptions + .Include(o => o.Node) + .FirstOrDefaultAsync(o => o.Id == req.OptionId, ct); + + if (option == null || option.Node == null || option.Node.DialogTreeId != npc.DialogTreeId.Value) + { + await SendAsync(connection, DungeonOpCodes.NPC_DIALOG_RESULT, new + { + success = false, + error = "invalid_option" + }, ct); + return; + } + + var (conditionMet, conditionError) = await EvaluateDialogConditionAsync(db, session, option, ct); + if (!conditionMet) + { + await SendAsync(connection, DungeonOpCodes.NPC_DIALOG_RESULT, new + { + success = false, + error = conditionError ?? "condition_failed" + }, ct); + return; + } + + if (option.ConsumeConditionItem && + option.ConditionType == NpcDialogConditionType.HasItem && + int.TryParse(option.ConditionValue, out var consumeItemDefId)) + { + await ConsumeCharacterItemAsync(db, session.CharacterId, consumeItemDefId, Math.Max(1, option.ConditionQuantity), ct); + } + + var nextNode = option.NextNodeId.HasValue + ? await db.DungeonNpcDialogNodes.FirstOrDefaultAsync(n => n.Id == option.NextNodeId.Value && n.DialogTreeId == npc.DialogTreeId.Value, ct) + : null; + + if (nextNode != null) + { + await ApplyNpcDialogRewardsAsync(db, session, nextNode, ct); + await SendNpcDialogNodeAsync(connection, session, npc, nextNode.Id, ct); + await SendAsync(connection, DungeonOpCodes.NPC_DIALOG_RESULT, new + { + success = true, + npcId = npc.Id, + nextNodeId = nextNode.Id, + isTerminal = nextNode.IsTerminal + }, ct); + return; + } + + await SendAsync(connection, DungeonOpCodes.NPC_DIALOG_RESULT, new + { + success = true, + npcId = npc.Id, + nextNodeId = (int?)null, + isTerminal = true + }, ct); + } + + private async Task HandleNpcShopAction(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory payload, CancellationToken ct) + { + if (!session.CurrentDungeonId.HasValue || !_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) + { + await SendErrorAsync(connection, "not_in_dungeon", ct); + return; + } + + var req = _ser.Deserialize(payload); + if (!dungeon.Simulation.Npcs.TryGetValue(req.NpcId, out var npc) || !npc.CanShop || !npc.ShopId.HasValue) + { + await SendAsync(connection, DungeonOpCodes.NPC_SHOP_RESULT, new + { + success = false, + error = "npc_shop_unavailable" + }, ct); + return; + } + + if (!string.Equals(req.Action, "buy", StringComparison.OrdinalIgnoreCase)) + { + await SendAsync(connection, DungeonOpCodes.NPC_SHOP_RESULT, new + { + success = false, + error = "unsupported_shop_action", + message = "Only buy is currently supported." + }, ct); + return; + } + + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var shopItem = await db.DungeonNpcShopItems + .Include(s => s.ItemDefinition) + .FirstOrDefaultAsync(s => s.ShopId == npc.ShopId.Value && s.SlotIndex == req.SlotIndex, ct); + + if (shopItem == null || shopItem.ItemDefinition == null) + { + await SendAsync(connection, DungeonOpCodes.NPC_SHOP_RESULT, new + { + success = false, + error = "shop_item_not_found" + }, ct); + return; + } + + var quantity = Math.Max(1, req.Quantity); + if (!shopItem.Restocks) + { + quantity = Math.Min(quantity, shopItem.Quantity); + if (quantity <= 0) + { + await SendAsync(connection, DungeonOpCodes.NPC_SHOP_RESULT, new + { + success = false, + error = "out_of_stock" + }, ct); + return; + } + } + + var totalPrice = shopItem.PriceGold * quantity; + var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == session.CharacterId, ct); + if (character == null) + { + await SendAsync(connection, DungeonOpCodes.NPC_SHOP_RESULT, new + { + success = false, + error = "character_not_found" + }, ct); + return; + } + + if (character.Gold < totalPrice) + { + await SendAsync(connection, DungeonOpCodes.NPC_SHOP_RESULT, new + { + success = false, + error = "not_enough_gold", + requiredGold = totalPrice, + currentGold = character.Gold + }, ct); + return; + } + + var added = await AddItemToCharacterInventoryAsync( + db, + session.CharacterId, + shopItem.ItemDefinitionId, + quantity, + ct); + + if (!added) + { + await SendAsync(connection, DungeonOpCodes.NPC_SHOP_RESULT, new + { + success = false, + error = "inventory_full" + }, ct); + return; + } + + character.Gold -= totalPrice; + if (!shopItem.Restocks) + { + shopItem.Quantity = Math.Max(0, shopItem.Quantity - quantity); + } + + await db.SaveChangesAsync(ct); + session.Character.Gold = character.Gold; + + await SendAsync(connection, DungeonOpCodes.NPC_SHOP_RESULT, new + { + success = true, + npcId = npc.Id, + action = "buy", + itemDefinitionId = shopItem.ItemDefinitionId, + quantity, + totalPrice, + remainingGold = character.Gold, + remainingStock = shopItem.Quantity + }, ct); + + await HandleInventoryRequest(connection, session, ct); + await SendNpcShopStateAsync(connection, npc.ShopId.Value, ct); + } + + private async Task SendNpcDialogNodeAsync(IConnection connection, DungeonPlayerSession session, NpcInstance npc, int? nodeId, CancellationToken ct) + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + DungeonNpcDialogNode? node; + if (nodeId.HasValue) + { + node = await db.DungeonNpcDialogNodes + .FirstOrDefaultAsync(n => n.Id == nodeId.Value && n.DialogTreeId == npc.DialogTreeId, ct); + } + else + { + node = await db.DungeonNpcDialogNodes + .FirstOrDefaultAsync(n => n.DialogTreeId == npc.DialogTreeId && n.IsRoot, ct); + } + + if (node == null) + { + await SendAsync(connection, DungeonOpCodes.NPC_DIALOG_STATE, new + { + success = false, + error = "dialog_node_not_found", + npcId = npc.Id + }, ct); + return; + } + + var options = await db.DungeonNpcDialogOptions + .Where(o => o.NodeId == node.Id) + .OrderBy(o => o.SortOrder) + .ToListAsync(ct); + + var filtered = new List(); + foreach (var option in options) + { + var (ok, _) = await EvaluateDialogConditionAsync(db, session, option, ct); + if (!ok) continue; + + filtered.Add(new + { + id = option.Id, + text = option.PlayerText, + nextNodeId = option.NextNodeId + }); + } + + await SendAsync(connection, DungeonOpCodes.NPC_DIALOG_STATE, new + { + success = true, + npcId = npc.Id, + node = new + { + id = node.Id, + text = node.Text, + isTerminal = node.IsTerminal, + rewardGold = node.RewardGold, + rewardXp = node.RewardXp, + rewardItemDefinitionId = node.RewardItemDefinitionId, + rewardItemQuantity = node.RewardItemQuantity, + rewardQuestKey = node.RewardQuestKey + }, + options = filtered + }, ct); + } + + private async Task SendNpcShopStateAsync(IConnection connection, int shopId, CancellationToken ct) + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var shop = await db.DungeonNpcShops + .Include(s => s.Items) + .ThenInclude(i => i.ItemDefinition) + .FirstOrDefaultAsync(s => s.Id == shopId && s.IsEnabled, ct); + + if (shop == null) + { + await SendAsync(connection, DungeonOpCodes.NPC_SHOP_STATE, new + { + success = false, + error = "shop_not_found" + }, ct); + return; + } + + var now = DateTime.UtcNow; + foreach (var item in shop.Items.Where(i => i.Restocks && i.RestockIntervalSeconds > 0 && i.LastRestockAt.HasValue)) + { + if ((now - item.LastRestockAt.Value).TotalSeconds >= item.RestockIntervalSeconds) + { + item.LastRestockAt = now; + } + } + await db.SaveChangesAsync(ct); + + await SendAsync(connection, DungeonOpCodes.NPC_SHOP_STATE, new + { + success = true, + shop = new + { + id = shop.Id, + name = shop.Name, + items = shop.Items.OrderBy(i => i.SlotIndex).Select(i => new + { + slotIndex = i.SlotIndex, + itemDefinitionId = i.ItemDefinitionId, + itemName = i.ItemDefinition != null ? i.ItemDefinition.Name : $"Item {i.ItemDefinitionId}", + quantity = i.Quantity, + priceGold = i.PriceGold, + restocks = i.Restocks, + restockIntervalSeconds = i.RestockIntervalSeconds + }) + } + }, ct); + } + + private async Task<(bool Ok, string? Error)> EvaluateDialogConditionAsync(GameDbContext db, DungeonPlayerSession session, DungeonNpcDialogOption option, CancellationToken ct) + { + switch (option.ConditionType) + { + case NpcDialogConditionType.None: + return (true, null); + + case NpcDialogConditionType.HasItem: + if (!int.TryParse(option.ConditionValue, out var itemDefinitionId)) + return (false, "invalid_condition_value"); + + var itemCount = await db.DungeonCharacterItems + .Where(i => i.CharacterId == session.CharacterId && i.ItemDefinitionId == itemDefinitionId) + .SumAsync(i => (int?)i.Quantity, ct) ?? 0; + + return itemCount >= Math.Max(1, option.ConditionQuantity) + ? (true, null) + : (false, "requires_item"); + + case NpcDialogConditionType.CharacterLevelAtLeast: + if (!int.TryParse(option.ConditionValue, out var minLevel)) + return (false, "invalid_condition_value"); + return session.Character.Level >= minLevel ? (true, null) : (false, "level_too_low"); + + case NpcDialogConditionType.CharacterLevelAtMost: + if (!int.TryParse(option.ConditionValue, out var maxLevel)) + return (false, "invalid_condition_value"); + return session.Character.Level <= maxLevel ? (true, null) : (false, "level_too_high"); + + case NpcDialogConditionType.GoldAtLeast: + if (!long.TryParse(option.ConditionValue, out var minGold)) + return (false, "invalid_condition_value"); + return session.Character.Gold >= minGold ? (true, null) : (false, "not_enough_gold"); + + // Quest condition wiring will hook into quest service when added. + case NpcDialogConditionType.QuestCompleted: + case NpcDialogConditionType.QuestActive: + return (false, "quest_system_not_ready"); + + default: + return (false, "unsupported_condition"); + } + } + + private async Task ApplyNpcDialogRewardsAsync(GameDbContext db, DungeonPlayerSession session, DungeonNpcDialogNode node, CancellationToken ct) + { + var modified = false; + var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == session.CharacterId, ct); + if (character == null) + return; + + if (node.RewardGold > 0) + { + character.Gold += node.RewardGold; + session.Character.Gold = character.Gold; + modified = true; + } + + if (node.RewardXp > 0) + { + character.Experience += node.RewardXp; + session.Character.Experience = character.Experience; + modified = true; + } + + if (node.RewardItemDefinitionId.HasValue && node.RewardItemQuantity > 0) + { + var added = await AddItemToCharacterInventoryAsync( + db, + session.CharacterId, + node.RewardItemDefinitionId.Value, + node.RewardItemQuantity, + ct); + modified = modified || added; + } + + if (modified) + { + await db.SaveChangesAsync(ct); + } + } + + private async Task AddItemToCharacterInventoryAsync(GameDbContext db, ulong characterId, int itemDefinitionId, int quantity, CancellationToken ct) + { + if (quantity <= 0) + return true; + + var itemDef = await db.DungeonItemDefinitions.FirstOrDefaultAsync(i => i.Id == itemDefinitionId, ct); + if (itemDef == null) + return false; + + var inventoryItems = await db.DungeonCharacterItems + .Where(i => i.CharacterId == characterId && !i.IsEquipped) + .ToListAsync(ct); + + var remaining = quantity; + if (itemDef.Stackable) + { + foreach (var stack in inventoryItems.Where(i => i.ItemDefinitionId == itemDefinitionId && i.Quantity < itemDef.MaxStack)) + { + var canAdd = Math.Min(remaining, itemDef.MaxStack - stack.Quantity); + if (canAdd <= 0) continue; + stack.Quantity += canAdd; + remaining -= canAdd; + if (remaining <= 0) + return true; + } + } + + var usedSlots = inventoryItems.Select(i => i.SlotIndex).ToHashSet(); + for (var slot = 0; slot < 30 && remaining > 0; slot++) + { + if (usedSlots.Contains(slot)) + continue; + + var addQty = itemDef.Stackable ? Math.Min(remaining, itemDef.MaxStack) : 1; + db.DungeonCharacterItems.Add(new DungeonCharacterItem + { + CharacterId = characterId, + ItemDefinitionId = itemDefinitionId, + Quantity = addQty, + SlotIndex = slot, + IsEquipped = false + }); + + usedSlots.Add(slot); + remaining -= addQty; + } + + return remaining <= 0; + } + + private async Task ConsumeCharacterItemAsync(GameDbContext db, ulong characterId, int itemDefinitionId, int quantity, CancellationToken ct) + { + if (quantity <= 0) + return; + + var items = await db.DungeonCharacterItems + .Where(i => i.CharacterId == characterId && i.ItemDefinitionId == itemDefinitionId && !i.IsEquipped) + .OrderBy(i => i.SlotIndex) + .ToListAsync(ct); + + var remaining = quantity; + foreach (var item in items) + { + if (remaining <= 0) break; + var take = Math.Min(item.Quantity, remaining); + item.Quantity -= take; + remaining -= take; + if (item.Quantity <= 0) + { + db.DungeonCharacterItems.Remove(item); + } + } + + await db.SaveChangesAsync(ct); + } +} + diff --git a/Game/Dungeon/DungeonHandler.Stash.cs b/Game/Dungeon/DungeonHandler.Stash.cs index 73f4044..e264338 100644 --- a/Game/Dungeon/DungeonHandler.Stash.cs +++ b/Game/Dungeon/DungeonHandler.Stash.cs @@ -13,11 +13,11 @@ using Server.Networking.Messages; namespace GameServer.Dungeon; -#region Stash System (VIP Feature) +#region Stash System public sealed partial class DungeonHandler { - private const int STASH_SLOTS = 50; // Number of stash slots for VIP + private const int STASH_SLOTS = 50; // Number of stash slots /// /// Handle request to view stash contents @@ -27,19 +27,6 @@ public sealed partial class DungeonHandler using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); - // 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) @@ -80,19 +67,6 @@ public sealed partial class DungeonHandler using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); - // 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) { @@ -223,19 +197,6 @@ public sealed partial class DungeonHandler using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); - // 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) { diff --git a/Game/Dungeon/DungeonHandler.cs b/Game/Dungeon/DungeonHandler.cs index 3f38403..121483e 100644 --- a/Game/Dungeon/DungeonHandler.cs +++ b/Game/Dungeon/DungeonHandler.cs @@ -43,6 +43,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler private Dictionary _abilityDefinitions = new(); private Dictionary _abilityAnimationMappings = new(); private Dictionary _mobSpriteConfigs = new(); // MobDefinitionId -> SpriteConfig JSON + private Dictionary _npcDefinitions = new(); private bool _initialized = false; private volatile bool _spatialStateFilterEnabled = true; private volatile float _spatialStateRadiusPx = 32f * 28f; // 28 tiles @@ -163,6 +164,9 @@ public sealed partial class DungeonHandler : IClientMessageHandler DungeonOpCodes.DUNGEON_INPUT_CHEST, DungeonOpCodes.DUNGEON_INPUT_PORTAL, DungeonOpCodes.DUNGEON_INPUT_FIRE_PROJECTILE, + DungeonOpCodes.DUNGEON_INPUT_NPC_INTERACT, + DungeonOpCodes.DUNGEON_INPUT_NPC_DIALOG_SELECT, + DungeonOpCodes.DUNGEON_INPUT_NPC_SHOP_ACTION, DungeonOpCodes.INVENTORY_REQUEST, DungeonOpCodes.EQUIP_ITEM, DungeonOpCodes.UNEQUIP_ITEM, @@ -189,7 +193,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler DungeonOpCodes.CRAFTING_SKILLS_REQUEST, DungeonOpCodes.CRAFTING_RECIPES_REQUEST, DungeonOpCodes.CRAFTING_ATTEMPT, - // Stash (VIP) + // Stash DungeonOpCodes.STASH_REQUEST, DungeonOpCodes.STASH_DEPOSIT, DungeonOpCodes.STASH_WITHDRAW, @@ -234,7 +238,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler if (!_sessions.TryGet(connection.Id, out var accountId, out _)) { // Ignore stray input before auth to avoid booting the client during connect - if (opCode is >= DungeonOpCodes.DUNGEON_INPUT_MOVE and <= DungeonOpCodes.DUNGEON_INPUT_FIRE_PROJECTILE) + if (opCode is >= DungeonOpCodes.DUNGEON_INPUT_MOVE and <= DungeonOpCodes.DUNGEON_INPUT_NPC_SHOP_ACTION) return; await SendErrorAsync(connection, $"auth_required for packet: {opCode}", ct); @@ -297,6 +301,15 @@ public sealed partial class DungeonHandler : IClientMessageHandler case DungeonOpCodes.DUNGEON_INPUT_FIRE_PROJECTILE: await HandleFireProjectile(connection, session, payload, ct); break; + case DungeonOpCodes.DUNGEON_INPUT_NPC_INTERACT: + await HandleNpcInteract(connection, session, payload, ct); + break; + case DungeonOpCodes.DUNGEON_INPUT_NPC_DIALOG_SELECT: + await HandleNpcDialogSelect(connection, session, payload, ct); + break; + case DungeonOpCodes.DUNGEON_INPUT_NPC_SHOP_ACTION: + await HandleNpcShopAction(connection, session, payload, ct); + break; case DungeonOpCodes.INVENTORY_REQUEST: await HandleInventoryRequest(connection, session, ct); @@ -379,7 +392,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler await HandleCraftingAttempt(connection, session, payload, ct); break; - // Stash (VIP Feature) + // Stash case DungeonOpCodes.STASH_REQUEST: await HandleStashRequest(connection, session, ct); break; @@ -708,7 +721,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler var (layout, layoutV2) = await GenerateDungeonLayoutWithFallbackAsync(seed, tier, ct); - var simulation = new DungeonSimulation(layout, tier, _mobDefinitions, bracketMin, _abilityDefinitions, _mobSpriteConfigs, _abilityAnimationMappings); + var simulation = new DungeonSimulation(layout, tier, _mobDefinitions, bracketMin, _abilityDefinitions, _mobSpriteConfigs, _abilityAnimationMappings, _npcDefinitions); instance = new DungeonInstance { @@ -1683,15 +1696,15 @@ public sealed partial class DungeonHandler : IClientMessageHandler return; // Generate loot from the mob's loot tables - var loot = _lootService.GenerateMobLoot( + var lootResult = _lootService.GenerateMobLoot( mob.DefinitionId, dungeon.Tier, 1.0f ); // Collect all items (normal loot + carried player loot) - var allItems = new List(loot); - long totalGold = 0; + var allItems = new List(lootResult.Items); + long totalGold = lootResult.Gold; // Add any carried player loot from player kills if (mob.HasCarriedLoot) @@ -2862,6 +2875,11 @@ public sealed partial class DungeonHandler : IClientMessageHandler ? nearbyOrRelevantMobs : nearbyOrRelevantMobs.Where(m => !m.IsAlive || m.TargetId == session.CharacterId).ToList(); var visibleMobIds = visibleMobs.Select(m => m.Id).ToHashSet(); + var visibleNpcs = (sendSpatialThisTick + ? sim.Npcs.Values.Where(n => !spatialFiltering || IsNearby(n.X, n.Y)) + : Enumerable.Empty()) + .ToList(); + var visibleNpcIds = visibleNpcs.Select(n => n.Id).ToHashSet(); bool sendMobCatalog = session.CurrentDungeonId.HasValue && session.InitialMobCatalogDungeonId != session.CurrentDungeonId; @@ -2922,6 +2940,28 @@ public sealed partial class DungeonHandler : IClientMessageHandler tintColor = m.TintColor, scale = m.Scale }), + npcs = visibleNpcs.Select(n => new + { + id = n.Id, + definitionId = n.DefinitionId, + name = n.Name, + x = n.X, + y = n.Y, + rotation = n.Rotation, + level = n.Level, + health = n.Health, + maxHealth = n.MaxHealth, + isAlive = n.IsAlive, + isKillable = n.IsKillable, + canShop = n.CanShop, + hasDialog = n.HasDialog, + behavior = n.BehaviorMode.ToString().ToLower(), + onAttackBehavior = n.OnAttackBehavior.ToString().ToLower(), + currentAnimation = n.CurrentAnimation, + spriteConfig = DeserializeSpriteConfigSafe(n.SpriteConfigJson), + tintColor = n.TintColor, + scale = n.Scale + }), mobCatalog = sendMobCatalog ? sim.Mobs.Values.Select(m => new { id = m.Id, @@ -3095,7 +3135,11 @@ public sealed partial class DungeonHandler : IClientMessageHandler targetX = e.TargetX, targetY = e.TargetY, targetId = e.TargetId - }) + }), + npcInteraction = new + { + visibleNpcIds + } }, exitPosition = sim.Layout.ExitPosition != null ? new diff --git a/Game/Dungeon/DungeonLayout.cs b/Game/Dungeon/DungeonLayout.cs index e7ac531..0e84cea 100644 --- a/Game/Dungeon/DungeonLayout.cs +++ b/Game/Dungeon/DungeonLayout.cs @@ -25,6 +25,7 @@ public class DungeonLayout public List MobSpawns { get; set; } = new(); public List ChestSpawns { get; set; } = new(); + public List NpcSpawns { get; set; } = new(); public int TotalMobs { get; set; } public int TotalChests { get; set; } @@ -134,6 +135,15 @@ public class DungeonLayout id = c.Id, x = c.X, y = c.Y, type = c.ChestType.ToString(), roomIndex = c.RoomIndex + }), + npcs = NpcSpawns.Select(n => new + { + id = n.Id, + x = n.X, + y = n.Y, + npcDefinitionId = n.NpcDefinitionId, + npcName = n.NpcName, + roomIndex = n.RoomIndex }) }); } diff --git a/Game/Dungeon/DungeonNpcSpawn.cs b/Game/Dungeon/DungeonNpcSpawn.cs new file mode 100644 index 0000000..ad62ff0 --- /dev/null +++ b/Game/Dungeon/DungeonNpcSpawn.cs @@ -0,0 +1,13 @@ +namespace GameServer.Dungeon; + +public class DungeonNpcSpawn +{ + public int Id { get; set; } + public int X { get; set; } + public int Y { get; set; } + public int? NpcDefinitionId { get; set; } + public string? NpcName { get; set; } + public int RoomIndex { get; set; } + public bool IsAlive { get; set; } = true; +} + diff --git a/Game/Dungeon/DungeonSimulation.cs b/Game/Dungeon/DungeonSimulation.cs index 0797bc3..9e6f79c 100644 --- a/Game/Dungeon/DungeonSimulation.cs +++ b/Game/Dungeon/DungeonSimulation.cs @@ -29,14 +29,17 @@ public partial class DungeonSimulation public ConcurrentDictionary LootChests { get; } = new(); public ConcurrentDictionary Projectiles { get; } = new(); public ConcurrentDictionary HazardZones { get; } = new(); + public ConcurrentDictionary Npcs { get; } = new(); // ID generators private int _nextLootChestId = 1; private int _nextProjectileId = 1; private int _nextHazardId = 1; + private int _nextNpcId = 1; public int GetNextLootChestId() => _nextLootChestId++; public int GetNextProjectileId() => _nextProjectileId++; public int GetNextHazardId() => _nextHazardId++; + public int GetNextNpcId() => _nextNpcId++; // Combat tracking private readonly List _pendingDamageEvents = new(); @@ -54,7 +57,9 @@ public partial class DungeonSimulation private readonly Dictionary? _abilityDefinitions; private readonly Dictionary? _spriteConfigs; private readonly Dictionary? _abilityAnimationMappings; + private readonly Dictionary? _npcDefinitions; private readonly List<(int MobDefinitionId, float X, float Y, int Tier)> _pendingSummons = new(); + private readonly Random _npcWanderRandom = new(); public DungeonSimulation( DungeonLayout layout, @@ -63,7 +68,8 @@ public partial class DungeonSimulation int bracketMin = 1, Dictionary? abilityDefinitions = null, Dictionary? spriteConfigs = null, - Dictionary? abilityAnimationMappings = null) + Dictionary? abilityAnimationMappings = null, + Dictionary? npcDefinitions = null) { Layout = layout; Tier = tier; @@ -72,11 +78,44 @@ public partial class DungeonSimulation _abilityDefinitions = abilityDefinitions; _spriteConfigs = spriteConfigs; _abilityAnimationMappings = abilityAnimationMappings; + _npcDefinitions = npcDefinitions; SpawnMobs(); + SpawnNpcs(); InitializeChests(); SpawnExitPortal(); } + + private void SpawnNpcs() + { + if (_npcDefinitions == null || _npcDefinitions.Count == 0 || Layout.NpcSpawns.Count == 0) + return; + + foreach (var spawn in Layout.NpcSpawns.Where(s => s.IsAlive)) + { + DungeonNpcDefinition? def = null; + if (spawn.NpcDefinitionId.HasValue) + { + _npcDefinitions.TryGetValue(spawn.NpcDefinitionId.Value, out def); + } + + if (def == null || !def.IsEnabled) + continue; + + var npc = NpcInstance.FromDefinition( + def, + GetNextNpcId(), + spawn.X * 32 + 16, + spawn.Y * 32 + 16); + + if (!string.IsNullOrWhiteSpace(spawn.NpcName)) + { + npc.Name = spawn.NpcName!; + } + + Npcs[npc.Id] = npc; + } + } private void SpawnExitPortal() { @@ -390,6 +429,8 @@ public partial class DungeonSimulation UpdatePlayer(player); } + UpdateNpcs(); + // Keep corpses in the world after death (even after loot is emptied). // We still stamp when loot becomes empty so UI/inspection logic can reference it. foreach (var mob in Mobs.Values.Where(m => !m.IsAlive)) @@ -429,6 +470,43 @@ public partial class DungeonSimulation Phase = Phase }; } + + private void UpdateNpcs() + { + foreach (var npc in Npcs.Values) + { + if (!npc.IsAlive || !npc.CanWander || npc.BehaviorMode != DataServer.Data.Enums.NpcBehaviorMode.Wander) + continue; + + npc.NextWanderIn -= TickDelta; + if (npc.NextWanderIn > 0f) + continue; + + npc.NextWanderIn = Math.Max(0.25f, npc.WanderIntervalSeconds); + + // Random short-step wander constrained by radius around spawn. + var step = 12f; + var dx = (float)(_npcWanderRandom.NextDouble() * 2.0 - 1.0) * step; + var dy = (float)(_npcWanderRandom.NextDouble() * 2.0 - 1.0) * step; + var nx = npc.X + dx; + var ny = npc.Y + dy; + + var distX = nx - npc.SpawnX; + var distY = ny - npc.SpawnY; + var maxDistSq = npc.WanderRadiusPx * npc.WanderRadiusPx; + if ((distX * distX) + (distY * distY) > maxDistSq) + continue; + + var tileX = (int)MathF.Floor(nx / 32f); + var tileY = (int)MathF.Floor(ny / 32f); + if (!Layout.IsWalkable(tileX, tileY)) + continue; + + npc.X = nx; + npc.Y = ny; + npc.Rotation = MathF.Atan2(dy, dx); + } + } /// /// Process a mob's ability/attack against a target diff --git a/Game/Dungeon/LootService.cs b/Game/Dungeon/LootService.cs index 0fccfdd..2c454c7 100644 --- a/Game/Dungeon/LootService.cs +++ b/Game/Dungeon/LootService.cs @@ -16,6 +16,12 @@ public class LootDrop public int Quantity { get; set; } } +public class LootRollResult +{ + public List Items { get; set; } = new(); + public long Gold { get; set; } +} + /// /// Service for generating loot from loot tables /// @@ -109,15 +115,15 @@ public class LootService /// /// Generate loot for a mob kill /// - public List GenerateMobLoot(int mobDefinitionId, int dungeonTier, float dropChanceMultiplier = 1.0f) + public LootRollResult GenerateMobLoot(int mobDefinitionId, int dungeonTier, float dropChanceMultiplier = 1.0f) { - var loot = new List(); + var result = new LootRollResult(); if (!_mobLootTableMappings.TryGetValue(mobDefinitionId, out var mappings)) { _log.LogWarning("No loot tables found for mob {MobId}. Available mappings: {MobIds}", mobDefinitionId, string.Join(", ", _mobLootTableMappings.Keys)); - return loot; // No loot tables for this mob + return result; // No loot tables for this mob } _log.LogDebug("Generating loot for mob {MobId}, found {Count} table mappings", mobDefinitionId, mappings.Count); @@ -137,31 +143,29 @@ public class LootService // Generate drops from this table var drops = GenerateFromTable(table, dungeonTier, dropChanceMultiplier); - loot.AddRange(drops); + result.Items.AddRange(drops.Items); + result.Gold += drops.Gold; } - _log.LogDebug("Generated {Count} loot drops for mob {MobId}", loot.Count, mobDefinitionId); + _log.LogDebug("Generated {Count} loot drops and {Gold} gold for mob {MobId}", result.Items.Count, result.Gold, mobDefinitionId); - return loot; + return result; } /// /// Generate loot from a specific loot table /// - public List GenerateFromTable(DungeonLootTable table, int dungeonTier, float extraMultiplier = 1.0f) + public LootRollResult GenerateFromTable(DungeonLootTable table, int dungeonTier, float extraMultiplier = 1.0f) { - var loot = new List(); + var result = new LootRollResult(); var entries = table.Entries.ToList(); - if (entries.Count == 0) - return loot; - float totalMultiplier = table.DropChanceMultiplier * extraMultiplier; // First, add all guaranteed drops foreach (var entry in entries.Where(e => e.Guaranteed)) { - AddDrop(loot, entry); + AddDrop(result.Items, entry); } // Determine how many additional drops @@ -181,7 +185,7 @@ public class LootService if (_random.NextDouble() < chance) { - AddDrop(loot, entry); + AddDrop(result.Items, entry); dropCount--; } } @@ -192,7 +196,7 @@ public class LootService var selected = WeightedRandomSelect(nonGuaranteed); if (selected != null) { - AddDrop(loot, selected); + AddDrop(result.Items, selected); dropCount--; } else @@ -200,8 +204,17 @@ public class LootService break; } } - - return loot; + + // Roll optional gold for this table + var goldChance = Math.Clamp(table.GoldDropChance, 0f, 1f) * totalMultiplier; + if (table.MaxGold > 0 && goldChance > 0f && _random.NextDouble() < goldChance) + { + var minGold = Math.Max(0, table.MinGold); + var maxGold = Math.Max(minGold, table.MaxGold); + result.Gold += _random.Next(minGold, maxGold + 1); + } + + return result; } private void AddDrop(List loot, DungeonLootTableEntry entry) diff --git a/Game/Dungeon/NpcInstance.cs b/Game/Dungeon/NpcInstance.cs new file mode 100644 index 0000000..4f3b375 --- /dev/null +++ b/Game/Dungeon/NpcInstance.cs @@ -0,0 +1,75 @@ +using DataServer.Data.Entities; +using DataServer.Data.Enums; + +namespace GameServer.Dungeon; + +public class NpcInstance +{ + public int Id { get; set; } + public int DefinitionId { get; set; } + public string Name { get; set; } = ""; + + public float X { get; set; } + public float Y { get; set; } + public float SpawnX { get; set; } + public float SpawnY { get; set; } + public float Rotation { get; set; } + + public int Level { get; set; } = 1; + public int Health { get; set; } = 100; + public int MaxHealth { get; set; } = 100; + public bool IsAlive { get; set; } = true; + public bool IsKillable { get; set; } = true; + public bool CanShop { get; set; } = false; + public bool HasDialog { get; set; } = false; + public bool CanWander { get; set; } = true; + + public NpcBehaviorMode BehaviorMode { get; set; } = NpcBehaviorMode.Wander; + public NpcOnAttackBehavior OnAttackBehavior { get; set; } = NpcOnAttackBehavior.FightBack; + + public float WanderRadiusPx { get; set; } = 96f; + public float WanderIntervalSeconds { get; set; } = 2.5f; + public float NextWanderIn { get; set; } = 2.5f; + + public int? LootTableId { get; set; } + public int? ShopId { get; set; } + public int? DialogTreeId { get; set; } + + public string CurrentAnimation { get; set; } = "idle_down"; + public string? SpriteConfigJson { get; set; } + public string TintColor { get; set; } = "#ffffff"; + public float Scale { get; set; } = 1f; + + public static NpcInstance FromDefinition(DungeonNpcDefinition def, int id, float x, float y) + { + return new NpcInstance + { + Id = id, + DefinitionId = def.Id, + Name = def.Name, + X = x, + Y = y, + SpawnX = x, + SpawnY = y, + Level = Math.Max(1, def.Level), + Health = Math.Max(1, def.MaxHealth), + MaxHealth = Math.Max(1, def.MaxHealth), + IsKillable = def.IsKillable, + CanShop = def.CanShop, + HasDialog = def.HasDialog, + CanWander = def.CanWander, + BehaviorMode = def.BehaviorMode, + OnAttackBehavior = def.OnAttackBehavior, + WanderRadiusPx = Math.Max(0f, def.WanderRadiusPx), + WanderIntervalSeconds = Math.Max(0.25f, def.WanderIntervalSeconds), + NextWanderIn = Math.Max(0.25f, def.WanderIntervalSeconds), + LootTableId = def.LootTableId, + ShopId = def.ShopId, + DialogTreeId = def.DialogTreeId, + SpriteConfigJson = def.SpriteConfigJson, + TintColor = string.IsNullOrWhiteSpace(def.TintColor) ? "#ffffff" : def.TintColor, + Scale = Math.Max(0.1f, def.Scale) + }; + } +} + diff --git a/Migrations/20260214153000_NpcSystemAndLootTableGold.cs b/Migrations/20260214153000_NpcSystemAndLootTableGold.cs new file mode 100644 index 0000000..75b88ec --- /dev/null +++ b/Migrations/20260214153000_NpcSystemAndLootTableGold.cs @@ -0,0 +1,285 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SystemRevivalServer.Migrations +{ + /// + public partial class NpcSystemAndLootTableGold : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "GoldDropChance", + table: "dungeon_loot_tables", + type: "float", + nullable: false, + defaultValue: 0f); + + migrationBuilder.AddColumn( + name: "MaxGold", + table: "dungeon_loot_tables", + type: "int", + nullable: false, + defaultValue: 0); + + migrationBuilder.AddColumn( + name: "MinGold", + table: "dungeon_loot_tables", + type: "int", + nullable: false, + defaultValue: 0); + + migrationBuilder.CreateTable( + name: "dungeon_npc_dialog_trees", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + Name = table.Column(type: "varchar(64)", maxLength: 64, nullable: false), + Description = table.Column(type: "varchar(256)", maxLength: 256, nullable: false), + IsEnabled = table.Column(type: "tinyint(1)", nullable: false), + CreatedAt = table.Column(type: "datetime(6)", nullable: false), + UpdatedAt = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_dungeon_npc_dialog_trees", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "dungeon_npc_shops", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + Name = table.Column(type: "varchar(64)", maxLength: 64, nullable: false), + IsEnabled = table.Column(type: "tinyint(1)", nullable: false), + CreatedAt = table.Column(type: "datetime(6)", nullable: false), + UpdatedAt = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_dungeon_npc_shops", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "dungeon_npc_dialog_nodes", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + DialogTreeId = table.Column(type: "int", nullable: false), + NodeKey = table.Column(type: "varchar(128)", maxLength: 128, nullable: false), + Text = table.Column(type: "varchar(2048)", maxLength: 2048, nullable: false), + IsRoot = table.Column(type: "tinyint(1)", nullable: false), + IsTerminal = table.Column(type: "tinyint(1)", nullable: false), + RewardType = table.Column(type: "varchar(64)", maxLength: 64, nullable: true), + RewardItemDefinitionId = table.Column(type: "int", nullable: true), + RewardItemQuantity = table.Column(type: "int", nullable: false), + RewardGold = table.Column(type: "bigint", nullable: false), + RewardXp = table.Column(type: "bigint", nullable: false), + RewardQuestKey = table.Column(type: "varchar(64)", maxLength: 64, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_dungeon_npc_dialog_nodes", x => x.Id); + table.ForeignKey( + name: "FK_dungeon_npc_dialog_nodes_dungeon_npc_dialog_trees_DialogTreeId", + column: x => x.DialogTreeId, + principalTable: "dungeon_npc_dialog_trees", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "dungeon_npc_shop_items", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + ShopId = table.Column(type: "int", nullable: false), + SlotIndex = table.Column(type: "int", nullable: false), + ItemDefinitionId = table.Column(type: "int", nullable: false), + Quantity = table.Column(type: "int", nullable: false), + PriceGold = table.Column(type: "bigint", nullable: false), + Restocks = table.Column(type: "tinyint(1)", nullable: false), + RestockIntervalSeconds = table.Column(type: "int", nullable: false), + LastRestockAt = table.Column(type: "datetime(6)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_dungeon_npc_shop_items", x => x.Id); + table.ForeignKey( + name: "FK_dungeon_npc_shop_items_dungeon_item_definitions_ItemDefinitionId", + column: x => x.ItemDefinitionId, + principalTable: "dungeon_item_definitions", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_dungeon_npc_shop_items_dungeon_npc_shops_ShopId", + column: x => x.ShopId, + principalTable: "dungeon_npc_shops", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "dungeon_npc_definitions", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + Name = table.Column(type: "varchar(64)", maxLength: 64, nullable: false), + Key = table.Column(type: "varchar(64)", maxLength: 64, nullable: false), + Description = table.Column(type: "varchar(256)", maxLength: 256, nullable: false), + Level = table.Column(type: "int", nullable: false), + IsEnabled = table.Column(type: "tinyint(1)", nullable: false), + IsKillable = table.Column(type: "tinyint(1)", nullable: false), + CanShop = table.Column(type: "tinyint(1)", nullable: false), + HasDialog = table.Column(type: "tinyint(1)", nullable: false), + CanWander = table.Column(type: "tinyint(1)", nullable: false), + BehaviorMode = table.Column(type: "int", nullable: false), + OnAttackBehavior = table.Column(type: "int", nullable: false), + MaxHealth = table.Column(type: "int", nullable: false), + AttackPower = table.Column(type: "int", nullable: false), + Defense = table.Column(type: "int", nullable: false), + Strength = table.Column(type: "int", nullable: false), + Dexterity = table.Column(type: "int", nullable: false), + Intelligence = table.Column(type: "int", nullable: false), + Wisdom = table.Column(type: "int", nullable: false), + Endurance = table.Column(type: "int", nullable: false), + ResistancesJson = table.Column(type: "varchar(2048)", maxLength: 2048, nullable: false), + SpriteConfigJson = table.Column(type: "varchar(4096)", maxLength: 4096, nullable: true), + TintColor = table.Column(type: "varchar(16)", maxLength: 16, nullable: false), + Scale = table.Column(type: "float", nullable: false), + WanderRadiusPx = table.Column(type: "float", nullable: false), + WanderIntervalSeconds = table.Column(type: "float", nullable: false), + LootTableId = table.Column(type: "int", nullable: true), + ShopId = table.Column(type: "int", nullable: true), + DialogTreeId = table.Column(type: "int", nullable: true), + AbilityDefinitionIdsJson = table.Column(type: "varchar(2048)", maxLength: 2048, nullable: false), + CreatedAt = table.Column(type: "datetime(6)", nullable: false), + UpdatedAt = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_dungeon_npc_definitions", x => x.Id); + table.ForeignKey( + name: "FK_dungeon_npc_definitions_dungeon_loot_tables_LootTableId", + column: x => x.LootTableId, + principalTable: "dungeon_loot_tables", + principalColumn: "Id"); + table.ForeignKey( + name: "FK_dungeon_npc_definitions_dungeon_npc_dialog_trees_DialogTreeId", + column: x => x.DialogTreeId, + principalTable: "dungeon_npc_dialog_trees", + principalColumn: "Id"); + table.ForeignKey( + name: "FK_dungeon_npc_definitions_dungeon_npc_shops_ShopId", + column: x => x.ShopId, + principalTable: "dungeon_npc_shops", + principalColumn: "Id"); + }); + + migrationBuilder.CreateTable( + name: "dungeon_npc_dialog_options", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + NodeId = table.Column(type: "int", nullable: false), + PlayerText = table.Column(type: "varchar(256)", maxLength: 256, nullable: false), + NextNodeId = table.Column(type: "int", nullable: true), + ConditionType = table.Column(type: "int", nullable: false), + ConditionValue = table.Column(type: "varchar(64)", maxLength: 64, nullable: true), + ConditionQuantity = table.Column(type: "int", nullable: false), + ConsumeConditionItem = table.Column(type: "tinyint(1)", nullable: false), + SortOrder = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_dungeon_npc_dialog_options", x => x.Id); + table.ForeignKey( + name: "FK_dungeon_npc_dialog_options_dungeon_npc_dialog_nodes_NodeId", + column: x => x.NodeId, + principalTable: "dungeon_npc_dialog_nodes", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_dungeon_npc_definitions_DialogTreeId", + table: "dungeon_npc_definitions", + column: "DialogTreeId"); + + migrationBuilder.CreateIndex( + name: "IX_dungeon_npc_definitions_LootTableId", + table: "dungeon_npc_definitions", + column: "LootTableId"); + + migrationBuilder.CreateIndex( + name: "IX_dungeon_npc_definitions_ShopId", + table: "dungeon_npc_definitions", + column: "ShopId"); + + migrationBuilder.CreateIndex( + name: "IX_dungeon_npc_dialog_nodes_DialogTreeId", + table: "dungeon_npc_dialog_nodes", + column: "DialogTreeId"); + + migrationBuilder.CreateIndex( + name: "IX_dungeon_npc_dialog_options_NodeId", + table: "dungeon_npc_dialog_options", + column: "NodeId"); + + migrationBuilder.CreateIndex( + name: "IX_dungeon_npc_shop_items_ItemDefinitionId", + table: "dungeon_npc_shop_items", + column: "ItemDefinitionId"); + + migrationBuilder.CreateIndex( + name: "IX_dungeon_npc_shop_items_ShopId", + table: "dungeon_npc_shop_items", + column: "ShopId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "dungeon_npc_definitions"); + + migrationBuilder.DropTable( + name: "dungeon_npc_dialog_options"); + + migrationBuilder.DropTable( + name: "dungeon_npc_shop_items"); + + migrationBuilder.DropTable( + name: "dungeon_npc_dialog_nodes"); + + migrationBuilder.DropTable( + name: "dungeon_npc_shops"); + + migrationBuilder.DropTable( + name: "dungeon_npc_dialog_trees"); + + migrationBuilder.DropColumn( + name: "GoldDropChance", + table: "dungeon_loot_tables"); + + migrationBuilder.DropColumn( + name: "MaxGold", + table: "dungeon_loot_tables"); + + migrationBuilder.DropColumn( + name: "MinGold", + table: "dungeon_loot_tables"); + } + } +} + diff --git a/Networking/Messages/DungeonOpCodes.cs b/Networking/Messages/DungeonOpCodes.cs index cc56d9d..6246822 100644 --- a/Networking/Messages/DungeonOpCodes.cs +++ b/Networking/Messages/DungeonOpCodes.cs @@ -34,6 +34,9 @@ public static class DungeonOpCodes public const int DUNGEON_INPUT_CHEST = 403; public const int DUNGEON_INPUT_PORTAL = 404; public const int DUNGEON_INPUT_FIRE_PROJECTILE = 405; + public const int DUNGEON_INPUT_NPC_INTERACT = 406; + public const int DUNGEON_INPUT_NPC_DIALOG_SELECT = 407; + public const int DUNGEON_INPUT_NPC_SHOP_ACTION = 408; // Escape (450-499) public const int ESCAPE_START = 450; @@ -102,10 +105,17 @@ public static class DungeonOpCodes // Server Broadcast (600-609) public const int SERVER_BROADCAST = 600; - // Stash (610-619) - VIP Feature + // Stash (610-619) public const int STASH_REQUEST = 610; // Request stash contents public const int STASH_STATE = 611; // Stash contents response public const int STASH_DEPOSIT = 612; // Move item from inventory to stash public const int STASH_WITHDRAW = 613; // Move item from stash to inventory public const int STASH_RESULT = 614; // Result of deposit/withdraw operation + + // NPC Interaction (620-639) + public const int NPC_INTERACT_STATE = 620; + public const int NPC_DIALOG_STATE = 621; + public const int NPC_DIALOG_RESULT = 622; + public const int NPC_SHOP_STATE = 623; + public const int NPC_SHOP_RESULT = 624; } diff --git a/Services/Admin/Pages/LootTables/Edit.cshtml b/Services/Admin/Pages/LootTables/Edit.cshtml index df8ef8d..7075c54 100644 --- a/Services/Admin/Pages/LootTables/Edit.cshtml +++ b/Services/Admin/Pages/LootTables/Edit.cshtml @@ -63,7 +63,7 @@

Drop Settings

-
+
@@ -84,6 +84,18 @@
+
+ + +
+
+ + +
+
+ + +
diff --git a/Services/Admin/Pages/LootTables/Edit.cshtml.cs b/Services/Admin/Pages/LootTables/Edit.cshtml.cs index 44903a2..173d12d 100644 --- a/Services/Admin/Pages/LootTables/Edit.cshtml.cs +++ b/Services/Admin/Pages/LootTables/Edit.cshtml.cs @@ -60,6 +60,9 @@ public class EditModel : AdminPageModel LootTable.MinDrops = 1; LootTable.MaxDrops = 3; LootTable.DropChanceMultiplier = 1.0f; + LootTable.GoldDropChance = 0f; + LootTable.MinGold = 0; + LootTable.MaxGold = 0; } } @@ -111,6 +114,9 @@ public class EditModel : AdminPageModel existing.MaxDrops = LootTable.MaxDrops; existing.DropChanceMultiplier = LootTable.DropChanceMultiplier; existing.GuaranteedDrop = LootTable.GuaranteedDrop; + existing.GoldDropChance = LootTable.GoldDropChance; + existing.MinGold = LootTable.MinGold; + existing.MaxGold = LootTable.MaxGold; existing.IsEnabled = LootTable.IsEnabled; await _db.SaveChangesAsync(); diff --git a/data/GameDbContext.cs b/data/GameDbContext.cs index 8662b4c..f98ebec 100644 --- a/data/GameDbContext.cs +++ b/data/GameDbContext.cs @@ -72,6 +72,14 @@ public sealed class GameDbContext : DbContext // Projectile/Quiver system public DbSet DungeonQuiverAmmoSlots => Set(); + // NPC system + public DbSet DungeonNpcDefinitions => Set(); + public DbSet DungeonNpcShops => Set(); + public DbSet DungeonNpcShopItems => Set(); + public DbSet DungeonNpcDialogTrees => Set(); + public DbSet DungeonNpcDialogNodes => Set(); + public DbSet DungeonNpcDialogOptions => Set(); + protected override void OnModelCreating(ModelBuilder b) { b.ApplyConfigurationsFromAssembly(typeof(GameDbContext).Assembly); diff --git a/data/entities/LootEntities.cs b/data/entities/LootEntities.cs index caea02d..7f99833 100644 --- a/data/entities/LootEntities.cs +++ b/data/entities/LootEntities.cs @@ -49,6 +49,21 @@ public class DungeonLootTable /// If true, guaranteed to drop at least MinDrops items ///
public bool GuaranteedDrop { get; set; } = false; + + /// + /// Chance to drop gold from this table (0.0 - 1.0) + /// + public float GoldDropChance { get; set; } = 0f; + + /// + /// Minimum gold amount when gold roll succeeds + /// + public int MinGold { get; set; } = 0; + + /// + /// Maximum gold amount when gold roll succeeds + /// + public int MaxGold { get; set; } = 0; public bool IsEnabled { get; set; } = true; @@ -58,4 +73,3 @@ public class DungeonLootTable - diff --git a/data/entities/NpcEntities.cs b/data/entities/NpcEntities.cs new file mode 100644 index 0000000..8125ce3 --- /dev/null +++ b/data/entities/NpcEntities.cs @@ -0,0 +1,188 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using DataServer.Data.Enums; + +namespace DataServer.Data.Entities; + +[Table("dungeon_npc_definitions")] +public class DungeonNpcDefinition +{ + [Key] + public int Id { get; set; } + + [Required] + [MaxLength(64)] + public string Name { get; set; } = ""; + + [MaxLength(64)] + public string Key { get; set; } = ""; + + [MaxLength(256)] + public string Description { get; set; } = ""; + + public int Level { get; set; } = 1; + public bool IsEnabled { get; set; } = true; + public bool IsKillable { get; set; } = true; + public bool CanShop { get; set; } = false; + public bool HasDialog { get; set; } = false; + public bool CanWander { get; set; } = true; + + public NpcBehaviorMode BehaviorMode { get; set; } = NpcBehaviorMode.Wander; + public NpcOnAttackBehavior OnAttackBehavior { get; set; } = NpcOnAttackBehavior.FightBack; + + public int MaxHealth { get; set; } = 100; + public int AttackPower { get; set; } = 10; + public int Defense { get; set; } = 5; + public int Strength { get; set; } = 5; + public int Dexterity { get; set; } = 5; + public int Intelligence { get; set; } = 5; + public int Wisdom { get; set; } = 5; + public int Endurance { get; set; } = 5; + + [MaxLength(2048)] + public string ResistancesJson { get; set; } = "{}"; + + [MaxLength(4096)] + public string? SpriteConfigJson { get; set; } + + [MaxLength(16)] + public string TintColor { get; set; } = "#ffffff"; + + public float Scale { get; set; } = 1f; + public float WanderRadiusPx { get; set; } = 96f; + public float WanderIntervalSeconds { get; set; } = 2.5f; + + public int? LootTableId { get; set; } + [ForeignKey(nameof(LootTableId))] + public DungeonLootTable? LootTable { get; set; } + + public int? ShopId { get; set; } + [ForeignKey(nameof(ShopId))] + public DungeonNpcShop? Shop { get; set; } + + public int? DialogTreeId { get; set; } + [ForeignKey(nameof(DialogTreeId))] + public DungeonNpcDialogTree? DialogTree { get; set; } + + [MaxLength(2048)] + public string AbilityDefinitionIdsJson { get; set; } = "[]"; + + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + public DateTime UpdatedAt { get; set; } = DateTime.UtcNow; +} + +[Table("dungeon_npc_shops")] +public class DungeonNpcShop +{ + [Key] + public int Id { get; set; } + + [Required] + [MaxLength(64)] + public string Name { get; set; } = ""; + + public bool IsEnabled { get; set; } = true; + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + public DateTime UpdatedAt { get; set; } = DateTime.UtcNow; + + public ICollection Items { get; set; } = new List(); +} + +[Table("dungeon_npc_shop_items")] +public class DungeonNpcShopItem +{ + [Key] + public int Id { get; set; } + + public int ShopId { get; set; } + [ForeignKey(nameof(ShopId))] + public DungeonNpcShop? Shop { get; set; } + + public int SlotIndex { get; set; } + public int ItemDefinitionId { get; set; } + + [ForeignKey(nameof(ItemDefinitionId))] + public DungeonItemDefinition? ItemDefinition { get; set; } + + public int Quantity { get; set; } = 1; + public long PriceGold { get; set; } = 1; + public bool Restocks { get; set; } = true; + public int RestockIntervalSeconds { get; set; } = 300; + public DateTime? LastRestockAt { get; set; } +} + +[Table("dungeon_npc_dialog_trees")] +public class DungeonNpcDialogTree +{ + [Key] + public int Id { get; set; } + + [Required] + [MaxLength(64)] + public string Name { get; set; } = ""; + + [MaxLength(256)] + public string Description { get; set; } = ""; + + public bool IsEnabled { get; set; } = true; + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + public DateTime UpdatedAt { get; set; } = DateTime.UtcNow; + + public ICollection Nodes { get; set; } = new List(); +} + +[Table("dungeon_npc_dialog_nodes")] +public class DungeonNpcDialogNode +{ + [Key] + public int Id { get; set; } + + public int DialogTreeId { get; set; } + [ForeignKey(nameof(DialogTreeId))] + public DungeonNpcDialogTree? DialogTree { get; set; } + + [MaxLength(128)] + public string NodeKey { get; set; } = ""; + + [MaxLength(2048)] + public string Text { get; set; } = ""; + + public bool IsRoot { get; set; } = false; + public bool IsTerminal { get; set; } = false; + + [MaxLength(64)] + public string? RewardType { get; set; } + public int? RewardItemDefinitionId { get; set; } + public int RewardItemQuantity { get; set; } = 1; + public long RewardGold { get; set; } = 0; + public long RewardXp { get; set; } = 0; + [MaxLength(64)] + public string? RewardQuestKey { get; set; } + + public ICollection Options { get; set; } = new List(); +} + +[Table("dungeon_npc_dialog_options")] +public class DungeonNpcDialogOption +{ + [Key] + public int Id { get; set; } + + public int NodeId { get; set; } + [ForeignKey(nameof(NodeId))] + public DungeonNpcDialogNode? Node { get; set; } + + [MaxLength(256)] + public string PlayerText { get; set; } = ""; + + public int? NextNodeId { get; set; } + + public NpcDialogConditionType ConditionType { get; set; } = NpcDialogConditionType.None; + [MaxLength(64)] + public string? ConditionValue { get; set; } + public int ConditionQuantity { get; set; } = 1; + + public bool ConsumeConditionItem { get; set; } = false; + public int SortOrder { get; set; } = 0; +} + diff --git a/data/enums/NpcEnums.cs b/data/enums/NpcEnums.cs new file mode 100644 index 0000000..b17b75f --- /dev/null +++ b/data/enums/NpcEnums.cs @@ -0,0 +1,28 @@ +namespace DataServer.Data.Enums; + +public enum NpcBehaviorMode +{ + Passive = 0, + Wander = 1, + Aggressive = 2 +} + +public enum NpcOnAttackBehavior +{ + Ignore = 0, + FightBack = 1, + Flee = 2, + CallForHelp = 3 +} + +public enum NpcDialogConditionType +{ + None = 0, + HasItem = 1, + QuestCompleted = 2, + QuestActive = 3, + CharacterLevelAtLeast = 4, + CharacterLevelAtMost = 5, + GoldAtLeast = 6 +} + diff --git a/pending-clientChanges.md b/pending-clientChanges.md index 385ddaf..a3c764f 100644 --- a/pending-clientChanges.md +++ b/pending-clientChanges.md @@ -1,20 +1,65 @@ # Pending Client Changes -## HazardZone Tile Tinting (Ability Type 29) +## NPC Interactions -- `DUNGEON_STATE` now includes a top-level `hazards` array every tick. -- Each hazard item includes: - - `id` - - `sourceMobId` - - `x`, `y`, `radius` (world-space pixels) - - `duration` (seconds remaining) - - `tickInterval`, `nextTickIn` - - `damagePerTick`, `damageTypeKey` - - `visualKey` - - `tintColor` (hex from ability config, ex: `#ff5500`) - - `tintOpacity` (0..1 from ability config) -- Client behavior: - - Render tile tint overlay for the area covered by each active hazard in `hazards`. - - Keep overlays synchronized to the current `hazards` list from each state packet. - - Remove overlay when a hazard no longer exists in the list (expired/removed server-side). - - If multiple hazards overlap, blend/stack tints in a deterministic order (recommend by `id` ascending). +- New input opcodes: + - `DUNGEON_INPUT_NPC_INTERACT` (`406`) + - `DUNGEON_INPUT_NPC_DIALOG_SELECT` (`407`) + - `DUNGEON_INPUT_NPC_SHOP_ACTION` (`408`) +- New response opcodes: + - `NPC_INTERACT_STATE` (`620`) + - `NPC_DIALOG_STATE` (`621`) + - `NPC_DIALOG_RESULT` (`622`) + - `NPC_SHOP_STATE` (`623`) + - `NPC_SHOP_RESULT` (`624`) + +### DUNGEON_STATE additions + +- `npcs` array added to top-level dungeon state. +- NPC payload fields: + - `id`, `definitionId`, `name` + - `x`, `y`, `rotation` + - `level`, `health`, `maxHealth`, `isAlive` + - `isKillable`, `canShop`, `hasDialog` + - `behavior`, `onAttackBehavior` + - `currentAnimation`, `spriteConfig`, `tintColor`, `scale` + +### Interaction payloads + +- `DUNGEON_INPUT_NPC_INTERACT` request: + - `{ npcId }` +- `DUNGEON_INPUT_NPC_DIALOG_SELECT` request: + - `{ npcId, optionId }` +- `DUNGEON_INPUT_NPC_SHOP_ACTION` request: + - `{ npcId, action: "buy", slotIndex, quantity }` + +### Dialog payloads + +- `NPC_DIALOG_STATE`: + - `success` + - `npcId` + - `node`: `{ id, text, isTerminal, rewardGold, rewardXp, rewardItemDefinitionId, rewardItemQuantity, rewardQuestKey }` + - `options`: list of `{ id, text, nextNodeId }` that pass server-side conditions. +- `NPC_DIALOG_RESULT`: + - `success`, `npcId`, `nextNodeId`, `isTerminal` + - or `error` when blocked/invalid. + +### Shop payloads + +- `NPC_SHOP_STATE`: + - `success` + - `shop`: `{ id, name, items[] }` + - each item: `{ slotIndex, itemDefinitionId, itemName, quantity, priceGold, restocks, restockIntervalSeconds }` +- `NPC_SHOP_RESULT`: + - `success`, `npcId`, `action`, `itemDefinitionId`, `quantity`, `totalPrice`, `remainingGold`, `remainingStock` + - or `error` for failure states. + +## Stash Access + +- Stash is no longer VIP-gated on server. +- Existing stash opcodes are unchanged: + - `STASH_REQUEST` (`610`) + - `STASH_STATE` (`611`) + - `STASH_DEPOSIT` (`612`) + - `STASH_WITHDRAW` (`613`) + - `STASH_RESULT` (`614`)