Files
systemrevivalserver/Game/Dungeon/CraftingHandler.cs
T

699 lines
27 KiB
C#

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DataServer.Data;
using DataServer.Data.Entities;
using Server.Networking;
using Server.Networking.Messages;
using System.Text.Json;
namespace GameServer.Dungeon;
/// <summary>
/// Handles crafting operations including recipe discovery, crafting, and skill progression
/// </summary>
public class CraftingHandler
{
private readonly ILogger<CraftingHandler> _log;
private readonly IServiceScopeFactory _scopeFactory;
// Cache recipes in memory for fast lookup
private Dictionary<int, DungeonCraftingRecipe> _recipes = new();
private Dictionary<string, int> _ingredientHashToRecipeId = new(); // For recipe discovery
private bool _recipesLoaded = false;
public CraftingHandler(ILogger<CraftingHandler> log, IServiceScopeFactory scopeFactory)
{
_log = log;
_scopeFactory = scopeFactory;
}
public async Task InitializeAsync()
{
await RefreshRecipeCacheAsync();
}
/// <summary>
/// Refresh the recipe cache from database. Call this after recipes are modified in admin.
/// </summary>
public async Task RefreshRecipeCacheAsync()
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var recipes = await db.DungeonCraftingRecipes
.Include(r => r.Ingredients)
.Where(r => r.IsEnabled)
.ToListAsync();
_recipes = recipes.ToDictionary(r => r.Id);
// Clear old hash lookup and rebuild
_ingredientHashToRecipeId.Clear();
// Build ingredient hash lookup for recipe discovery
foreach (var recipe in recipes)
{
var hash = GetIngredientHash(recipe.Ingredients.ToList());
_ingredientHashToRecipeId[hash] = recipe.Id;
_log.LogDebug("Recipe {Name} (ID {Id}) hash: {Hash}", recipe.Name, recipe.Id, hash);
}
_recipesLoaded = true;
_log.LogInformation("CraftingHandler loaded {Count} recipes", recipes.Count);
}
/// <summary>
/// Get crafting skill for a character, creating if it doesn't exist
/// </summary>
public async Task<DungeonCharacterCraftingSkill> GetOrCreateCraftingSkillAsync(
GameDbContext db, ulong characterId, CraftingSkillType skillType)
{
var skill = await db.DungeonCharacterCraftingSkills
.FirstOrDefaultAsync(s => s.CharacterId == characterId && s.SkillType == skillType);
if (skill == null)
{
skill = new DungeonCharacterCraftingSkill
{
CharacterId = characterId,
SkillType = skillType,
Level = 1,
Experience = 0
};
db.DungeonCharacterCraftingSkills.Add(skill);
await db.SaveChangesAsync();
}
return skill;
}
/// <summary>
/// Get all crafting skills for a character
/// </summary>
public async Task<Dictionary<CraftingSkillType, DungeonCharacterCraftingSkill>> GetAllCraftingSkillsAsync(
GameDbContext db, ulong characterId)
{
var skills = await db.DungeonCharacterCraftingSkills
.Where(s => s.CharacterId == characterId)
.ToListAsync();
var result = new Dictionary<CraftingSkillType, DungeonCharacterCraftingSkill>();
// Ensure all skill types exist
foreach (CraftingSkillType skillType in Enum.GetValues(typeof(CraftingSkillType)))
{
var skill = skills.FirstOrDefault(s => s.SkillType == skillType);
if (skill == null)
{
skill = new DungeonCharacterCraftingSkill
{
CharacterId = characterId,
SkillType = skillType,
Level = 1,
Experience = 0
};
db.DungeonCharacterCraftingSkills.Add(skill);
}
result[skillType] = skill;
}
await db.SaveChangesAsync();
return result;
}
/// <summary>
/// Get known recipes for a character
/// </summary>
public async Task<List<DungeonCraftingRecipe>> GetKnownRecipesAsync(GameDbContext db, ulong characterId)
{
// Get explicitly known recipes
var knownRecipeIds = await db.DungeonCharacterKnownRecipes
.Where(kr => kr.CharacterId == characterId)
.Select(kr => kr.RecipeId)
.ToListAsync();
// Also include base recipes that everyone knows
var baseRecipeIds = _recipes.Values
.Where(r => r.IsBaseRecipe)
.Select(r => r.Id);
var allKnownIds = knownRecipeIds.Union(baseRecipeIds).ToHashSet();
return _recipes.Values.Where(r => allKnownIds.Contains(r.Id)).ToList();
}
/// <summary>
/// Try to discover a recipe by combining ingredients
/// Returns the recipe if discovered, null otherwise
/// </summary>
public async Task<(DungeonCraftingRecipe? Recipe, bool AlreadyKnown, string? Error)> TryDiscoverRecipeAsync(
GameDbContext db, ulong characterId, List<(int ItemDefinitionId, int Quantity)> ingredients,
CraftingSkillType? skillTypeFilter = null)
{
// Build hash from ingredients
var sortedIngredients = ingredients.OrderBy(i => i.ItemDefinitionId).ThenBy(i => i.Quantity).ToList();
var hash = GetIngredientHashFromInput(sortedIngredients);
_log.LogInformation("Discovery attempt - Hash: {Hash}, SkillFilter: {Skill}, Ingredients: {Ing}",
hash, skillTypeFilter, string.Join(", ", ingredients.Select(i => $"{i.ItemDefinitionId}x{i.Quantity}")));
if (!_ingredientHashToRecipeId.TryGetValue(hash, out var recipeId))
{
_log.LogInformation("No recipe found for hash {Hash}. Known hashes: {Hashes}",
hash, string.Join(", ", _ingredientHashToRecipeId.Keys.Take(10)));
return (null, false, "No recipe found for these ingredients");
}
var recipe = _recipes[recipeId];
// Check skill type filter
if (skillTypeFilter.HasValue && recipe.SkillType != skillTypeFilter.Value)
{
return (null, false, $"This combination creates something in {recipe.SkillType}, not {skillTypeFilter.Value}");
}
// Check if already known
var alreadyKnown = await db.DungeonCharacterKnownRecipes
.AnyAsync(kr => kr.CharacterId == characterId && kr.RecipeId == recipeId);
if (alreadyKnown)
{
return (recipe, true, null);
}
// Learn the recipe
db.DungeonCharacterKnownRecipes.Add(new DungeonCharacterKnownRecipe
{
CharacterId = characterId,
RecipeId = recipeId,
DiscoveredAt = DateTime.UtcNow
});
await db.SaveChangesAsync();
_log.LogInformation("Character {CharId} discovered recipe: {Recipe}", characterId, recipe.Name);
return (recipe, false, null);
}
/// <summary>
/// Consume materials on failed discovery attempt (65% chance to lose materials)
/// </summary>
public async Task<(bool MaterialsLost, List<string> LostItems)> TryConsumeMaterialsOnFailedDiscoveryAsync(
GameDbContext db, ulong characterId, List<(int ItemDefinitionId, int Quantity)> ingredients)
{
const float MATERIAL_LOSS_CHANCE = 0.65f;
var rng = new Random();
if (rng.NextDouble() >= MATERIAL_LOSS_CHANCE)
{
// Lucky! Materials saved
return (false, new List<string>());
}
// Load inventory
var inventory = await db.DungeonCharacterItems
.Where(i => i.CharacterId == characterId && !i.IsEquipped)
.ToListAsync();
var lostItems = new List<string>();
foreach (var (itemDefId, qty) in ingredients)
{
int remaining = qty;
var stacks = inventory.Where(i => i.ItemDefinitionId == itemDefId).ToList();
foreach (var stack in stacks)
{
if (remaining <= 0) break;
int toRemove = Math.Min(remaining, stack.Quantity);
stack.Quantity -= toRemove;
remaining -= toRemove;
if (stack.Quantity <= 0)
{
db.DungeonCharacterItems.Remove(stack);
}
}
// Get item name for message
var itemDef = await db.DungeonItemDefinitions.FindAsync(itemDefId);
if (itemDef != null)
{
lostItems.Add($"{qty}x {itemDef.Name}");
}
}
await db.SaveChangesAsync();
_log.LogInformation("Character {CharId} lost materials on failed discovery: {Items}",
characterId, string.Join(", ", lostItems));
return (true, lostItems);
}
/// <summary>
/// Craft an item from a known recipe
/// </summary>
public async Task<CraftingResult> CraftItemAsync(
GameDbContext db,
ulong characterId,
int recipeId,
DungeonCharacter character)
{
if (!_recipes.TryGetValue(recipeId, out var recipe))
{
return new CraftingResult { Success = false, ErrorMessage = "Recipe not found" };
}
// Verify character knows the recipe
var isBaseRecipe = recipe.IsBaseRecipe;
var knowsRecipe = isBaseRecipe || await db.DungeonCharacterKnownRecipes
.AnyAsync(kr => kr.CharacterId == characterId && kr.RecipeId == recipeId);
if (!knowsRecipe)
{
return new CraftingResult { Success = false, ErrorMessage = "You don't know this recipe" };
}
// Get crafting skill
var skill = await GetOrCreateCraftingSkillAsync(db, characterId, recipe.SkillType);
// Check level requirement
if (skill.Level < recipe.RequiredLevel)
{
return new CraftingResult
{
Success = false,
ErrorMessage = $"Requires {recipe.SkillType} level {recipe.RequiredLevel}"
};
}
// Verify ingredients
var inventory = await db.DungeonCharacterItems
.Where(i => i.CharacterId == characterId && !i.IsEquipped)
.ToListAsync();
var ingredientsToConsume = new List<(DungeonCharacterItem Item, int ConsumeCount)>();
foreach (var ingredient in recipe.Ingredients)
{
var availableItems = inventory
.Where(i => i.ItemDefinitionId == ingredient.ItemDefinitionId)
.ToList();
int totalAvailable = availableItems.Sum(i => i.Quantity);
if (totalAvailable < ingredient.Quantity)
{
var itemDef = await db.DungeonItemDefinitions.FindAsync(ingredient.ItemDefinitionId);
return new CraftingResult
{
Success = false,
ErrorMessage = $"Need {ingredient.Quantity} {itemDef?.Name ?? "items"} (have {totalAvailable})"
};
}
// Mark items to consume
int remaining = ingredient.Quantity;
foreach (var item in availableItems)
{
if (remaining <= 0) break;
int toConsume = Math.Min(remaining, item.Quantity);
ingredientsToConsume.Add((item, toConsume));
remaining -= toConsume;
}
}
// Consume ingredients
foreach (var (item, consumeCount) in ingredientsToConsume)
{
item.Quantity -= consumeCount;
if (item.Quantity <= 0)
{
db.DungeonCharacterItems.Remove(item);
}
}
// Create output item
var outputItemDef = await db.DungeonItemDefinitions.FindAsync(recipe.OutputItemDefinitionId);
if (outputItemDef == null)
{
return new CraftingResult { Success = false, ErrorMessage = "Invalid recipe output" };
}
// Check for bonus output (upgraded item at higher levels)
bool gotBonusOutput = false;
int finalOutputItemId = recipe.OutputItemDefinitionId;
int finalOutputQuantity = recipe.OutputQuantity;
if (recipe.BonusOutputItemDefinitionId.HasValue &&
skill.Level >= recipe.BonusOutputMinLevel)
{
// Calculate bonus chance based on level
// At BonusOutputMinLevel: BonusOutputChanceAtMinLevel% chance
// At BonusOutputMaxLevel: 100% chance
// Linear interpolation between
float levelRange = recipe.BonusOutputMaxLevel - recipe.BonusOutputMinLevel;
float levelProgress = Math.Min(1f, (skill.Level - recipe.BonusOutputMinLevel) / Math.Max(1f, levelRange));
float bonusChance = recipe.BonusOutputChanceAtMinLevel +
(100f - recipe.BonusOutputChanceAtMinLevel) * levelProgress;
var rng = new Random();
if (rng.NextDouble() * 100 < bonusChance)
{
gotBonusOutput = true;
finalOutputItemId = recipe.BonusOutputItemDefinitionId.Value;
finalOutputQuantity = recipe.BonusOutputQuantity;
outputItemDef = await db.DungeonItemDefinitions.FindAsync(finalOutputItemId);
_log.LogInformation("Character {CharId} got bonus output! {BonusChance:F1}% chance",
characterId, bonusChance);
}
}
DungeonCraftedItem? craftedItem = null;
var rollResults = new List<(string Stat, int Value)>();
// Handle stat rolling for equipment
if (recipe.HasStatRolls && outputItemDef != null)
{
_log.LogInformation("Crafting item {ItemName} with stat rolls. MinStr={MinStr}, MaxStr={MaxStr}",
outputItemDef.Name, outputItemDef.MinBonusStrength, outputItemDef.MaxBonusStrength);
var rng = new Random();
craftedItem = new DungeonCraftedItem
{
BaseItemDefinitionId = finalOutputItemId,
CrafterId = characterId,
CrafterName = character.Name,
RecipeId = recipeId,
CraftedAt = DateTime.UtcNow,
CraftingLevelAtCreation = skill.Level
};
// Calculate skill quality bonus
// 2x required level = 50% chance for max on each roll
// Formula: skillBonus = min(1.0, skill.Level / (recipe.RequiredLevel * 2))
float skillBonus = Math.Min(1.0f, (float)skill.Level / (recipe.RequiredLevel * 2));
_log.LogInformation("Skill bonus: {SkillBonus} (level {Level} / required {Required})",
skillBonus, skill.Level, recipe.RequiredLevel);
int totalRolled = 0;
int maxPossibleTotal = 0;
// Roll each stat that has a range defined on the item
rollResults = RollItemStats(outputItemDef, skillBonus, rng, out totalRolled, out maxPossibleTotal);
_log.LogInformation("Rolled {Count} stats, total={Total}, maxPossible={Max}",
rollResults.Count, totalRolled, maxPossibleTotal);
// Apply rolled stats to the crafted item
foreach (var (stat, value) in rollResults)
{
_log.LogInformation("Applying stat {Stat} = {Value}", stat, value);
ApplyStatRoll(craftedItem, stat, value);
}
// If no ranges defined, fall back to old system using recipe's PossibleStats
if (rollResults.Count == 0 && recipe.PossibleStats.Count > 0)
{
int rollCount = skill.StatRollCount;
int minRoll = skill.MinStatRoll;
int maxRoll = skill.MaxStatRoll;
for (int i = 0; i < rollCount; i++)
{
var stat = recipe.PossibleStats[rng.Next(recipe.PossibleStats.Count)];
int value = RollWithSkillBonus(minRoll, maxRoll, skillBonus, rng);
totalRolled += value;
maxPossibleTotal += maxRoll;
ApplyStatRoll(craftedItem, stat, value);
rollResults.Add((stat, value));
}
}
// Calculate quality rating (0-100 based on how good the rolls were)
craftedItem.QualityRating = maxPossibleTotal > 0
? (int)(100f * totalRolled / maxPossibleTotal)
: 50;
craftedItem.RollHistoryJson = JsonSerializer.Serialize(rollResults.Select(r => new { stat = r.Stat, value = r.Value }));
db.DungeonCraftedItems.Add(craftedItem);
}
// Check if we can stack with existing items (only for non-crafted items without stat rolls)
int finalSlotIndex = -1;
bool addedToStack = false;
if (!recipe.HasStatRolls && outputItemDef != null && outputItemDef.Stackable)
{
// Find existing stack of same item
var existingStack = inventory.FirstOrDefault(i =>
i.ItemDefinitionId == finalOutputItemId &&
!i.IsEquipped &&
i.Quantity < (outputItemDef.MaxStack > 0 ? outputItemDef.MaxStack : 99));
if (existingStack != null)
{
int canAdd = (outputItemDef.MaxStack > 0 ? outputItemDef.MaxStack : 99) - existingStack.Quantity;
int toAdd = Math.Min(canAdd, finalOutputQuantity);
existingStack.Quantity += toAdd;
finalSlotIndex = existingStack.SlotIndex;
addedToStack = true;
// If we couldn't add all, we need a new slot for the rest
if (toAdd < finalOutputQuantity)
{
finalOutputQuantity -= toAdd;
addedToStack = false; // Need to create new item for remainder
}
else
{
finalOutputQuantity = 0;
}
}
}
// If not stacked (or remainder), find empty slot and create new item
if (!addedToStack || finalOutputQuantity > 0)
{
var usedSlots = inventory.Where(i => i.CharacterId == characterId && !i.IsEquipped).Select(i => i.SlotIndex).ToHashSet();
int emptySlot = -1;
for (int i = 0; i < 30; i++)
{
if (!usedSlots.Contains(i))
{
emptySlot = i;
break;
}
}
if (emptySlot == -1 && finalOutputQuantity > 0)
{
return new CraftingResult { Success = false, ErrorMessage = "Inventory full" };
}
if (finalOutputQuantity > 0)
{
var newItem = new DungeonCharacterItem
{
CharacterId = characterId,
ItemDefinitionId = finalOutputItemId,
Quantity = finalOutputQuantity,
SlotIndex = emptySlot,
IsEquipped = false,
AcquiredAt = DateTime.UtcNow
};
db.DungeonCharacterItems.Add(newItem);
finalSlotIndex = emptySlot;
// Link crafted item if applicable
if (craftedItem != null)
{
await db.SaveChangesAsync(); // Save to get newItem.Id
db.DungeonCharacterItemCraftedLinks.Add(new DungeonCharacterItemCraftedLink
{
CharacterItemId = newItem.Id,
CraftedItemId = craftedItem.Id
});
}
}
}
await db.SaveChangesAsync();
// Award XP
int xpGained = DungeonCharacterCraftingSkill.GetCraftingXp(recipe.Tier, skill.Level);
skill.Experience += xpGained;
skill.TotalItemsCrafted++;
// Check for level up
bool leveledUp = false;
while (skill.Level < 100 && skill.Experience >= skill.ExperienceForNextLevel)
{
skill.Experience -= skill.ExperienceForNextLevel;
skill.Level++;
leveledUp = true;
}
// Update known recipe craft count
var knownRecipe = await db.DungeonCharacterKnownRecipes
.FirstOrDefaultAsync(kr => kr.CharacterId == characterId && kr.RecipeId == recipeId);
if (knownRecipe != null)
{
knownRecipe.TimesCrafted++;
}
await db.SaveChangesAsync();
_log.LogInformation("Character {CharId} crafted {Item} (quality {Quality}, +{Xp} XP)",
characterId, outputItemDef.Name, craftedItem?.QualityRating ?? 0, xpGained);
return new CraftingResult
{
Success = true,
OutputItem = outputItemDef,
CraftedItem = craftedItem,
RollResults = rollResults,
XpGained = xpGained,
NewSkillLevel = skill.Level,
LeveledUp = leveledUp,
SlotIndex = finalSlotIndex,
GotBonusOutput = gotBonusOutput,
OutputQuantity = recipe.OutputQuantity,
AddedToStack = addedToStack
};
}
/// <summary>
/// Roll item stats using the item definition's min/max ranges.
/// Higher skill bonus = higher chance for max values.
/// </summary>
private List<(string Stat, int Value)> RollItemStats(
DungeonItemDefinition item,
float skillBonus,
Random rng,
out int totalRolled,
out int maxPossibleTotal)
{
var results = new List<(string Stat, int Value)>();
int rolled = 0;
int maxTotal = 0;
// Helper to roll a stat
void AddRoll(string statName, int min, int max)
{
if (max > min) // Only roll if there's a range
{
int value = RollWithSkillBonus(min, max, skillBonus, rng);
results.Add((statName, value));
rolled += value;
maxTotal += max;
}
else if (max > 0) // Fixed value
{
results.Add((statName, max));
rolled += max;
maxTotal += max;
}
}
// Stat bonuses
AddRoll("BonusStrength", item.MinBonusStrength, item.MaxBonusStrength);
AddRoll("BonusIntelligence", item.MinBonusIntelligence, item.MaxBonusIntelligence);
AddRoll("BonusWisdom", item.MinBonusWisdom, item.MaxBonusWisdom);
AddRoll("BonusEndurance", item.MinBonusEndurance, item.MaxBonusEndurance);
AddRoll("BonusDexterity", item.MinBonusDexterity, item.MaxBonusDexterity);
AddRoll("BonusHealth", item.MinBonusHealth, item.MaxBonusHealth);
AddRoll("BonusMana", item.MinBonusMana, item.MaxBonusMana);
// Weapon damage
AddRoll("MinDamage", item.MinMinDamage, item.MaxMinDamage);
AddRoll("MaxDamage", item.MinMaxDamage, item.MaxMaxDamage);
// Armor
AddRoll("Armor", item.MinArmor, item.MaxArmor);
totalRolled = rolled;
maxPossibleTotal = maxTotal;
return results;
}
/// <summary>
/// Roll a value between min and max, biased toward max based on skill bonus.
/// skillBonus of 0.5 = 50% chance to get max value
/// skillBonus of 1.0 = always get max value
/// </summary>
private int RollWithSkillBonus(int min, int max, float skillBonus, Random rng)
{
if (min >= max) return max;
// Roll to see if we get max
if (rng.NextDouble() < skillBonus)
{
return max;
}
// Otherwise roll normally
return rng.Next(min, max + 1);
}
private void ApplyStatRoll(DungeonCraftedItem item, string stat, int value)
{
switch (stat)
{
case "BonusStrength": item.RolledBonusStrength += value; break;
case "BonusIntelligence": item.RolledBonusIntelligence += value; break;
case "BonusWisdom": item.RolledBonusWisdom += value; break;
case "BonusEndurance": item.RolledBonusEndurance += value; break;
case "BonusDexterity": item.RolledBonusDexterity += value; break;
case "BonusHealth": item.RolledBonusHealth += value; break;
case "BonusMana": item.RolledBonusMana += value; break;
case "Armor": item.RolledBonusArmor += value; break;
case "MagicResist": item.RolledBonusMagicResist += value; break;
case "MinDamage": item.RolledBonusMinDamage += value; break;
case "MaxDamage": item.RolledBonusMaxDamage += value; break;
case "HealAmount": item.RolledBonusHealAmount += value; break;
case "ManaRestore": item.RolledBonusManaRestore += value; break;
}
}
private string GetIngredientHash(List<DungeonCraftingRecipeIngredient> ingredients)
{
var parts = ingredients
.OrderBy(i => i.ItemDefinitionId)
.ThenBy(i => i.Quantity)
.Select(i => $"{i.ItemDefinitionId}:{i.Quantity}");
return string.Join("|", parts);
}
private string GetIngredientHashFromInput(List<(int ItemDefinitionId, int Quantity)> ingredients)
{
var parts = ingredients
.OrderBy(i => i.ItemDefinitionId)
.ThenBy(i => i.Quantity)
.Select(i => $"{i.ItemDefinitionId}:{i.Quantity}");
return string.Join("|", parts);
}
}
public class CraftingResult
{
public bool Success { get; set; }
public string? ErrorMessage { get; set; }
public DungeonItemDefinition? OutputItem { get; set; }
public DungeonCraftedItem? CraftedItem { get; set; }
public List<(string Stat, int Value)> RollResults { get; set; } = new();
public int XpGained { get; set; }
public int NewSkillLevel { get; set; }
public bool LeveledUp { get; set; }
public int SlotIndex { get; set; }
public bool GotBonusOutput { get; set; }
public int OutputQuantity { get; set; }
public bool AddedToStack { get; set; }
}