using DataServer.Data; using DataServer.Data.Entities; using DataServer.Data.Enums; using GameServer.Dungeon; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Server.Networking; using Server.Networking.Messages; namespace GameServer.World; public sealed partial class WorldHandler { private sealed class WorldNpcInteractRequest { public int NpcId { get; set; } } private sealed class WorldNpcDialogSelectRequest { public int NpcId { get; set; } public int OptionId { get; set; } } private sealed class WorldNpcShopActionRequest { public int NpcId { get; set; } public string Action { get; set; } = "buy"; public int SlotIndex { get; set; } public int Quantity { get; set; } = 1; } /// /// Find the NPC in the player's current zone simulation. /// private NpcInstance? FindWorldNpc(WorldSessionState s, int npcId) { var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ); if (!_activeZones.TryGetValue(zoneKey, out var zoneSim)) return null; return zoneSim.Npcs.TryGetValue(npcId, out var npc) ? npc : null; } private async Task HandleWorldNpcInteract(IConnection conn, WorldSessionState s, ReadOnlyMemory payload, CancellationToken ct) { var req = WorldInputParser.Parse(payload); if (req == null) return; var npc = FindWorldNpc(s, req.NpcId); if (npc == null) { await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_INTERACT_STATE, new { success = false, error = "npc_not_found" }, ct); return; } // Check distance (NPC must be within interaction range) float dist = MathF.Sqrt(MathF.Pow(npc.X - s.X, 2) + MathF.Pow(npc.Y - s.Y, 2)); if (dist > 128f) // ~4 tiles { await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_INTERACT_STATE, new { success = false, error = "too_far" }, ct); return; } await _broadcast.SendAsync(conn, OpCodes.WORLD_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 SendWorldNpcDialogNodeAsync(conn, s, npc, null, ct); } if (npc.CanShop && npc.ShopId.HasValue) { await SendWorldNpcShopStateAsync(conn, npc.ShopId.Value, ct); } } private async Task HandleWorldNpcDialogSelect(IConnection conn, WorldSessionState s, ReadOnlyMemory payload, CancellationToken ct) { var req = WorldInputParser.Parse(payload); if (req == null) return; var npc = FindWorldNpc(s, req.NpcId); if (npc == null || !npc.HasDialog || !npc.DialogTreeId.HasValue) { await _broadcast.SendAsync(conn, OpCodes.WORLD_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 _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_DIALOG_RESULT, new { success = false, error = "invalid_option" }, ct); return; } var (conditionMet, conditionError) = await EvaluateWorldDialogConditionAsync(db, s.CharacterId, option, ct); if (!conditionMet) { await _broadcast.SendAsync(conn, OpCodes.WORLD_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 ConsumeWorldCharacterItemAsync(db, s.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 ApplyWorldDialogRewardsAsync(db, s.CharacterId, nextNode, ct); await SendWorldNpcDialogNodeAsync(conn, s, npc, nextNode.Id, ct); await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_DIALOG_RESULT, new { success = true, npcId = npc.Id, nextNodeId = nextNode.Id, isTerminal = nextNode.IsTerminal }, ct); return; } await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_DIALOG_RESULT, new { success = true, npcId = npc.Id, nextNodeId = (int?)null, isTerminal = true }, ct); } private async Task HandleWorldNpcShopAction(IConnection conn, WorldSessionState s, ReadOnlyMemory payload, CancellationToken ct) { var req = WorldInputParser.Parse(payload); if (req == null) return; var npc = FindWorldNpc(s, req.NpcId); if (npc == null || !npc.CanShop || !npc.ShopId.HasValue) { await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new { success = false, error = "npc_shop_unavailable" }, ct); return; } if (string.Equals(req.Action, "sell", StringComparison.OrdinalIgnoreCase)) { await HandleWorldNpcShopSellAsync(conn, s, npc, req, ct); return; } if (!string.Equals(req.Action, "buy", StringComparison.OrdinalIgnoreCase)) { await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new { success = false, error = "unsupported_shop_action" }, ct); return; } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var shopItem = await db.DungeonNpcShopItems .Include(si => si.ItemDefinition) .FirstOrDefaultAsync(si => si.ShopId == npc.ShopId.Value && si.SlotIndex == req.SlotIndex, ct); if (shopItem == null || shopItem.ItemDefinition == null) { await _broadcast.SendAsync(conn, OpCodes.WORLD_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 _broadcast.SendAsync(conn, OpCodes.WORLD_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 == s.CharacterId, ct); if (character == null) { await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new { success = false, error = "character_not_found" }, ct); return; } if (character.Gold < totalPrice) { await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new { success = false, error = "not_enough_gold", requiredGold = totalPrice, currentGold = character.Gold }, ct); return; } var added = await AddWorldItemToInventoryAsync(db, s.CharacterId, shopItem.ItemDefinitionId, quantity, ct); if (!added) { await _broadcast.SendAsync(conn, OpCodes.WORLD_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); await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new { success = true, npcId = npc.Id, action = "buy", itemDefinitionId = shopItem.ItemDefinitionId, quantity, totalPrice, remainingGold = character.Gold, remainingStock = shopItem.Quantity }, ct); // Re-send updated shop state await SendWorldNpcShopStateAsync(conn, npc.ShopId.Value, ct); } // ---- World NPC Helpers ---- private async Task SendWorldNpcDialogNodeAsync(IConnection conn, WorldSessionState s, 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 _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_DIALOG_RESULT, 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 EvaluateWorldDialogConditionAsync(db, s.CharacterId, option, ct); if (!ok) continue; filtered.Add(new { id = option.Id, text = option.PlayerText, nextNodeId = option.NextNodeId }); } await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_INTERACT_STATE, new { success = true, npcId = npc.Id, dialogNode = new { id = node.Id, text = node.Text, isTerminal = node.IsTerminal, rewardGold = node.RewardGold, rewardXp = node.RewardXp, rewardItemDefinitionId = node.RewardItemDefinitionId, rewardItemQuantity = node.RewardItemQuantity }, options = filtered }, ct); } private async Task SendWorldNpcShopStateAsync(IConnection conn, 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 _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new { success = false, error = "shop_not_found" }, ct); return; } // Handle restocking 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 _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_INTERACT_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)> EvaluateWorldDialogConditionAsync( GameDbContext db, ulong characterId, DungeonNpcDialogOption option, CancellationToken ct) { switch (option.ConditionType) { case NpcDialogConditionType.None: return (true, null); case NpcDialogConditionType.HasItem: if (!int.TryParse(option.ConditionValue, out var itemDefId)) return (false, "invalid_condition_value"); var itemCount = await db.DungeonCharacterItems .Where(i => i.CharacterId == characterId && i.ItemDefinitionId == itemDefId) .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"); var charLevel = await db.DungeonCharacters .Where(c => c.Id == characterId) .Select(c => c.Level) .FirstOrDefaultAsync(ct); return charLevel >= minLevel ? (true, null) : (false, "level_too_low"); case NpcDialogConditionType.CharacterLevelAtMost: if (!int.TryParse(option.ConditionValue, out var maxLevel)) return (false, "invalid_condition_value"); var charLvl = await db.DungeonCharacters .Where(c => c.Id == characterId) .Select(c => c.Level) .FirstOrDefaultAsync(ct); return charLvl <= maxLevel ? (true, null) : (false, "level_too_high"); case NpcDialogConditionType.GoldAtLeast: if (!long.TryParse(option.ConditionValue, out var minGold)) return (false, "invalid_condition_value"); var gold = await db.DungeonCharacters .Where(c => c.Id == characterId) .Select(c => c.Gold) .FirstOrDefaultAsync(ct); return gold >= minGold ? (true, null) : (false, "not_enough_gold"); case NpcDialogConditionType.QuestCompleted: case NpcDialogConditionType.QuestActive: return (false, "quest_system_not_ready"); default: return (false, "unsupported_condition"); } } private async Task ApplyWorldDialogRewardsAsync(GameDbContext db, ulong characterId, DungeonNpcDialogNode node, CancellationToken ct) { var modified = false; var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == characterId, ct); if (character == null) return; if (node.RewardGold > 0) { character.Gold += node.RewardGold; modified = true; } if (node.RewardXp > 0) { character.Experience += node.RewardXp; modified = true; } if (node.RewardItemDefinitionId.HasValue && node.RewardItemQuantity > 0) { var added = await AddWorldItemToInventoryAsync(db, characterId, node.RewardItemDefinitionId.Value, node.RewardItemQuantity, ct); modified = modified || added; } if (modified) await db.SaveChangesAsync(ct); } private async Task AddWorldItemToInventoryAsync(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 ConsumeWorldCharacterItemAsync(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); } /// /// Handle selling an item from the player's inventory to an NPC shop. /// SlotIndex refers to the player's inventory slot to sell from. /// Sell price is 25% of the item's base buy price (or PriceGold from shop if found there). /// private async Task HandleWorldNpcShopSellAsync( IConnection conn, WorldSessionState s, NpcInstance npc, WorldNpcShopActionRequest req, CancellationToken ct) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); // Find the item in the player's inventory at the specified slot var inventoryItem = await db.DungeonCharacterItems .Include(i => i.ItemDefinition) .FirstOrDefaultAsync(i => i.CharacterId == s.CharacterId && i.SlotIndex == req.SlotIndex && !i.IsEquipped, ct); if (inventoryItem == null || inventoryItem.ItemDefinition == null) { await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new { success = false, error = "item_not_found" }, ct); return; } var quantity = Math.Max(1, Math.Min(req.Quantity, inventoryItem.Quantity)); // Calculate sell price: check if this item type is in the shop's catalog for a reference price long pricePerUnit = 0; if (npc.ShopId.HasValue) { var shopEntry = await db.DungeonNpcShopItems .FirstOrDefaultAsync(si => si.ShopId == npc.ShopId.Value && si.ItemDefinitionId == inventoryItem.ItemDefinitionId, ct); if (shopEntry != null) { pricePerUnit = shopEntry.PriceGold / 4; // 25% of shop buy price } } // Fallback: 25% of a base price formula if not in shop if (pricePerUnit <= 0) { // Base price heuristic: item level * rarity multiplier pricePerUnit = Math.Max(1, inventoryItem.ItemDefinition.RequiredLevel * 2); } long totalGold = pricePerUnit * quantity; var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == s.CharacterId, ct); if (character == null) { await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new { success = false, error = "character_not_found" }, ct); return; } // Remove quantity from inventory inventoryItem.Quantity -= quantity; if (inventoryItem.Quantity <= 0) { db.DungeonCharacterItems.Remove(inventoryItem); } // Award gold character.Gold += totalGold; await db.SaveChangesAsync(ct); await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new { success = true, npcId = npc.Id, action = "sell", itemDefinitionId = inventoryItem.ItemDefinitionId, quantity, totalPrice = totalGold, remainingGold = character.Gold }, ct); // Re-send updated shop state if (npc.ShopId.HasValue) { await SendWorldNpcShopStateAsync(conn, npc.ShopId.Value, ct); } } }