using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Server.Data; using Server.Data.Entities; namespace Server.Game.Dungeon; /// /// Generated loot result - an item with quantity /// public class LootDrop { public int ItemDefinitionId { get; set; } public DungeonItemDefinition Item { get; set; } = null!; public int Quantity { get; set; } } /// /// Service for generating loot from loot tables /// public class LootService { private readonly ILogger _log; private readonly IServiceScopeFactory _scopeFactory; // Cached data private Dictionary _lootTables = new(); private Dictionary> _mobLootTableMappings = new(); // MobId -> List private Dictionary _itemDefinitions = new(); private bool _initialized = false; private readonly Random _random = new(); public LootService(ILogger log, IServiceScopeFactory scopeFactory) { _log = log; _scopeFactory = scopeFactory; } public async Task InitializeAsync() { if (_initialized) return; using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); // Load all loot tables with their entries var tables = await db.Set() .Include(t => t.Entries) .Where(t => t.IsEnabled) .ToListAsync(); // Seed defaults if empty if (tables.Count == 0) { tables = await SeedDefaultLootTablesAsync(db); } _lootTables = tables.ToDictionary(t => t.Id); // Load mob -> loot table mappings var mappings = await db.Set() .Include(m => m.LootTable) .ToListAsync(); // Seed mob mappings if missing (can happen if tables exist but mappings were cleared) if (mappings.Count == 0 && tables.Count > 0) { _log.LogInformation("No mob loot table mappings found, seeding defaults..."); var defaultMappings = GetDefaultMobLootTableMappings(tables); db.Set().AddRange(defaultMappings); await db.SaveChangesAsync(); mappings = await db.Set() .Include(m => m.LootTable) .ToListAsync(); _log.LogInformation("Seeded {Count} mob loot table mappings", mappings.Count); } _mobLootTableMappings = mappings .GroupBy(m => m.MobDefinitionId) .ToDictionary(g => g.Key, g => g.OrderBy(m => m.Priority).ToList()); // Load item definitions var items = await db.Set() .Where(i => i.IsEnabled) .ToListAsync(); // Seed default items if empty if (items.Count == 0) { items = await SeedDefaultItemsAsync(db); } _itemDefinitions = items.ToDictionary(i => i.Id); _initialized = true; _log.LogInformation("LootService initialized: {Tables} tables, {Items} items, {Mappings} mob mappings", _lootTables.Count, _itemDefinitions.Count, mappings.Count); } /// /// Generate loot for a mob kill /// public List GenerateMobLoot(int mobDefinitionId, int dungeonTier, float dropChanceMultiplier = 1.0f) { var loot = new List(); 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 } _log.LogDebug("Generating loot for mob {MobId}, found {Count} table mappings", mobDefinitionId, mappings.Count); foreach (var mapping in mappings) { // Check if this table rolls if (_random.NextDouble() > mapping.RollChance) continue; if (!_lootTables.TryGetValue(mapping.LootTableId, out var table)) continue; // Check tier requirements if (dungeonTier < table.MinTier || dungeonTier > table.MaxTier) continue; // Generate drops from this table var drops = GenerateFromTable(table, dungeonTier, dropChanceMultiplier); loot.AddRange(drops); } _log.LogDebug("Generated {Count} loot drops for mob {MobId}", loot.Count, mobDefinitionId); return loot; } /// /// Generate loot from a specific loot table /// public List GenerateFromTable(DungeonLootTable table, int dungeonTier, float extraMultiplier = 1.0f) { var loot = new List(); 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); } // Determine how many additional drops int dropCount = table.GuaranteedDrop ? _random.Next(table.MinDrops, table.MaxDrops + 1) : 0; // Roll for each non-guaranteed entry var nonGuaranteed = entries.Where(e => !e.Guaranteed).ToList(); foreach (var entry in nonGuaranteed) { // Calculate drop chance with tier scaling float chance = entry.DropChance + (entry.DropChancePerTier * (dungeonTier - 1)); chance = Math.Min(chance, entry.MaxDropChance); chance *= totalMultiplier; if (_random.NextDouble() < chance) { AddDrop(loot, entry); dropCount--; } } // If we need more drops to meet minimum, use weighted random selection while (dropCount > 0 && nonGuaranteed.Count > 0) { var selected = WeightedRandomSelect(nonGuaranteed); if (selected != null) { AddDrop(loot, selected); dropCount--; } else { break; } } return loot; } private void AddDrop(List loot, DungeonLootTableEntry entry) { if (!_itemDefinitions.TryGetValue(entry.ItemDefinitionId, out var item)) return; int quantity = _random.Next(entry.MinQuantity, entry.MaxQuantity + 1); // Check if we already have this item in loot (stack it) var existing = loot.FirstOrDefault(l => l.ItemDefinitionId == entry.ItemDefinitionId); if (existing != null && item.Stackable) { existing.Quantity = Math.Min(existing.Quantity + quantity, item.MaxStack); } else { loot.Add(new LootDrop { ItemDefinitionId = entry.ItemDefinitionId, Item = item, Quantity = quantity }); } } private DungeonLootTableEntry? WeightedRandomSelect(List entries) { int totalWeight = entries.Sum(e => e.Weight); if (totalWeight <= 0) return null; int roll = _random.Next(totalWeight); int cumulative = 0; foreach (var entry in entries) { cumulative += entry.Weight; if (roll < cumulative) return entry; } return entries.LastOrDefault(); } public DungeonItemDefinition? GetItemDefinition(int itemId) { return _itemDefinitions.GetValueOrDefault(itemId); } private async Task> SeedDefaultLootTablesAsync(GameDbContext db) { var tables = GetDefaultLootTables(); db.Set().AddRange(tables); await db.SaveChangesAsync(); // Now add entries (need table IDs first) var entries = GetDefaultLootTableEntries(tables); db.Set().AddRange(entries); await db.SaveChangesAsync(); // Add mob mappings var mappings = GetDefaultMobLootTableMappings(tables); db.Set().AddRange(mappings); await db.SaveChangesAsync(); _log.LogInformation("Seeded {Count} default loot tables", tables.Count); // Reload with entries return await db.Set() .Include(t => t.Entries) .Where(t => t.IsEnabled) .ToListAsync(); } private List GetDefaultLootTables() { return new List { // Common mob loot new() { Id = 1, Name = "Common Mob", Description = "Basic drops from common mobs", MinDrops = 1, MaxDrops = 2, GuaranteedDrop = true }, new() { Id = 2, Name = "Undead Mob", Description = "Drops from undead creatures", MinDrops = 1, MaxDrops = 2 }, new() { Id = 3, Name = "Beast Mob", Description = "Drops from beasts", MinDrops = 1, MaxDrops = 2 }, new() { Id = 4, Name = "Demon Mob", Description = "Drops from demons", MinDrops = 1, MaxDrops = 3 }, new() { Id = 5, Name = "Elemental Mob", Description = "Drops from elementals", MinDrops = 1, MaxDrops = 2 }, // Boss loot new() { Id = 10, Name = "Boss Common", Description = "Guaranteed boss drops", MinDrops = 2, MaxDrops = 4, GuaranteedDrop = true }, new() { Id = 11, Name = "Boss Rare", Description = "Rare boss drops", MinDrops = 1, MaxDrops = 2, DropChanceMultiplier = 2.0f }, // Equipment tables (rare drops) new() { Id = 20, Name = "Weapon Drop", Description = "Chance for weapon drop", MinDrops = 1, MaxDrops = 1, DropChanceMultiplier = 0.5f }, new() { Id = 21, Name = "Armor Drop", Description = "Chance for armor drop", MinDrops = 1, MaxDrops = 1, DropChanceMultiplier = 0.5f }, }; } private List GetDefaultLootTableEntries(List tables) { // Item IDs from default items (we'll create these next): // 1-10: Materials // 11-20: Consumables // 21-30: Weapons // 31-40: Armor return new List { // Common Mob (Table 1) - basic materials new() { LootTableId = 1, ItemDefinitionId = 1, DropChance = 0.5f, MinQuantity = 1, MaxQuantity = 3, Weight = 100 }, // Bone Fragment new() { LootTableId = 1, ItemDefinitionId = 11, DropChance = 0.2f, MinQuantity = 1, MaxQuantity = 1, Weight = 50 }, // Minor Health Potion // Undead Mob (Table 2) new() { LootTableId = 2, ItemDefinitionId = 1, DropChance = 0.8f, MinQuantity = 2, MaxQuantity = 5, Weight = 100 }, // Bone Fragment new() { LootTableId = 2, ItemDefinitionId = 2, DropChance = 0.3f, MinQuantity = 1, MaxQuantity = 2, Weight = 60 }, // Rotted Cloth new() { LootTableId = 2, ItemDefinitionId = 3, DropChance = 0.1f, MinQuantity = 1, MaxQuantity = 1, Weight = 20 }, // Soul Essence // Beast Mob (Table 3) new() { LootTableId = 3, ItemDefinitionId = 4, DropChance = 0.7f, MinQuantity = 1, MaxQuantity = 3, Weight = 100 }, // Beast Hide new() { LootTableId = 3, ItemDefinitionId = 5, DropChance = 0.4f, MinQuantity = 1, MaxQuantity = 2, Weight = 70 }, // Beast Fang new() { LootTableId = 3, ItemDefinitionId = 6, DropChance = 0.2f, MinQuantity = 1, MaxQuantity = 1, Weight = 30 }, // Beast Heart // Demon Mob (Table 4) new() { LootTableId = 4, ItemDefinitionId = 7, DropChance = 0.6f, MinQuantity = 1, MaxQuantity = 2, Weight = 100 }, // Demon Essence new() { LootTableId = 4, ItemDefinitionId = 8, DropChance = 0.3f, MinQuantity = 1, MaxQuantity = 1, Weight = 50 }, // Infernal Shard new() { LootTableId = 4, ItemDefinitionId = 12, DropChance = 0.25f, MinQuantity = 1, MaxQuantity = 1, Weight = 40 }, // Health Potion // Elemental Mob (Table 5) new() { LootTableId = 5, ItemDefinitionId = 9, DropChance = 0.7f, MinQuantity = 1, MaxQuantity = 3, Weight = 100 }, // Elemental Core new() { LootTableId = 5, ItemDefinitionId = 10, DropChance = 0.2f, MinQuantity = 1, MaxQuantity = 1, Weight = 40 }, // Arcane Dust new() { LootTableId = 5, ItemDefinitionId = 14, DropChance = 0.2f, MinQuantity = 1, MaxQuantity = 1, Weight = 30 }, // Mana Potion // Boss Common (Table 10) new() { LootTableId = 10, ItemDefinitionId = 12, DropChance = 1.0f, MinQuantity = 2, MaxQuantity = 3, Weight = 100, Guaranteed = true }, // Health Potion new() { LootTableId = 10, ItemDefinitionId = 14, DropChance = 1.0f, MinQuantity = 1, MaxQuantity = 2, Weight = 100, Guaranteed = true }, // Mana Potion new() { LootTableId = 10, ItemDefinitionId = 3, DropChance = 0.8f, MinQuantity = 2, MaxQuantity = 4, Weight = 80 }, // Soul Essence // Boss Rare (Table 11) new() { LootTableId = 11, ItemDefinitionId = 21, DropChance = 0.15f, MinQuantity = 1, MaxQuantity = 1, Weight = 50, DropChancePerTier = 0.03f }, // Iron Sword new() { LootTableId = 11, ItemDefinitionId = 31, DropChance = 0.15f, MinQuantity = 1, MaxQuantity = 1, Weight = 50, DropChancePerTier = 0.03f }, // Leather Armor new() { LootTableId = 11, ItemDefinitionId = 8, DropChance = 0.5f, MinQuantity = 1, MaxQuantity = 2, Weight = 100 }, // Infernal Shard // Weapon Drop (Table 20) new() { LootTableId = 20, ItemDefinitionId = 21, DropChance = 0.05f, MinQuantity = 1, MaxQuantity = 1, Weight = 100, DropChancePerTier = 0.01f }, // Iron Sword new() { LootTableId = 20, ItemDefinitionId = 22, DropChance = 0.03f, MinQuantity = 1, MaxQuantity = 1, Weight = 60, DropChancePerTier = 0.01f }, // Steel Sword new() { LootTableId = 20, ItemDefinitionId = 23, DropChance = 0.04f, MinQuantity = 1, MaxQuantity = 1, Weight = 80, DropChancePerTier = 0.01f }, // Wooden Staff // Armor Drop (Table 21) new() { LootTableId = 21, ItemDefinitionId = 31, DropChance = 0.05f, MinQuantity = 1, MaxQuantity = 1, Weight = 100, DropChancePerTier = 0.01f }, // Leather Armor new() { LootTableId = 21, ItemDefinitionId = 32, DropChance = 0.03f, MinQuantity = 1, MaxQuantity = 1, Weight = 60, DropChancePerTier = 0.01f }, // Chainmail new() { LootTableId = 21, ItemDefinitionId = 33, DropChance = 0.05f, MinQuantity = 1, MaxQuantity = 1, Weight = 80, DropChancePerTier = 0.01f }, // Leather Helm }; } private List GetDefaultMobLootTableMappings(List tables) { // ACTUAL Mob IDs from DefaultDungeonMobs: // 1: Skeleton (Undead) // 2: Zombie (Undead) // 3: Giant Rat (Beast) // 4: Giant Spider (Beast) // 10: Skeleton Knight (Elite, Undead) // 20: Imp (Demon) // 21: Cultist (Humanoid) // 30: Stone Golem (Elite, Construct) // 31: Fire Elemental (Elemental) // 100: The Bone Lord (Boss, Undead) return new List { // Skeleton (Undead) - ID 1 new() { MobDefinitionId = 1, LootTableId = 1, Priority = 0 }, // Common new() { MobDefinitionId = 1, LootTableId = 2, Priority = 1 }, // Undead new() { MobDefinitionId = 1, LootTableId = 20, Priority = 2, RollChance = 0.3f }, // Weapon chance // Zombie (Undead) - ID 2 new() { MobDefinitionId = 2, LootTableId = 1, Priority = 0 }, // Common new() { MobDefinitionId = 2, LootTableId = 2, Priority = 1 }, // Undead new() { MobDefinitionId = 2, LootTableId = 21, Priority = 2, RollChance = 0.3f }, // Armor chance // Giant Rat (Beast) - ID 3 new() { MobDefinitionId = 3, LootTableId = 1, Priority = 0 }, // Common new() { MobDefinitionId = 3, LootTableId = 3, Priority = 1 }, // Beast // Giant Spider (Beast) - ID 4 new() { MobDefinitionId = 4, LootTableId = 1, Priority = 0 }, // Common new() { MobDefinitionId = 4, LootTableId = 3, Priority = 1 }, // Beast new() { MobDefinitionId = 4, LootTableId = 20, Priority = 2, RollChance = 0.2f }, // Weapon // Skeleton Knight (Elite, Undead) - ID 10 new() { MobDefinitionId = 10, LootTableId = 1, Priority = 0 }, // Common new() { MobDefinitionId = 10, LootTableId = 2, Priority = 1 }, // Undead new() { MobDefinitionId = 10, LootTableId = 20, Priority = 2, RollChance = 0.5f }, // Weapon new() { MobDefinitionId = 10, LootTableId = 21, Priority = 3, RollChance = 0.5f }, // Armor // Imp (Demon) - ID 20 new() { MobDefinitionId = 20, LootTableId = 1, Priority = 0 }, // Common new() { MobDefinitionId = 20, LootTableId = 4, Priority = 1 }, // Demon // Cultist (Humanoid) - ID 21 new() { MobDefinitionId = 21, LootTableId = 1, Priority = 0 }, // Common new() { MobDefinitionId = 21, LootTableId = 4, Priority = 1 }, // Demon loot new() { MobDefinitionId = 21, LootTableId = 20, Priority = 2, RollChance = 0.3f }, // Weapon // Stone Golem (Elite) - ID 30 new() { MobDefinitionId = 30, LootTableId = 1, Priority = 0 }, // Common new() { MobDefinitionId = 30, LootTableId = 5, Priority = 1 }, // Elemental new() { MobDefinitionId = 30, LootTableId = 21, Priority = 2, RollChance = 0.6f }, // Armor // Fire Elemental - ID 31 new() { MobDefinitionId = 31, LootTableId = 1, Priority = 0 }, // Common new() { MobDefinitionId = 31, LootTableId = 5, Priority = 1 }, // Elemental // The Bone Lord (Boss) - ID 100 new() { MobDefinitionId = 100, LootTableId = 10, Priority = 0 }, // Boss Common new() { MobDefinitionId = 100, LootTableId = 11, Priority = 1 }, // Boss Rare new() { MobDefinitionId = 100, LootTableId = 2, Priority = 2 }, // Undead }; } private async Task> SeedDefaultItemsAsync(GameDbContext db) { var items = DefaultDungeonItems.GetDefaultItems(); db.Set().AddRange(items); await db.SaveChangesAsync(); _log.LogInformation("Seeded {Count} default item definitions", items.Count); return items; } }