3161 lines
126 KiB
C#
3161 lines
126 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Text.Json;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
using DataServer.Data;
|
|
using DataServer.Data.Entities;
|
|
using DataServer.Data.Enums;
|
|
using Server.Networking;
|
|
using Server.Networking.Handling;
|
|
using Server.Networking.Messages;
|
|
using Server.Redis;
|
|
using GameServices;
|
|
using GameServices.Auth;
|
|
using GameServer.Networking.DTOs;
|
|
|
|
namespace GameServer.Dungeon;
|
|
|
|
/// <summary>
|
|
/// Handles dungeon crawler game messages via the server's message router
|
|
/// Implements IClientMessageHandler for integration with existing infrastructure
|
|
/// </summary>
|
|
public sealed partial class DungeonHandler : IClientMessageHandler
|
|
{
|
|
private readonly ILogger<DungeonHandler> _log;
|
|
private readonly ISessionRegistry _sessions;
|
|
private readonly IMessageSerializer _ser;
|
|
private readonly IServiceScopeFactory _scopeFactory;
|
|
private readonly IServerBroadcastService _broadcastService;
|
|
private readonly IRedisManager _redis;
|
|
|
|
// Pod identifier for multi-instance tracking
|
|
private readonly string _podId;
|
|
|
|
// Player state tracking (keyed by connection ID)
|
|
private readonly ConcurrentDictionary<Guid, DungeonPlayerSession> _playerSessions = new();
|
|
|
|
// Active dungeon instances
|
|
private readonly ConcurrentDictionary<Guid, DungeonInstance> _dungeons = new();
|
|
|
|
// Mob definitions cache
|
|
private Dictionary<int, DungeonMobDefinition> _mobDefinitions = new();
|
|
private Dictionary<int, string?> _mobSpriteConfigs = new(); // MobDefinitionId -> SpriteConfig JSON
|
|
private bool _initialized = false;
|
|
|
|
|
|
// Tick management
|
|
private Timer? _tickTimer;
|
|
private long _currentTick = 0;
|
|
|
|
//LootSystem
|
|
private LootService _lootService = null!;
|
|
|
|
// Crafting
|
|
private CraftingHandler _craftingHandler = null!;
|
|
|
|
public DungeonHandler(
|
|
ILogger<DungeonHandler> log,
|
|
ISessionRegistry sessions,
|
|
IMessageSerializer ser,
|
|
IServiceScopeFactory scopeFactory,
|
|
LootService lootService,
|
|
CraftingHandler craftingHandler,
|
|
IServerBroadcastService broadcastService,
|
|
IRedisManager redis)
|
|
{
|
|
_log = log;
|
|
_sessions = sessions;
|
|
_ser = ser;
|
|
_scopeFactory = scopeFactory;
|
|
_lootService = lootService;
|
|
_craftingHandler = craftingHandler;
|
|
_broadcastService = broadcastService;
|
|
_redis = redis;
|
|
|
|
// Generate unique pod ID (use hostname in K8s, or random for local dev)
|
|
_podId = Environment.GetEnvironmentVariable("HOSTNAME")
|
|
?? Environment.GetEnvironmentVariable("POD_NAME")
|
|
?? $"local-{Guid.NewGuid().ToString()[..8]}";
|
|
}
|
|
|
|
public IReadOnlyCollection<int> SupportedOpCodes => new[]
|
|
{
|
|
DungeonOpCodes.HUB_STATE,
|
|
DungeonOpCodes.STAT_ALLOCATE,
|
|
DungeonOpCodes.DUNGEON_ENTER,
|
|
DungeonOpCodes.DUNGEON_LEAVE,
|
|
DungeonOpCodes.DUNGEON_INPUT_MOVE,
|
|
DungeonOpCodes.DUNGEON_INPUT_ATTACK,
|
|
DungeonOpCodes.DUNGEON_INPUT_PICKUP,
|
|
DungeonOpCodes.DUNGEON_INPUT_CHEST,
|
|
DungeonOpCodes.DUNGEON_INPUT_PORTAL,
|
|
DungeonOpCodes.DUNGEON_INPUT_FIRE_PROJECTILE,
|
|
DungeonOpCodes.INVENTORY_REQUEST,
|
|
DungeonOpCodes.EQUIP_ITEM,
|
|
DungeonOpCodes.UNEQUIP_ITEM,
|
|
DungeonOpCodes.USE_ITEM,
|
|
DungeonOpCodes.DROP_ITEM,
|
|
DungeonOpCodes.CHAT_SEND,
|
|
DungeonOpCodes.HOTBAR_ASSIGN,
|
|
// Loot chest operations
|
|
DungeonOpCodes.LOOT_CHEST_OPEN,
|
|
DungeonOpCodes.LOOT_CHEST_TAKE_ITEM,
|
|
DungeonOpCodes.LOOT_CHEST_TAKE_ALL,
|
|
DungeonOpCodes.LOOT_CHEST_CLOSE,
|
|
//Mob Loot
|
|
DungeonOpCodes.MOB_LOOT_REQUEST,
|
|
DungeonOpCodes.MOB_LOOT_TAKE_ALL,
|
|
DungeonOpCodes.MOB_LOOT_TAKE_ITEM,
|
|
// Dungeon browser
|
|
DungeonOpCodes.DUNGEON_LIST_REQUEST,
|
|
DungeonOpCodes.DUNGEON_CREATE,
|
|
DungeonOpCodes.DUNGEON_JOIN,
|
|
// Asset management
|
|
DungeonOpCodes.ASSET_MANIFEST_REQUEST,
|
|
// Crafting
|
|
DungeonOpCodes.CRAFTING_SKILLS_REQUEST,
|
|
DungeonOpCodes.CRAFTING_RECIPES_REQUEST,
|
|
DungeonOpCodes.CRAFTING_ATTEMPT,
|
|
// Stash (VIP)
|
|
DungeonOpCodes.STASH_REQUEST,
|
|
DungeonOpCodes.STASH_DEPOSIT,
|
|
DungeonOpCodes.STASH_WITHDRAW,
|
|
//Inventory
|
|
DungeonOpCodes.MOVE_ITEM,
|
|
DungeonOpCodes.STACK_ITEMS,
|
|
DungeonOpCodes.AUTO_STACK_INVENTORY,
|
|
|
|
OpCodes.PONG
|
|
};
|
|
|
|
public async Task InitializeAsync()
|
|
{
|
|
if (_initialized) return;
|
|
|
|
await LoadMobDefinitionsAsync();
|
|
await _lootService.InitializeAsync();
|
|
|
|
// Subscribe to Redis broadcast channel for multi-pod support
|
|
await SubscribeToBroadcastChannelAsync();
|
|
|
|
// Start tick loop (20 ticks per second)
|
|
_tickTimer = new Timer(TickAll, null, 0, 50);
|
|
|
|
_initialized = true;
|
|
_log.LogInformation("DungeonHandler initialized on pod {PodId} with {MobCount} mob definitions", _podId, _mobDefinitions.Count);
|
|
}
|
|
|
|
public async Task HandleAsync(int opCode, IConnection connection, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
// Ensure initialized
|
|
if (!_initialized)
|
|
{
|
|
await InitializeAsync();
|
|
}
|
|
if (opCode == DungeonOpCodes.ASSET_MANIFEST_REQUEST)
|
|
{
|
|
await HandleAssetManifestRequest(connection, ct);
|
|
}
|
|
// All dungeon operations require authentication
|
|
if (!_sessions.TryGet(connection.Id, out var accountId, out _))
|
|
{
|
|
await SendErrorAsync(connection, $"auth_required for packet: {opCode}", ct);
|
|
return;
|
|
}
|
|
|
|
// Get or create player session
|
|
var session = await GetOrCreateSessionAsync(connection, accountId, ct);
|
|
if (session == null)
|
|
{
|
|
await SendErrorAsync(connection, "no_character", ct);
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
switch (opCode)
|
|
{
|
|
case DungeonOpCodes.HUB_STATE:
|
|
await HandleHubStateRequest(connection, session, ct);
|
|
break;
|
|
|
|
case DungeonOpCodes.STAT_ALLOCATE:
|
|
await HandleStatAllocate(connection, session, payload, ct);
|
|
break;
|
|
|
|
case DungeonOpCodes.DUNGEON_ENTER:
|
|
await HandleDungeonEnter(connection, session, payload, ct);
|
|
break;
|
|
|
|
case DungeonOpCodes.DUNGEON_LEAVE:
|
|
await HandleDungeonLeave(connection, session, ct);
|
|
break;
|
|
|
|
case DungeonOpCodes.DUNGEON_INPUT_MOVE:
|
|
HandleInputMove(session, payload);
|
|
break;
|
|
|
|
case DungeonOpCodes.DUNGEON_INPUT_ATTACK:
|
|
HandleInputAttack(session, payload);
|
|
break;
|
|
|
|
case DungeonOpCodes.DUNGEON_INPUT_PICKUP:
|
|
HandleInputPickup(session, payload);
|
|
break;
|
|
|
|
case DungeonOpCodes.DUNGEON_INPUT_CHEST:
|
|
HandleInputChest(session, payload);
|
|
break;
|
|
|
|
case DungeonOpCodes.DUNGEON_INPUT_PORTAL:
|
|
await HandlePortalUse(connection, session, payload, ct);
|
|
break;
|
|
|
|
case DungeonOpCodes.DUNGEON_INPUT_FIRE_PROJECTILE:
|
|
await HandleFireProjectile(connection, session, payload, ct);
|
|
break;
|
|
|
|
case DungeonOpCodes.INVENTORY_REQUEST:
|
|
await HandleInventoryRequest(connection, session, ct);
|
|
break;
|
|
|
|
case DungeonOpCodes.EQUIP_ITEM:
|
|
await HandleEquipItem(connection, session, payload, ct);
|
|
break;
|
|
|
|
case DungeonOpCodes.UNEQUIP_ITEM:
|
|
await HandleUnequipItem(connection, session, payload, ct);
|
|
break;
|
|
|
|
case DungeonOpCodes.USE_ITEM:
|
|
await HandleUseItem(connection, session, payload, ct);
|
|
break;
|
|
case DungeonOpCodes.STACK_ITEMS:
|
|
await HandleStackItems(connection, session, payload, ct);
|
|
break;
|
|
case DungeonOpCodes.MOVE_ITEM:
|
|
await HandleMoveItem(connection, session, payload, ct);
|
|
break;
|
|
case DungeonOpCodes.AUTO_STACK_INVENTORY:
|
|
await HandleAutoStackInventory(connection, session, ct);
|
|
break;
|
|
case DungeonOpCodes.CHAT_SEND:
|
|
await HandleChatSend(connection, session, payload, ct);
|
|
break;
|
|
case DungeonOpCodes.HOTBAR_ASSIGN:
|
|
await HandleHotbarAssign(connection, session, payload, ct);
|
|
break;
|
|
|
|
// Loot chest operations
|
|
case DungeonOpCodes.LOOT_CHEST_OPEN:
|
|
await HandleLootChestOpen(connection, session, payload, ct);
|
|
break;
|
|
case DungeonOpCodes.LOOT_CHEST_TAKE_ITEM:
|
|
await HandleLootChestTakeItem(connection, session, payload, ct);
|
|
break;
|
|
case DungeonOpCodes.LOOT_CHEST_TAKE_ALL:
|
|
await HandleLootChestTakeAll(connection, session, payload, ct);
|
|
break;
|
|
case DungeonOpCodes.LOOT_CHEST_CLOSE:
|
|
await HandleLootChestClose(connection, session, payload, ct);
|
|
break;
|
|
|
|
// Mob loot operations
|
|
case DungeonOpCodes.MOB_LOOT_REQUEST:
|
|
await HandleMobLootRequest(connection, session, payload, ct);
|
|
break;
|
|
case DungeonOpCodes.MOB_LOOT_TAKE_ITEM:
|
|
await HandleMobLootTakeItem(connection, session, payload, ct);
|
|
break;
|
|
case DungeonOpCodes.MOB_LOOT_TAKE_ALL:
|
|
await HandleMobLootTakeAll(connection, session, payload, ct);
|
|
break;
|
|
|
|
// Dungeon browser
|
|
case DungeonOpCodes.DUNGEON_LIST_REQUEST:
|
|
await HandleDungeonListRequest(connection, session, ct);
|
|
break;
|
|
case DungeonOpCodes.DUNGEON_CREATE:
|
|
await HandleDungeonCreate(connection, session, payload, ct);
|
|
break;
|
|
case DungeonOpCodes.DUNGEON_JOIN:
|
|
await HandleDungeonJoin(connection, session, payload, ct);
|
|
break;
|
|
case DungeonOpCodes.ASSET_MANIFEST_REQUEST:
|
|
await HandleAssetManifestRequest(connection, ct);
|
|
break;
|
|
|
|
// Crafting
|
|
case DungeonOpCodes.CRAFTING_SKILLS_REQUEST:
|
|
await HandleCraftingSkillsRequest(connection, session, ct);
|
|
break;
|
|
case DungeonOpCodes.CRAFTING_RECIPES_REQUEST:
|
|
await HandleCraftingRecipesRequest(connection, session, ct);
|
|
break;
|
|
case DungeonOpCodes.CRAFTING_ATTEMPT:
|
|
await HandleCraftingAttempt(connection, session, payload, ct);
|
|
break;
|
|
|
|
// Stash (VIP Feature)
|
|
case DungeonOpCodes.STASH_REQUEST:
|
|
await HandleStashRequest(connection, session, ct);
|
|
break;
|
|
case DungeonOpCodes.STASH_DEPOSIT:
|
|
await HandleStashDeposit(connection, session, payload, ct);
|
|
break;
|
|
case DungeonOpCodes.STASH_WITHDRAW:
|
|
await HandleStashWithdraw(connection, session, payload, ct);
|
|
break;
|
|
|
|
case OpCodes.PONG:
|
|
break;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_log.LogError(ex, "Error handling dungeon opcode {OpCode} for account {AccountId}", opCode, accountId);
|
|
await SendErrorAsync(connection, "internal_error", ct);
|
|
}
|
|
}
|
|
|
|
private async Task<DungeonPlayerSession?> GetOrCreateSessionAsync(IConnection connection, ulong accountId, CancellationToken ct)
|
|
{
|
|
if (_playerSessions.TryGetValue(connection.Id, out var existing))
|
|
{
|
|
return existing;
|
|
}
|
|
|
|
// Load character from database
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
var character = await db.Set<DungeonCharacter>()
|
|
.FirstOrDefaultAsync(c => c.AccountId == accountId && !c.IsDeleted, ct);
|
|
|
|
if (character == null)
|
|
{
|
|
// Auto-create a character for this account
|
|
character = new DungeonCharacter
|
|
{
|
|
AccountId = accountId,
|
|
Name = $"Hero_{accountId}",
|
|
Level = 1,
|
|
UnspentStatPoints = 5,
|
|
Strength = 1,
|
|
Intelligence = 1,
|
|
Wisdom = 1,
|
|
Endurance = 1,
|
|
Dexterity = 1
|
|
};
|
|
|
|
db.Set<DungeonCharacter>().Add(character);
|
|
await db.SaveChangesAsync(ct);
|
|
_log.LogInformation("Created new dungeon character for account {AccountId}", accountId);
|
|
}
|
|
|
|
var session = new DungeonPlayerSession
|
|
{
|
|
ConnectionId = connection.Id,
|
|
Connection = connection,
|
|
AccountId = accountId,
|
|
CharacterId = character.Id,
|
|
Character = character,
|
|
State = PlayerState.InHub
|
|
};
|
|
|
|
_playerSessions[connection.Id] = session;
|
|
|
|
// Track in Redis for global player count
|
|
await TrackPlayerConnectedAsync(session);
|
|
|
|
return session;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Track player connection in Redis for global stats
|
|
/// </summary>
|
|
private async Task TrackPlayerConnectedAsync(DungeonPlayerSession session)
|
|
{
|
|
try
|
|
{
|
|
// Increment global player count
|
|
await _redis.Db.StringIncrementAsync("stats:players");
|
|
|
|
// Store player session info for this pod
|
|
await _redis.SetJsonAsync($"player:{session.CharacterId}", new
|
|
{
|
|
accountId = session.AccountId,
|
|
characterId = session.CharacterId,
|
|
characterName = session.Character.Name,
|
|
podId = _podId,
|
|
state = session.State.ToString(),
|
|
connectedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
|
|
}, TimeSpan.FromHours(24));
|
|
|
|
_log.LogDebug("Player {CharacterId} connected on pod {PodId}", session.CharacterId, _podId);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_log.LogWarning(ex, "Failed to track player connection in Redis");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Remove player tracking from Redis
|
|
/// </summary>
|
|
private async Task TrackPlayerDisconnectedAsync(DungeonPlayerSession session)
|
|
{
|
|
try
|
|
{
|
|
// Decrement global player count (don't go below 0)
|
|
var count = await _redis.Db.StringDecrementAsync("stats:players");
|
|
if (count < 0)
|
|
{
|
|
await _redis.Db.StringSetAsync("stats:players", 0);
|
|
}
|
|
|
|
// Remove player session info
|
|
await _redis.Db.KeyDeleteAsync($"player:{session.CharacterId}");
|
|
|
|
_log.LogDebug("Player {CharacterId} disconnected from pod {PodId}", session.CharacterId, _podId);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_log.LogWarning(ex, "Failed to track player disconnection in Redis");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Track dungeon creation in Redis
|
|
/// </summary>
|
|
private async Task TrackDungeonCreatedAsync(DungeonInstance dungeon)
|
|
{
|
|
try
|
|
{
|
|
// Increment global dungeon count
|
|
await _redis.Db.StringIncrementAsync("stats:dungeons");
|
|
|
|
// Store dungeon info
|
|
await _redis.SetJsonAsync($"dungeon:{dungeon.Id}", new
|
|
{
|
|
id = dungeon.Id.ToString(),
|
|
tier = dungeon.Tier,
|
|
podId = _podId,
|
|
creatorName = dungeon.CreatorName,
|
|
creatorLevel = dungeon.CreatorLevel,
|
|
levelBracketMin = dungeon.LevelBracketMin,
|
|
levelBracketMax = dungeon.LevelBracketMax,
|
|
createdAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
|
|
}, TimeSpan.FromHours(2)); // Dungeons auto-expire from Redis after 2 hours
|
|
|
|
_log.LogDebug("Dungeon {DungeonId} created on pod {PodId}", dungeon.Id, _podId);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_log.LogWarning(ex, "Failed to track dungeon creation in Redis");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Track dungeon destruction in Redis
|
|
/// </summary>
|
|
private async Task TrackDungeonDestroyedAsync(Guid dungeonId)
|
|
{
|
|
try
|
|
{
|
|
// Decrement global dungeon count (don't go below 0)
|
|
var count = await _redis.Db.StringDecrementAsync("stats:dungeons");
|
|
if (count < 0)
|
|
{
|
|
await _redis.Db.StringSetAsync("stats:dungeons", 0);
|
|
}
|
|
|
|
// Remove dungeon info
|
|
await _redis.Db.KeyDeleteAsync($"dungeon:{dungeonId}");
|
|
|
|
_log.LogDebug("Dungeon {DungeonId} destroyed on pod {PodId}", dungeonId, _podId);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_log.LogWarning(ex, "Failed to track dungeon destruction in Redis");
|
|
}
|
|
}
|
|
|
|
private async Task HandleHubStateRequest(IConnection connection, DungeonPlayerSession session, CancellationToken ct)
|
|
{
|
|
var hubState = GetHubState(session.Character);
|
|
await SendAsync(connection, DungeonOpCodes.HUB_STATE, hubState, ct);
|
|
}
|
|
|
|
private async Task HandleStatAllocate(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
var request = _ser.Deserialize<StatAllocateRequest>(payload);
|
|
if (string.IsNullOrEmpty(request.Stat)) return;
|
|
|
|
var character = session.Character;
|
|
if (character.UnspentStatPoints <= 0) return;
|
|
|
|
switch (request.Stat.ToLower())
|
|
{
|
|
case "strength": character.Strength++; break;
|
|
case "str": character.Strength++; break;
|
|
case "intelligence": character.Intelligence++; break;
|
|
case "int": character.Intelligence++; break;
|
|
case "wisdom": character.Wisdom++; break;
|
|
case "wis": character.Wisdom++; break;
|
|
case "endurance": character.Endurance++; break;
|
|
case "end": character.Endurance++; break;
|
|
case "dexterity": character.Dexterity++; break;
|
|
case "dex": character.Dexterity++; break;
|
|
default: return;
|
|
}
|
|
|
|
character.UnspentStatPoints--;
|
|
|
|
// Save to database
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
db.Attach(character);
|
|
db.Entry(character).Property(c => c.Strength).IsModified = true;
|
|
db.Entry(character).Property(c => c.Intelligence).IsModified = true;
|
|
db.Entry(character).Property(c => c.Wisdom).IsModified = true;
|
|
db.Entry(character).Property(c => c.Endurance).IsModified = true;
|
|
db.Entry(character).Property(c => c.Dexterity).IsModified = true;
|
|
db.Entry(character).Property(c => c.UnspentStatPoints).IsModified = true;
|
|
await db.SaveChangesAsync(ct);
|
|
|
|
// If player is in dungeon, update their stats in simulation immediately
|
|
if (session.State == PlayerState.InDungeon && session.CurrentDungeonId.HasValue)
|
|
{
|
|
if (_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
|
|
{
|
|
if (dungeon.Simulation.Players.TryGetValue(session.CharacterId, out var player))
|
|
{
|
|
// Recalculate combat stats with new base stats
|
|
var equippedItems = await db.DungeonCharacterItems
|
|
.Include(i => i.ItemDefinition)
|
|
.Include(i => i.CraftedItem)
|
|
.Where(i => i.CharacterId == character.Id && i.IsEquipped)
|
|
.ToListAsync(ct);
|
|
|
|
var newStats = DungeonCharacterStats.GetCombatStats(character, equippedItems);
|
|
|
|
// Update player instance stats
|
|
player.Strength = newStats.Strength;
|
|
player.Intelligence = newStats.Intelligence;
|
|
player.Wisdom = newStats.Wisdom;
|
|
player.Endurance = newStats.Endurance;
|
|
player.Dexterity = newStats.Dexterity;
|
|
player.Armor = newStats.Armor;
|
|
player.MoveSpeed = newStats.MoveSpeed;
|
|
player.AttackSpeed = newStats.AttackSpeed;
|
|
|
|
// Update max health/mana/stamina and heal the difference
|
|
float oldMaxHealth = player.MaxHealth;
|
|
float oldMaxMana = player.MaxMana;
|
|
float oldMaxStamina = player.MaxStamina;
|
|
|
|
player.MaxHealth = newStats.MaxHealth;
|
|
player.MaxMana = newStats.MaxMana;
|
|
player.MaxStamina = newStats.MaxStamina;
|
|
|
|
// Heal the difference when max increases
|
|
if (newStats.MaxHealth > oldMaxHealth)
|
|
player.Health = Math.Min(newStats.MaxHealth, player.Health + (newStats.MaxHealth - oldMaxHealth));
|
|
if (newStats.MaxMana > oldMaxMana)
|
|
player.Mana = Math.Min(newStats.MaxMana, player.Mana + (newStats.MaxMana - oldMaxMana));
|
|
if (newStats.MaxStamina > oldMaxStamina)
|
|
player.Stamina = Math.Min(newStats.MaxStamina, player.Stamina + (newStats.MaxStamina - oldMaxStamina));
|
|
|
|
Console.WriteLine($"[StatAllocate] Updated {character.Name}'s stats in dungeon - STR:{player.Strength} INT:{player.Intelligence} WIS:{player.Wisdom} END:{player.Endurance} DEX:{player.Dexterity}");
|
|
}
|
|
}
|
|
}
|
|
|
|
await SendAsync(connection, DungeonOpCodes.HUB_STATE, GetHubState(character), ct);
|
|
}
|
|
|
|
private async Task HandleDungeonEnter(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
if (session.State == PlayerState.InDungeon)
|
|
{
|
|
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "already_in_dungeon" }, ct);
|
|
return;
|
|
}
|
|
var request = _ser.Deserialize<DungeonEnterRequest>(payload);
|
|
int tier = Math.Clamp(request.Tier, 1, 10);
|
|
int playerLevel = session.Character.Level;
|
|
var (bracketMin, bracketMax) = DungeonInstance.GetLevelBracket(playerLevel);
|
|
|
|
const int maxPlayersPerDungeon = 20;
|
|
|
|
// Try to find an existing dungeon of the same tier AND bracket that isn't full
|
|
DungeonInstance? instance = null;
|
|
Guid dungeonId = Guid.Empty;
|
|
|
|
foreach (var (id, dungeon) in _dungeons)
|
|
{
|
|
if (dungeon.Tier == tier &&
|
|
dungeon.LevelBracketMin == bracketMin && // Must match bracket
|
|
dungeon.Simulation.Phase == DungeonPhase.Active &&
|
|
dungeon.Simulation.Players.Count < maxPlayersPerDungeon &&
|
|
dungeon.IsJoinWindowOpen) // Use join window instead of hardcoded time
|
|
{
|
|
instance = dungeon;
|
|
dungeonId = id;
|
|
_log.LogInformation("Player {Name} joining existing dungeon {Id} (tier {Tier}, bracket {Min}-{Max}, {Players}/{Max} players)",
|
|
session.Character.Name, id, tier, bracketMin, bracketMax, dungeon.Simulation.Players.Count, maxPlayersPerDungeon);
|
|
|
|
// If dungeon is empty, respawn all mobs
|
|
if (dungeon.Simulation.Players.Count == 0)
|
|
{
|
|
RespawnAllMobs(dungeon);
|
|
_log.LogInformation("Respawned all mobs in dungeon {Id} (was empty when player joined via Quick Join)", id);
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Create new dungeon if none found
|
|
if (instance == null)
|
|
{
|
|
dungeonId = Guid.NewGuid();
|
|
int seed = Random.Shared.Next();
|
|
|
|
// Try V2 generator with room templates first
|
|
DungeonLayout layout;
|
|
DungeonLayoutV2? layoutV2 = null;
|
|
|
|
try
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
// First try V3 generator (DungeonBuilder templates)
|
|
var generator = new DungeonGeneratorV3(db, seed, tier);
|
|
layoutV2 = await generator.GenerateAsync();
|
|
|
|
// Check if V3 actually produced tiles (it might not if no palettes/templates exist)
|
|
if (layoutV2.TileDetails.Count == 0)
|
|
{
|
|
_log.LogWarning("V3 generator produced no tiles, falling back to V2");
|
|
var generatorV2 = new DungeonGeneratorV2(db, seed, tier);
|
|
layoutV2 = await generatorV2.GenerateAsync();
|
|
}
|
|
|
|
layout = layoutV2;
|
|
|
|
_log.LogInformation("Generated dungeon - {RoomCount} rooms, {TileCount} visual tiles",
|
|
layoutV2.Rooms.Count, layoutV2.TileDetails?.Count ?? 0);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_log.LogWarning(ex, "Dungeon generator failed, falling back to V2");
|
|
try
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
var generatorV2 = new DungeonGeneratorV2(db, seed, tier);
|
|
layoutV2 = await generatorV2.GenerateAsync();
|
|
layout = layoutV2;
|
|
}
|
|
catch (Exception ex2)
|
|
{
|
|
_log.LogWarning(ex2, "V2 generator also failed, using V1");
|
|
layout = DungeonGenerator.Generate(seed, tier);
|
|
}
|
|
}
|
|
|
|
var simulation = new DungeonSimulation(layout, tier, _mobDefinitions, bracketMin, null, _mobSpriteConfigs);
|
|
|
|
instance = new DungeonInstance
|
|
{
|
|
Id = dungeonId,
|
|
Tier = tier,
|
|
Seed = seed,
|
|
Simulation = simulation,
|
|
CreatedAt = DateTime.UtcNow,
|
|
LevelBracketMin = bracketMin,
|
|
LevelBracketMax = bracketMax,
|
|
CreatorLevel = playerLevel,
|
|
CreatorCharacterId = session.CharacterId,
|
|
CreatorName = session.Character.Name,
|
|
LayoutV2 = layoutV2 // Store V2 layout for visual tile data
|
|
};
|
|
|
|
_dungeons[dungeonId] = instance;
|
|
|
|
// Track in Redis
|
|
_ = TrackDungeonCreatedAsync(instance);
|
|
|
|
_log.LogInformation("Player {Name} (Level {Level}) created new dungeon {Id} (tier {Tier}, bracket {Min}-{Max})",
|
|
session.Character.Name, playerLevel, dungeonId, tier, bracketMin, bracketMax);
|
|
}
|
|
|
|
// Update last activity
|
|
instance.LastPlayerActivity = DateTime.UtcNow;
|
|
|
|
var layout2 = instance.Simulation.Layout;
|
|
|
|
// Add player to dungeon
|
|
var spawnPos = layout2.Rooms[0]; // Entrance room
|
|
|
|
// Load equipped items for stat calculations
|
|
List<DungeonCharacterItem> equippedCharacterItems;
|
|
DungeonCharacterCombatStats combatStats;
|
|
|
|
using (var scope = _scopeFactory.CreateScope())
|
|
{
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
equippedCharacterItems = await db.Set<DungeonCharacterItem>()
|
|
.Include(i => i.ItemDefinition)
|
|
.Include(i => i.CraftedItem)
|
|
.Where(i => i.CharacterId == session.CharacterId && i.IsEquipped)
|
|
.ToListAsync(ct);
|
|
|
|
// Calculate combat stats with equipment bonuses (including crafted)
|
|
combatStats = DungeonCharacterStats.GetCombatStats(session.Character, equippedCharacterItems);
|
|
}
|
|
|
|
var player = new PlayerInstance
|
|
{
|
|
CharacterId = session.CharacterId,
|
|
CharacterName = session.Character.Name,
|
|
X = spawnPos.CenterX * 32 + Random.Shared.Next(-20, 20),
|
|
Y = spawnPos.CenterY * 32 + Random.Shared.Next(-20, 20),
|
|
Health = Math.Min(session.Character.CurrentHealth, combatStats.MaxHealth),
|
|
MaxHealth = combatStats.MaxHealth,
|
|
Mana = Math.Min(session.Character.CurrentMana, combatStats.MaxMana),
|
|
MaxMana = combatStats.MaxMana,
|
|
Stamina = combatStats.MaxStamina,
|
|
MaxStamina = combatStats.MaxStamina,
|
|
MoveSpeed = combatStats.MoveSpeed,
|
|
AttackSpeed = combatStats.AttackSpeed,
|
|
Strength = combatStats.Strength,
|
|
Intelligence = combatStats.Intelligence,
|
|
Wisdom = combatStats.Wisdom,
|
|
Endurance = combatStats.Endurance,
|
|
Dexterity = combatStats.Dexterity,
|
|
Armor = combatStats.Armor
|
|
};
|
|
|
|
instance.Simulation.Players[session.CharacterId] = player;
|
|
|
|
// Update session state
|
|
session.State = PlayerState.InDungeon;
|
|
session.CurrentDungeonId = dungeonId;
|
|
session.PlayerInstance = player;
|
|
|
|
// Build visual tile data if V2 layout available
|
|
object? tileSheets = null;
|
|
object? visualTiles = null;
|
|
object? placedObjects = null;
|
|
|
|
_log.LogInformation("LayoutV2 is null: {IsNull}, TileDetails count: {Count}",
|
|
instance.LayoutV2 == null, instance.LayoutV2?.TileDetails?.Count ?? 0);
|
|
|
|
if (instance.LayoutV2 != null && instance.LayoutV2.TileDetails.Count > 0)
|
|
{
|
|
// Materialize to arrays for JSON serialization
|
|
tileSheets = instance.LayoutV2.TileMapSheets.Select(s => new
|
|
{
|
|
id = s.Id,
|
|
path = s.CdnPath,
|
|
tileW = s.TileWidth,
|
|
tileH = s.TileHeight,
|
|
sheetW = s.SheetWidth,
|
|
sheetH = s.SheetHeight,
|
|
cols = s.Columns
|
|
}).ToArray();
|
|
|
|
visualTiles = instance.LayoutV2.TileDetails.Select(t => new
|
|
{
|
|
x = t.X,
|
|
y = t.Y,
|
|
tid = t.TileDefinitionId,
|
|
sid = t.SheetId,
|
|
frame = t.FrameIndex,
|
|
l = t.Layer,
|
|
r = t.Rotation,
|
|
fx = t.FlipX,
|
|
fy = t.FlipY
|
|
}).ToArray();
|
|
|
|
// V3: Include placed objects (decorations, containers, traps)
|
|
if (instance.LayoutV2.Objects?.Count > 0)
|
|
{
|
|
placedObjects = instance.LayoutV2.Objects.Select(o => new
|
|
{
|
|
x = o.X,
|
|
y = o.Y,
|
|
id = o.ObjectTemplateId,
|
|
name = o.Name,
|
|
type = o.Type,
|
|
sheetId = o.SpriteSheetId,
|
|
frame = o.FrameIndex,
|
|
blocks = o.BlocksMovement,
|
|
interact = o.IsInteractable,
|
|
trap = o.IsTrap,
|
|
damage = o.TrapDamage,
|
|
loot = o.LootTableId
|
|
}).ToArray();
|
|
}
|
|
|
|
_log.LogInformation("Sending {SheetCount} sheets, {TileCount} visual tiles, {ObjectCount} objects to client",
|
|
instance.LayoutV2.TileMapSheets.Count, instance.LayoutV2.TileDetails.Count, instance.LayoutV2.Objects?.Count ?? 0);
|
|
}
|
|
|
|
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new
|
|
{
|
|
ok = true,
|
|
dungeonId = dungeonId.ToString(),
|
|
tier = instance.Tier,
|
|
seed = instance.Seed,
|
|
width = layout2.Width,
|
|
height = layout2.Height,
|
|
tilesRLE = layout2.SerializeTilesRLE(),
|
|
spawn = new { x = player.X, y = player.Y },
|
|
players = instance.Simulation.Players.Values.Select(p => new
|
|
{
|
|
id = p.CharacterId,
|
|
name = p.CharacterName,
|
|
x = p.X,
|
|
y = p.Y
|
|
}),
|
|
mobs = instance.Simulation.Mobs.Values.Select(m => new
|
|
{
|
|
id = m.Id,
|
|
name = m.Name,
|
|
x = m.X,
|
|
y = m.Y,
|
|
health = m.Health,
|
|
maxHealth = m.MaxHealth
|
|
}),
|
|
chests = instance.Simulation.Chests.Values.Select(c => new
|
|
{
|
|
id = c.Id,
|
|
x = c.X,
|
|
y = c.Y,
|
|
type = c.Type.ToString().ToLower(),
|
|
opened = c.IsOpened
|
|
}),
|
|
portals = instance.Simulation.Portals.Values.Where(p => p.IsActive).Select(p => new
|
|
{
|
|
id = p.Id,
|
|
x = p.X,
|
|
y = p.Y,
|
|
type = p.Type.ToString().ToLower()
|
|
}),
|
|
// V3 visual tile data
|
|
tileSheets,
|
|
visualTiles,
|
|
placedObjects
|
|
}, ct);
|
|
}
|
|
|
|
private async Task HandleDungeonLeave(IConnection connection, DungeonPlayerSession session, CancellationToken ct)
|
|
{
|
|
if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue)
|
|
{
|
|
return;
|
|
}
|
|
|
|
await RemoveFromDungeonAsync(session, false, ct);
|
|
|
|
await SendAsync(connection, DungeonOpCodes.HUB_STATE, GetHubState(session.Character), ct);
|
|
}
|
|
|
|
private void HandleInputMove(DungeonPlayerSession session, ReadOnlyMemory<byte> payload)
|
|
{
|
|
if (session.PlayerInstance == null) return;
|
|
|
|
var input = _ser.Deserialize<MoveInput>(payload);
|
|
session.PlayerInstance.InputX = input.Dx;
|
|
session.PlayerInstance.InputY = input.Dy;
|
|
session.PlayerInstance.Rotation = input.AimAngle;
|
|
}
|
|
|
|
private void HandleInputAttack(DungeonPlayerSession session, ReadOnlyMemory<byte> payload)
|
|
{
|
|
if (session.PlayerInstance == null) return;
|
|
if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue) return;
|
|
if (!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return;
|
|
|
|
var input = _ser.Deserialize<AttackInput>(payload);
|
|
var player = session.PlayerInstance;
|
|
|
|
// Find nearest mob in attack direction (within attack range and angle tolerance)
|
|
const float attackRange = 60f;
|
|
const float angleToleranceRad = 0.8f; // ~45 degrees
|
|
|
|
MobInstance? bestTarget = null;
|
|
float bestDist = float.MaxValue;
|
|
|
|
foreach (var mob in dungeon.Simulation.Mobs.Values.Where(m => m.IsAlive))
|
|
{
|
|
float dx = mob.X - player.X;
|
|
float dy = mob.Y - player.Y;
|
|
float dist = MathF.Sqrt(dx * dx + dy * dy);
|
|
|
|
if (dist > attackRange) continue;
|
|
|
|
float angleToMob = MathF.Atan2(dy, dx);
|
|
float angleDiff = MathF.Abs(NormalizeAngle(angleToMob - input.AimAngle));
|
|
|
|
if (angleDiff <= angleToleranceRad && dist < bestDist)
|
|
{
|
|
bestDist = dist;
|
|
bestTarget = mob;
|
|
}
|
|
}
|
|
|
|
if (bestTarget != null)
|
|
{
|
|
player.AttackTargetId = (ulong)bestTarget.Id;
|
|
player.WantsToAttack = true;
|
|
}
|
|
}
|
|
|
|
private static float NormalizeAngle(float angle)
|
|
{
|
|
while (angle > MathF.PI) angle -= 2 * MathF.PI;
|
|
while (angle < -MathF.PI) angle += 2 * MathF.PI;
|
|
return angle;
|
|
}
|
|
|
|
private void HandleInputPickup(DungeonPlayerSession session, ReadOnlyMemory<byte> payload)
|
|
{
|
|
if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue) return;
|
|
if (!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return;
|
|
|
|
var input = _ser.Deserialize<PickupInput>(payload);
|
|
|
|
if (dungeon.Simulation.DroppedItems.TryRemove((int)input.ItemId, out var item))
|
|
{
|
|
// TODO: Add to player inventory
|
|
_log.LogDebug("Player {Name} picked up item {ItemId}", session.Character.Name, item.ItemDefinitionId);
|
|
}
|
|
}
|
|
|
|
private void HandleInputChest(DungeonPlayerSession session, ReadOnlyMemory<byte> payload)
|
|
{
|
|
if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue) return;
|
|
if (!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return;
|
|
|
|
var input = _ser.Deserialize<ChestInput>(payload);
|
|
|
|
if (dungeon.Simulation.Chests.TryGetValue((int)input.ChestId, out var chest) && !chest.IsOpened)
|
|
{
|
|
chest.IsOpened = true;
|
|
// TODO: Generate loot
|
|
_log.LogDebug("Player {Name} opened chest {ChestId}", session.Character.Name, chest.Id);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Handle projectile firing - validates weapon, consumes ammunition, creates projectile
|
|
/// </summary>
|
|
private async Task HandleFireProjectile(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
if (session.PlayerInstance == null) return;
|
|
if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue) return;
|
|
if (!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return;
|
|
|
|
var input = _ser.Deserialize<FireProjectileInput>(payload);
|
|
var player = session.PlayerInstance;
|
|
|
|
// Normalize direction vector
|
|
float magnitude = MathF.Sqrt(input.DirectionX * input.DirectionX + input.DirectionY * input.DirectionY);
|
|
if (magnitude < 0.01f) return; // Invalid direction
|
|
|
|
float dirX = input.DirectionX / magnitude;
|
|
float dirY = input.DirectionY / magnitude;
|
|
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
// Get equipped weapon using new equipment system
|
|
var weaponItem = await db.DungeonCharacterItems
|
|
.Include(i => i.ItemDefinition)
|
|
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId
|
|
&& i.IsEquipped
|
|
&& i.EquipSlot == DungeonEquipmentSlot.MainHand, ct);
|
|
|
|
if (weaponItem?.ItemDefinition == null) return;
|
|
var weapon = weaponItem.ItemDefinition;
|
|
|
|
// Handle throwable weapons (consume from inventory)
|
|
if (weapon.IsThrowable)
|
|
{
|
|
await HandleThrowableProjectile(session, dungeon, weapon, dirX, dirY, ct);
|
|
return;
|
|
}
|
|
|
|
// Handle ranged weapons (require ammunition)
|
|
if (!weapon.RequiresAmmunition || weapon.ProjectileSpeed <= 0) return;
|
|
|
|
// Get ammunition from quiver
|
|
var ammo = await ConsumeAmmunitionFromQuiver(session, weapon.AmmunitionType, db, ct);
|
|
if (ammo == null)
|
|
{
|
|
// No ammo available - could send error message to client
|
|
_log.LogDebug("Player {Name} tried to fire {Weapon} but has no {AmmoType} ammunition",
|
|
session.Character.Name, weapon.Name, weapon.AmmunitionType);
|
|
return;
|
|
}
|
|
|
|
// Calculate damage (STR 30% + DEX 70%)
|
|
int weaponDamage = Random.Shared.Next(weapon.MinDamage, weapon.MaxDamage + 1);
|
|
int ammoDamage = Random.Shared.Next(ammo.MinDamage, ammo.MaxDamage + 1);
|
|
int baseDamage = weaponDamage + ammoDamage;
|
|
|
|
float statModifier = (session.Character.Strength * 0.3f + session.Character.Dexterity * 0.7f);
|
|
float statBonus = baseDamage * (statModifier / 100f);
|
|
int totalDamage = (int)(baseDamage + statBonus);
|
|
|
|
// Debug logging disabled
|
|
// Console.WriteLine($"[HandleFireProjectile] Weapon: {weapon.Name} ({weapon.MinDamage}-{weapon.MaxDamage}), Ammo: {ammo.Name} ({ammo.MinDamage}-{ammo.MaxDamage}), Total: {totalDamage}");
|
|
|
|
// Create projectile
|
|
var projectile = new ProjectileInstance
|
|
{
|
|
Id = dungeon.Simulation.GetNextProjectileId(),
|
|
SourceType = ProjectileSource.Player,
|
|
SourcePlayerId = session.CharacterId,
|
|
X = player.X,
|
|
Y = player.Y,
|
|
VelocityX = dirX * weapon.ProjectileSpeed,
|
|
VelocityY = dirY * weapon.ProjectileSpeed,
|
|
Speed = weapon.ProjectileSpeed,
|
|
Damage = totalDamage,
|
|
DamageTypeKey = weapon.DamageTypeKey,
|
|
MaxRange = weapon.ProjectileRange,
|
|
DistanceTraveled = 0,
|
|
AmmunitionItemDefinitionId = ammo.Id,
|
|
RecoveryChance = ammo.ArrowRecoveryChance,
|
|
CanHitMobs = true,
|
|
CanHitPlayers = false, // TODO: PvP support
|
|
SpriteKey = ammo.SpritePath ?? "projectile_arrow",
|
|
IsLinear = ammo.IsLinearProjectile,
|
|
FrontX = ammo.ProjectileFrontX,
|
|
FrontY = ammo.ProjectileFrontY,
|
|
BackX = ammo.ProjectileBackX,
|
|
BackY = ammo.ProjectileBackY
|
|
};
|
|
|
|
dungeon.Simulation.Projectiles.TryAdd(projectile.Id, projectile);
|
|
// Debug logging disabled
|
|
// Console.WriteLine($"[HandleFireProjectile] Added projectile {projectile.Id} to simulation. Total projectiles: {dungeon.Simulation.Projectiles.Count}");
|
|
|
|
// Broadcast projectile spawned
|
|
// Console.WriteLine($"[HandleFireProjectile] Broadcasting projectile {projectile.Id} to {dungeon.Simulation.Players.Count} players");
|
|
foreach (var dungeonPlayer in dungeon.Simulation.Players.Values)
|
|
{
|
|
// Console.WriteLine($"[HandleFireProjectile] Checking player CharId={dungeonPlayer.CharacterId}");
|
|
var playerSession = _playerSessions.Values.FirstOrDefault(p => p.CharacterId == dungeonPlayer.CharacterId);
|
|
if (playerSession != null)
|
|
{
|
|
// Console.WriteLine($"[HandleFireProjectile] Sending EVENT_PROJECTILE_SPAWNED (504) to player {playerSession.Character.Name} (CharId={playerSession.CharacterId})");
|
|
try
|
|
{
|
|
await SendAsync(playerSession.Connection, DungeonOpCodes.EVENT_PROJECTILE_SPAWNED, new
|
|
{
|
|
id = projectile.Id,
|
|
sourceType = "player",
|
|
sourceId = session.CharacterId,
|
|
x = projectile.X,
|
|
y = projectile.Y,
|
|
vx = projectile.VelocityX,
|
|
vy = projectile.VelocityY,
|
|
sprite = projectile.SpriteKey,
|
|
isLinear = projectile.IsLinear,
|
|
frontX = projectile.FrontX,
|
|
frontY = projectile.FrontY,
|
|
backX = projectile.BackX,
|
|
backY = projectile.BackY
|
|
}, ct);
|
|
// Console.WriteLine($"[HandleFireProjectile] Successfully sent EVENT_PROJECTILE_SPAWNED to {playerSession.Character.Name}");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"[HandleFireProjectile] ERROR sending EVENT_PROJECTILE_SPAWNED to {playerSession.Character.Name}: {ex.Message}");
|
|
}
|
|
}
|
|
// else
|
|
// {
|
|
// Console.WriteLine($"[HandleFireProjectile] WARNING: No session found for player CharId={dungeonPlayer.CharacterId}");
|
|
// }
|
|
}
|
|
|
|
_log.LogDebug("Player {Name} fired projectile with {Weapon} using {Ammo} for {Damage} damage",
|
|
session.Character.Name, weapon.Name, ammo.Name, totalDamage);
|
|
}
|
|
|
|
private async Task HandleThrowableProjectile(DungeonPlayerSession session, DungeonInstance dungeon, DungeonItemDefinition weapon, float dirX, float dirY, CancellationToken ct)
|
|
{
|
|
// Throwables consume from inventory
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
var throwableStack = await db.DungeonCharacterItems
|
|
.Include(i => i.CraftedItem)
|
|
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId &&
|
|
i.ItemDefinitionId == weapon.Id &&
|
|
i.Quantity > 0, ct);
|
|
|
|
if (throwableStack == null) return;
|
|
|
|
// Consume one
|
|
throwableStack.Quantity--;
|
|
if (throwableStack.Quantity <= 0)
|
|
{
|
|
db.DungeonCharacterItems.Remove(throwableStack);
|
|
}
|
|
await db.SaveChangesAsync(ct);
|
|
|
|
// Calculate damage (include crafted item rolled bonuses)
|
|
int totalMinDamage = weapon.MinDamage + (throwableStack.CraftedItem?.RolledBonusMinDamage ?? 0);
|
|
int totalMaxDamage = weapon.MaxDamage + (throwableStack.CraftedItem?.RolledBonusMaxDamage ?? 0);
|
|
int baseDamage = Random.Shared.Next(totalMinDamage, totalMaxDamage + 1);
|
|
float statModifier = (session.Character.Strength * 0.3f + session.Character.Dexterity * 0.7f);
|
|
float statBonus = baseDamage * (statModifier / 100f);
|
|
int totalDamage = (int)(baseDamage + statBonus);
|
|
|
|
// Create projectile
|
|
var projectile = new ProjectileInstance
|
|
{
|
|
Id = dungeon.Simulation.GetNextProjectileId(),
|
|
SourceType = ProjectileSource.Player,
|
|
SourcePlayerId = session.CharacterId,
|
|
X = session.PlayerInstance!.X,
|
|
Y = session.PlayerInstance.Y,
|
|
VelocityX = dirX * weapon.ProjectileSpeed,
|
|
VelocityY = dirY * weapon.ProjectileSpeed,
|
|
Speed = weapon.ProjectileSpeed,
|
|
Damage = totalDamage,
|
|
DamageTypeKey = weapon.DamageTypeKey,
|
|
MaxRange = weapon.ProjectileRange,
|
|
DistanceTraveled = 0,
|
|
AmmunitionItemDefinitionId = weapon.Id,
|
|
RecoveryChance = weapon.ArrowRecoveryChance,
|
|
CanHitMobs = true,
|
|
CanHitPlayers = false,
|
|
SpriteKey = weapon.SpritePath ?? "projectile_knife",
|
|
IsLinear = weapon.IsLinearProjectile,
|
|
FrontX = weapon.ProjectileFrontX,
|
|
FrontY = weapon.ProjectileFrontY,
|
|
BackX = weapon.ProjectileBackX,
|
|
BackY = weapon.ProjectileBackY
|
|
};
|
|
|
|
dungeon.Simulation.Projectiles.TryAdd(projectile.Id, projectile);
|
|
|
|
Console.WriteLine($"[HandleThrowableProjectile] Broadcasting projectile {projectile.Id} to {dungeon.Simulation.Players.Count} players");
|
|
foreach (var dungeonPlayer in dungeon.Simulation.Players.Values)
|
|
{
|
|
var playerSession = _playerSessions.Values.FirstOrDefault(p => p.CharacterId == dungeonPlayer.CharacterId);
|
|
if (playerSession != null)
|
|
{
|
|
Console.WriteLine($"[HandleThrowableProjectile] Sending EVENT_PROJECTILE_SPAWNED (504) to player {playerSession.Character.Name}");
|
|
try
|
|
{
|
|
await SendAsync(playerSession.Connection, DungeonOpCodes.EVENT_PROJECTILE_SPAWNED, new
|
|
{
|
|
id = projectile.Id,
|
|
sourceType = "player",
|
|
sourceId = session.CharacterId,
|
|
x = projectile.X,
|
|
y = projectile.Y,
|
|
vx = projectile.VelocityX,
|
|
vy = projectile.VelocityY,
|
|
sprite = projectile.SpriteKey,
|
|
isLinear = projectile.IsLinear,
|
|
frontX = projectile.FrontX,
|
|
frontY = projectile.FrontY,
|
|
backX = projectile.BackX,
|
|
backY = projectile.BackY
|
|
}, ct);
|
|
Console.WriteLine($"[HandleThrowableProjectile] Successfully sent EVENT_PROJECTILE_SPAWNED to {playerSession.Character.Name}");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"[HandleThrowableProjectile] ERROR sending EVENT_PROJECTILE_SPAWNED to {playerSession.Character.Name}: {ex.Message}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task<DungeonItemDefinition?> ConsumeAmmunitionFromQuiver(DungeonPlayerSession session, string? ammoType, GameDbContext db, CancellationToken ct)
|
|
{
|
|
if (string.IsNullOrEmpty(ammoType)) return null;
|
|
|
|
// Get equipped quiver using new equipment system
|
|
var quiverItem = await db.DungeonCharacterItems
|
|
.Include(i => i.ItemDefinition)
|
|
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId
|
|
&& i.IsEquipped
|
|
&& i.EquipSlot == DungeonEquipmentSlot.Quiver, ct);
|
|
|
|
if (quiverItem?.ItemDefinition == null) return null;
|
|
|
|
// Check if it's a quiver container
|
|
if (quiverItem.ItemDefinition.QuiverCapacity > 0)
|
|
{
|
|
// Quiver container - find ammunition in slots
|
|
var ammoSlot = await db.DungeonQuiverAmmoSlots
|
|
.Include(s => s.ItemDefinition)
|
|
.Where(s => s.QuiverCharacterItemId == quiverItem.Id && s.Quantity > 0)
|
|
.OrderBy(s => s.SlotIndex)
|
|
.FirstOrDefaultAsync(ct);
|
|
|
|
if (ammoSlot?.ItemDefinition == null) return null;
|
|
|
|
// Consume one
|
|
ammoSlot.Quantity--;
|
|
await db.SaveChangesAsync(ct);
|
|
|
|
return ammoSlot.ItemDefinition;
|
|
}
|
|
else
|
|
{
|
|
// Direct ammo equip (stack of arrows in quiver slot)
|
|
if (quiverItem.Quantity <= 0) return null;
|
|
|
|
quiverItem.Quantity--;
|
|
if (quiverItem.Quantity <= 0)
|
|
{
|
|
// Unequip when empty using new equipment system
|
|
quiverItem.IsEquipped = false;
|
|
quiverItem.EquipSlot = null;
|
|
db.DungeonCharacterItems.Remove(quiverItem);
|
|
}
|
|
await db.SaveChangesAsync(ct);
|
|
|
|
return quiverItem.ItemDefinition;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Handle portal use - instant extraction when player clicks/walks into portal
|
|
/// </summary>
|
|
private async Task HandlePortalUse(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue) return;
|
|
if (!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return;
|
|
|
|
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
|
|
var request = System.Text.Json.JsonSerializer.Deserialize<PortalUseRequest>(json);
|
|
if (request == null) return;
|
|
|
|
// Find the portal
|
|
if (!dungeon.Simulation.Portals.TryGetValue(request.PortalId, out var portal))
|
|
{
|
|
_log.LogWarning("Player {Name} tried to use non-existent portal {Id}", session.Character.Name, request.PortalId);
|
|
return;
|
|
}
|
|
|
|
if (!portal.IsActive)
|
|
{
|
|
_log.LogWarning("Player {Name} tried to use inactive portal {Id}", session.Character.Name, request.PortalId);
|
|
return;
|
|
}
|
|
|
|
var player = session.PlayerInstance;
|
|
if (player == null) return;
|
|
|
|
// Check distance to portal (must be within 64 pixels)
|
|
float dx = player.X - portal.X;
|
|
float dy = player.Y - portal.Y;
|
|
float dist = MathF.Sqrt(dx * dx + dy * dy);
|
|
|
|
if (dist > 64)
|
|
{
|
|
_log.LogDebug("Player {Name} too far from portal ({Dist})", session.Character.Name, dist);
|
|
return;
|
|
}
|
|
|
|
_log.LogInformation("Player {Name} using exit portal", session.Character.Name);
|
|
|
|
// Send portal used confirmation
|
|
await SendAsync(connection, DungeonOpCodes.PORTAL_USED, new
|
|
{
|
|
portalId = portal.Id,
|
|
type = portal.Type.ToString().ToLower()
|
|
}, ct);
|
|
|
|
// Extract player (keep loot, save progress)
|
|
await RemoveFromDungeonAsync(session, true, ct);
|
|
|
|
// Return to hub
|
|
await SendAsync(connection, DungeonOpCodes.HUB_STATE, GetHubState(session.Character), ct);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Handle hotbar slot assignment - links a hotbar slot to an inventory slot
|
|
/// </summary>
|
|
private async Task HandleHotbarAssign(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
|
|
var request = System.Text.Json.JsonSerializer.Deserialize<HotbarAssignRequest>(json);
|
|
if (request == null) return;
|
|
|
|
// Validate slots
|
|
if (request.HotbarSlot < 0 || request.HotbarSlot >= 8) return;
|
|
if (request.InventorySlot < 0 || request.InventorySlot >= 30) return;
|
|
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
// Check if the inventory slot has a valid item (consumable or equipment)
|
|
var invItem = await db.Set<DungeonCharacterItem>()
|
|
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId &&
|
|
i.SlotIndex == request.InventorySlot &&
|
|
!i.IsEquipped, ct);
|
|
|
|
if (invItem != null)
|
|
{
|
|
var itemDef = await db.Set<DungeonItemDefinition>()
|
|
.FirstOrDefaultAsync(d => d.Id == invItem.ItemDefinitionId, ct);
|
|
|
|
// Only allow consumables and equipment in hotbar
|
|
if (itemDef == null || (itemDef.Type != ItemType.Consumable &&
|
|
itemDef.Type != ItemType.Weapon &&
|
|
itemDef.Type != ItemType.Armor &&
|
|
itemDef.Type != ItemType.Accessory))
|
|
{
|
|
_log.LogDebug("Cannot assign item type {Type} to hotbar", itemDef?.Type);
|
|
return;
|
|
}
|
|
}
|
|
|
|
// Remove the same inventory slot from any other hotbar slot (prevent duplicates)
|
|
var duplicateEntries = await db.Set<DungeonBeltItem>()
|
|
.Where(b => b.CharacterId == session.CharacterId &&
|
|
b.InventorySlotIndex == request.InventorySlot &&
|
|
b.SlotIndex != request.HotbarSlot)
|
|
.ToListAsync(ct);
|
|
|
|
if (duplicateEntries.Any())
|
|
{
|
|
db.Set<DungeonBeltItem>().RemoveRange(duplicateEntries);
|
|
}
|
|
|
|
// Find existing hotbar entry for this slot
|
|
var existingEntry = await db.Set<DungeonBeltItem>()
|
|
.FirstOrDefaultAsync(b => b.CharacterId == session.CharacterId &&
|
|
b.SlotIndex == request.HotbarSlot, ct);
|
|
|
|
if (existingEntry != null)
|
|
{
|
|
// Update existing
|
|
existingEntry.InventorySlotIndex = request.InventorySlot;
|
|
}
|
|
else
|
|
{
|
|
// Create new
|
|
var newEntry = new DungeonBeltItem
|
|
{
|
|
CharacterId = session.CharacterId,
|
|
SlotIndex = request.HotbarSlot,
|
|
InventorySlotIndex = request.InventorySlot
|
|
};
|
|
db.Set<DungeonBeltItem>().Add(newEntry);
|
|
}
|
|
|
|
await db.SaveChangesAsync(ct);
|
|
|
|
// Send updated inventory state (includes hotbar)
|
|
await HandleInventoryRequest(connection, session, ct);
|
|
|
|
_log.LogDebug("Player {Name} assigned inventory slot {InvSlot} to hotbar slot {HotbarSlot}",
|
|
session.Character.Name, request.InventorySlot, request.HotbarSlot);
|
|
}
|
|
|
|
private void TickAll(object? state)
|
|
{
|
|
_currentTick++;
|
|
|
|
// Process pending broadcasts
|
|
ProcessPendingBroadcasts();
|
|
|
|
// Update active connection count for admin display
|
|
_broadcastService.SetActiveConnectionCount(_playerSessions.Count);
|
|
|
|
foreach (var (dungeonId, instance) in _dungeons)
|
|
{
|
|
try
|
|
{
|
|
var result = instance.Simulation.Tick(_currentTick);
|
|
|
|
// Process death events for loot generation
|
|
if (result.DeathEvents != null)
|
|
{
|
|
foreach (var death in result.DeathEvents)
|
|
{
|
|
if (death.EntityType == EntityType.Mob && death.KillerType == EntityType.Player)
|
|
{
|
|
_ = ProcessMobDeathLootAsync(instance, death);
|
|
|
|
if (instance.Simulation.Mobs.TryGetValue(death.EntityId, out var killedMob))
|
|
{
|
|
if (killedMob.Type == MobType.Boss)
|
|
{
|
|
instance.BossKilled = true;
|
|
_log.LogInformation("Boss killed in dungeon {Id}! Dungeon is now cleared.", dungeonId);
|
|
}
|
|
}
|
|
}
|
|
else if (death.EntityType == EntityType.Player)
|
|
{
|
|
_ = ProcessPlayerDeathLootTransferAsync(instance, death);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Get players in this dungeon
|
|
var playersInDungeon = _playerSessions.Values
|
|
.Where(s => s.CurrentDungeonId == dungeonId && s.State == PlayerState.InDungeon)
|
|
.ToList();
|
|
|
|
// ==================== TILE UPDATE BROADCASTING ====================
|
|
// Check for pending tile updates from admin editing
|
|
if (instance.HasPendingTileUpdates && instance.LayoutV2 != null && playersInDungeon.Count > 0)
|
|
{
|
|
instance.HasPendingTileUpdates = false;
|
|
|
|
// Get changed tiles if we're tracking them, otherwise send all
|
|
object[] tilesToSend;
|
|
object[]? walkableUpdates = null;
|
|
|
|
if (_changedTiles.TryRemove(dungeonId, out var changes) && changes.Count > 0)
|
|
{
|
|
// Differential update - only send changed tiles
|
|
var changedList = changes.ToList();
|
|
var tileDetails = instance.LayoutV2.TileDetails;
|
|
|
|
tilesToSend = changedList
|
|
.Select(c => {
|
|
var tile = tileDetails.FirstOrDefault(t => t.X == c.x && t.Y == c.y && t.Layer == c.layer);
|
|
if (tile != null)
|
|
{
|
|
return new
|
|
{
|
|
x = tile.X,
|
|
y = tile.Y,
|
|
sid = tile.SheetId,
|
|
frame = tile.FrameIndex,
|
|
l = tile.Layer,
|
|
r = tile.Rotation,
|
|
fx = tile.FlipX,
|
|
fy = tile.FlipY
|
|
};
|
|
}
|
|
// Tile was removed - send with sid=0 to indicate removal
|
|
return new
|
|
{
|
|
x = c.x,
|
|
y = c.y,
|
|
sid = 0,
|
|
frame = 0,
|
|
l = c.layer,
|
|
r = 0,
|
|
fx = false,
|
|
fy = false
|
|
};
|
|
})
|
|
.Cast<object>()
|
|
.ToArray();
|
|
|
|
// Also send walkable updates for changed positions
|
|
var layout = instance.LayoutV2;
|
|
walkableUpdates = changedList
|
|
.Select(c => c.layer == 0 ? new { x = c.x, y = c.y, w = layout.Walkable[c.x, c.y] } : null)
|
|
.Where(w => w != null)
|
|
.Distinct()
|
|
.Cast<object>()
|
|
.ToArray();
|
|
|
|
_log.LogInformation("Broadcasting {Count} tile updates to {PlayerCount} players in dungeon {Id}",
|
|
tilesToSend.Length, playersInDungeon.Count, dungeonId);
|
|
}
|
|
else
|
|
{
|
|
// Full update - send all tiles (fallback, shouldn't happen often)
|
|
tilesToSend = instance.LayoutV2.TileDetails.Select(t => new {
|
|
x = t.X,
|
|
y = t.Y,
|
|
sid = t.SheetId,
|
|
frame = t.FrameIndex,
|
|
l = t.Layer,
|
|
r = t.Rotation,
|
|
fx = t.FlipX,
|
|
fy = t.FlipY
|
|
}).Cast<object>().ToArray();
|
|
|
|
_log.LogInformation("Broadcasting full tile update ({Count} tiles) to {PlayerCount} players in dungeon {Id}",
|
|
tilesToSend.Length, playersInDungeon.Count, dungeonId);
|
|
}
|
|
|
|
// Broadcast to all players in this dungeon
|
|
var tileUpdate = new
|
|
{
|
|
tiles = tilesToSend,
|
|
walkable = walkableUpdates
|
|
};
|
|
|
|
foreach (var session in playersInDungeon)
|
|
{
|
|
_ = SendAsync(session.Connection, DungeonOpCodes.DUNGEON_TILE_UPDATE, tileUpdate, CancellationToken.None);
|
|
}
|
|
}
|
|
// ==================== END TILE UPDATE BROADCASTING ====================
|
|
|
|
// Check if dungeon was just cleared
|
|
if (result.Phase == DungeonPhase.Cleared && !instance.ClearedHandled)
|
|
{
|
|
instance.ClearedHandled = true;
|
|
foreach (var session in playersInDungeon)
|
|
{
|
|
_ = HandleDungeonClearedAsync(session);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
foreach (var session in playersInDungeon)
|
|
{
|
|
// Check escape completion (5 seconds = 100 ticks)
|
|
if (session.IsEscaping && _currentTick - session.EscapeStartTick >= 400)
|
|
{
|
|
_ = CompleteEscapeAsync(session);
|
|
continue;
|
|
}
|
|
|
|
// Check if player died
|
|
if (session.PlayerInstance != null && !session.PlayerInstance.IsAlive)
|
|
{
|
|
_ = HandlePlayerDeathAsync(session);
|
|
continue;
|
|
}
|
|
|
|
_ = SendDungeonStateAsync(session, result);
|
|
}
|
|
|
|
// Update last activity if players present
|
|
if (playersInDungeon.Count > 0)
|
|
{
|
|
instance.LastPlayerActivity = DateTime.UtcNow;
|
|
}
|
|
|
|
// Handle empty dungeon logic
|
|
if (playersInDungeon.Count == 0)
|
|
{
|
|
var emptyTime = DateTime.UtcNow - instance.LastPlayerActivity;
|
|
|
|
if (!instance.BossKilled && !instance.IsPersisted && emptyTime.TotalMinutes >= 5)
|
|
{
|
|
_ = PersistDungeonAsync(instance, CancellationToken.None);
|
|
_dungeons.TryRemove(dungeonId, out _);
|
|
_ = TrackDungeonDestroyedAsync(dungeonId);
|
|
_log.LogInformation("Dungeon {Id} persisted after 10 minutes empty", dungeonId);
|
|
}
|
|
else if (instance.BossKilled && emptyTime.TotalMinutes >= 5)
|
|
{
|
|
_dungeons.TryRemove(dungeonId, out _);
|
|
_ = TrackDungeonDestroyedAsync(dungeonId);
|
|
_log.LogInformation("Cleared dungeon {Id} removed after 5 minutes empty", dungeonId);
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_log.LogError(ex, "Error ticking dungeon {DungeonId}", dungeonId);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Process pending server broadcasts and send to all connected players
|
|
/// </summary>
|
|
private void ProcessPendingBroadcasts()
|
|
{
|
|
var broadcasts = _broadcastService.GetPendingBroadcasts();
|
|
if (broadcasts.Count == 0) return;
|
|
|
|
_log.LogInformation("Processing {Count} pending broadcasts, {PlayerCount} players online",
|
|
broadcasts.Count, _playerSessions.Count);
|
|
|
|
foreach (var broadcast in broadcasts)
|
|
{
|
|
// Send to all connected player sessions
|
|
foreach (var session in _playerSessions.Values)
|
|
{
|
|
_log.LogDebug("Sending broadcast to player session {ConnectionId}", session.ConnectionId);
|
|
_ = SendAsync(session.Connection, DungeonOpCodes.SERVER_BROADCAST, new
|
|
{
|
|
message = broadcast.Message,
|
|
type = broadcast.Type
|
|
}, CancellationToken.None);
|
|
}
|
|
|
|
_log.LogInformation("Broadcast sent to {Count} players: [{Type}] {Message}",
|
|
_playerSessions.Count, broadcast.Type, broadcast.Message);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Process loot when a mob dies - stores loot on mob body for player interaction
|
|
/// </summary>
|
|
private async Task ProcessMobDeathLootAsync(DungeonInstance dungeon, DeathEvent death)
|
|
{
|
|
try
|
|
{
|
|
// Find the mob that died (it's still in the dictionary but marked dead)
|
|
if (!dungeon.Simulation.Mobs.TryGetValue(death.EntityId, out var mob))
|
|
return;
|
|
|
|
// Generate loot from the mob's loot tables
|
|
var loot = _lootService.GenerateMobLoot(
|
|
mob.DefinitionId,
|
|
dungeon.Tier,
|
|
1.0f
|
|
);
|
|
|
|
// Collect all items (normal loot + carried player loot)
|
|
var allItems = new List<LootDrop>(loot);
|
|
long totalGold = 0;
|
|
|
|
// Add any carried player loot from player kills
|
|
if (mob.HasCarriedLoot)
|
|
{
|
|
_log.LogInformation("Mob {MobName} was carrying loot from {Count} player kills",
|
|
mob.Name, mob.CarriedPlayerLoot.Count);
|
|
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
foreach (var carried in mob.CarriedPlayerLoot)
|
|
{
|
|
totalGold += carried.Gold;
|
|
|
|
// Convert carried items to LootDrops
|
|
foreach (var item in carried.Items)
|
|
{
|
|
var itemDef = await db.Set<DungeonItemDefinition>()
|
|
.FirstOrDefaultAsync(d => d.Id == item.ItemDefinitionId);
|
|
|
|
if (itemDef != null)
|
|
{
|
|
allItems.Add(new LootDrop
|
|
{
|
|
ItemDefinitionId = item.ItemDefinitionId,
|
|
Item = itemDef,
|
|
Quantity = item.Quantity
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
// Clear the carried loot from the mob
|
|
mob.CarriedPlayerLoot.Clear();
|
|
}
|
|
|
|
// Store loot on the mob body for players to loot manually
|
|
mob.DeathLoot = allItems;
|
|
mob.DeathLootGold = totalGold;
|
|
|
|
// Don't set LootEmptiedAtTick here - let the simulation do it when dungeon is cleared
|
|
// This way corpses stay during combat even if they have no loot
|
|
|
|
_log.LogDebug("Mob {Mob} died with {Count} items and {Gold} gold loot",
|
|
mob.Name, allItems.Count, totalGold);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_log.LogError(ex, "Error processing loot for mob death");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Process player death - transfer inventory and 10% gold to killer
|
|
/// </summary>
|
|
private async Task ProcessPlayerDeathLootTransferAsync(DungeonInstance dungeon, DeathEvent death)
|
|
{
|
|
try
|
|
{
|
|
var victimSession = _playerSessions.Values
|
|
.FirstOrDefault(s => s.CharacterId == (ulong)death.EntityId);
|
|
|
|
if (victimSession == null)
|
|
return;
|
|
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
// Get victim's inventory (non-equipped items only)
|
|
var victimInventory = await db.Set<DungeonCharacterItem>()
|
|
.Include(i => i.ItemDefinition)
|
|
.Where(i => i.CharacterId == victimSession.CharacterId && !i.IsEquipped)
|
|
.ToListAsync();
|
|
|
|
// Calculate gold to transfer (10%)
|
|
var victim = await db.DungeonCharacters.FindAsync(victimSession.CharacterId);
|
|
if (victim == null) return;
|
|
|
|
long goldToTransfer = (long)(victim.Gold * 0.10);
|
|
|
|
// Build the loot package
|
|
var lootItems = victimInventory.Select(i => new CarriedLootItem
|
|
{
|
|
ItemDefinitionId = i.ItemDefinitionId,
|
|
Quantity = i.Quantity
|
|
}).ToList();
|
|
|
|
var carriedLoot = new CarriedLoot
|
|
{
|
|
VictimCharacterId = victimSession.CharacterId,
|
|
VictimName = victim.Name,
|
|
Items = lootItems,
|
|
Gold = goldToTransfer
|
|
};
|
|
|
|
// Remove items from victim's inventory
|
|
db.Set<DungeonCharacterItem>().RemoveRange(victimInventory);
|
|
|
|
// Deduct gold from victim
|
|
victim.Gold -= goldToTransfer;
|
|
|
|
await db.SaveChangesAsync();
|
|
|
|
// Send notification to victim about what they lost
|
|
await SendDeathLootLostNotificationAsync(victimSession, victimInventory, goldToTransfer);
|
|
|
|
_log.LogInformation("Player {Victim} died to {KillerType} {KillerId}. Lost {ItemCount} items and {Gold} gold",
|
|
victim.Name, death.KillerType, death.KillerId, victimInventory.Count, goldToTransfer);
|
|
|
|
// Transfer loot based on killer type
|
|
if (death.KillerType == EntityType.Mob)
|
|
{
|
|
// Mob killed player - mob now carries the loot
|
|
if (dungeon.Simulation.Mobs.TryGetValue(death.KillerId, out var killerMob))
|
|
{
|
|
killerMob.CarriedPlayerLoot.Add(carriedLoot);
|
|
_log.LogInformation("Mob {MobName} is now carrying loot from {Victim}",
|
|
killerMob.Name, victim.Name);
|
|
}
|
|
}
|
|
else if (death.KillerType == EntityType.Player)
|
|
{
|
|
// Player killed player - transfer directly
|
|
var killerSession = _playerSessions.Values
|
|
.FirstOrDefault(s => s.CharacterId == (ulong)death.KillerId);
|
|
|
|
if (killerSession != null)
|
|
{
|
|
await TransferPlayerLootToPlayerAsync(dungeon, killerSession, carriedLoot,
|
|
victimSession.PlayerInstance?.X ?? 0, victimSession.PlayerInstance?.Y ?? 0);
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_log.LogError(ex, "Error processing player death loot transfer");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Transfer carried loot directly to a player (from PvP kill)
|
|
/// </summary>
|
|
private async Task TransferPlayerLootToPlayerAsync(DungeonInstance dungeon, DungeonPlayerSession killer,
|
|
CarriedLoot loot, float x, float y)
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
// Convert carried items to LootDrops
|
|
var lootDrops = new List<LootDrop>();
|
|
foreach (var item in loot.Items)
|
|
{
|
|
var itemDef = await db.Set<DungeonItemDefinition>()
|
|
.FirstOrDefaultAsync(d => d.Id == item.ItemDefinitionId);
|
|
|
|
if (itemDef != null)
|
|
{
|
|
lootDrops.Add(new LootDrop
|
|
{
|
|
ItemDefinitionId = item.ItemDefinitionId,
|
|
Item = itemDef,
|
|
Quantity = item.Quantity
|
|
});
|
|
}
|
|
}
|
|
|
|
// Try to add to killer's inventory
|
|
var (addedItems, overflowItems, overflowGold) = await AddLootToInventoryWithOverflowAsync(
|
|
killer, lootDrops, loot.Gold);
|
|
|
|
if (addedItems.Count > 0)
|
|
{
|
|
await SendLootPopupAsync(killer, addedItems);
|
|
}
|
|
|
|
// Spawn chest for overflow
|
|
if (overflowItems.Count > 0 || overflowGold > 0)
|
|
{
|
|
await SpawnLootChestAsync(dungeon, killer, overflowItems, overflowGold, x, y,
|
|
loot.VictimCharacterId, null);
|
|
}
|
|
|
|
_log.LogInformation("Player {Killer} received loot from killing {Victim}: {Items} items, {Gold} gold",
|
|
killer.Character.Name, loot.VictimName, loot.Items.Count, loot.Gold);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Send notification to victim about what they lost on death
|
|
/// </summary>
|
|
private async Task SendDeathLootLostNotificationAsync(DungeonPlayerSession victim,
|
|
List<DungeonCharacterItem> lostItems, long lostGold)
|
|
{
|
|
var itemsData = lostItems.Select(i => new
|
|
{
|
|
name = i.ItemDefinition?.Name ?? "Unknown",
|
|
quantity = i.Quantity,
|
|
rarity = i.ItemDefinition?.Rarity.ToString() ?? "Common"
|
|
});
|
|
|
|
await SendAsync(victim.Connection, DungeonOpCodes.PLAYER_DEATH_LOOT_LOST, new
|
|
{
|
|
items = itemsData,
|
|
gold = lostGold,
|
|
message = $"You died and lost {lostItems.Count} items and {lostGold} gold!"
|
|
}, CancellationToken.None);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Add loot to inventory, returning what was added and what overflowed
|
|
/// </summary>
|
|
private async Task<(List<LootDrop> added, List<LootDrop> overflow, long overflowGold)>
|
|
AddLootToInventoryWithOverflowAsync(DungeonPlayerSession session, List<LootDrop> loot, long gold)
|
|
{
|
|
var added = new List<LootDrop>();
|
|
var overflow = new List<LootDrop>();
|
|
long overflowGold = 0;
|
|
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
// Get existing inventory items
|
|
var existingItems = await db.Set<DungeonCharacterItem>()
|
|
.Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped)
|
|
.ToListAsync();
|
|
|
|
// Find used slots
|
|
var usedSlots = existingItems.Select(i => i.SlotIndex).ToHashSet();
|
|
|
|
// Find next available slot
|
|
int FindNextSlot()
|
|
{
|
|
for (int i = 0; i < 30; i++)
|
|
{
|
|
if (!usedSlots.Contains(i))
|
|
{
|
|
usedSlots.Add(i);
|
|
return i;
|
|
}
|
|
}
|
|
return -1; // Full
|
|
}
|
|
|
|
foreach (var drop in loot)
|
|
{
|
|
int remainingToAdd = drop.Quantity;
|
|
|
|
// If item is stackable, try to fill existing stacks first
|
|
if (drop.Item.Stackable)
|
|
{
|
|
// Find all existing stacks of this item that have room
|
|
var existingStacks = existingItems
|
|
.Where(i => i.ItemDefinitionId == drop.ItemDefinitionId && i.Quantity < drop.Item.MaxStack)
|
|
.OrderBy(i => i.Quantity) // Fill least-full stacks first
|
|
.ToList();
|
|
|
|
foreach (var stack in existingStacks)
|
|
{
|
|
if (remainingToAdd <= 0) break;
|
|
|
|
int spaceInStack = drop.Item.MaxStack - stack.Quantity;
|
|
int toAdd = Math.Min(remainingToAdd, spaceInStack);
|
|
|
|
if (toAdd > 0)
|
|
{
|
|
stack.Quantity += toAdd;
|
|
remainingToAdd -= toAdd;
|
|
added.Add(new LootDrop
|
|
{
|
|
ItemDefinitionId = drop.ItemDefinitionId,
|
|
Item = drop.Item,
|
|
Quantity = toAdd
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
// If there's still quantity remaining, create new stack(s)
|
|
while (remainingToAdd > 0)
|
|
{
|
|
int nextSlot = FindNextSlot();
|
|
if (nextSlot >= 0)
|
|
{
|
|
// Determine how much to put in this new stack (up to max stack size)
|
|
int quantityForNewStack = drop.Item.Stackable
|
|
? Math.Min(remainingToAdd, drop.Item.MaxStack)
|
|
: remainingToAdd;
|
|
|
|
var newItem = new DungeonCharacterItem
|
|
{
|
|
CharacterId = session.CharacterId,
|
|
ItemDefinitionId = drop.ItemDefinitionId,
|
|
Quantity = quantityForNewStack,
|
|
SlotIndex = nextSlot
|
|
};
|
|
db.Set<DungeonCharacterItem>().Add(newItem);
|
|
existingItems.Add(newItem);
|
|
|
|
added.Add(new LootDrop
|
|
{
|
|
ItemDefinitionId = drop.ItemDefinitionId,
|
|
Item = drop.Item,
|
|
Quantity = quantityForNewStack
|
|
});
|
|
|
|
remainingToAdd -= quantityForNewStack;
|
|
}
|
|
else
|
|
{
|
|
// Inventory full - overflow the rest
|
|
overflow.Add(new LootDrop
|
|
{
|
|
ItemDefinitionId = drop.ItemDefinitionId,
|
|
Item = drop.Item,
|
|
Quantity = remainingToAdd
|
|
});
|
|
remainingToAdd = 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Handle gold
|
|
var character = await db.DungeonCharacters.FindAsync(session.CharacterId);
|
|
if (character != null)
|
|
{
|
|
character.Gold += gold;
|
|
}
|
|
|
|
await db.SaveChangesAsync();
|
|
|
|
return (added, overflow, overflowGold);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Spawn a personal loot chest for overflow items
|
|
/// </summary>
|
|
private async Task SpawnLootChestAsync(DungeonInstance dungeon, DungeonPlayerSession owner,
|
|
List<LootDrop> items, long gold, float x, float y, ulong? victimCharacterId, int? victimMobId)
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
// Create database record for auditing
|
|
var deathChest = new DeathChest
|
|
{
|
|
DungeonInstanceId = dungeon.Id,
|
|
OwnerCharacterId = owner.CharacterId,
|
|
VictimCharacterId = victimCharacterId,
|
|
VictimMobDefinitionId = victimMobId,
|
|
X = x,
|
|
Y = y,
|
|
GoldAmount = gold,
|
|
CreatedAt = DateTime.UtcNow
|
|
};
|
|
db.DeathChests.Add(deathChest);
|
|
await db.SaveChangesAsync();
|
|
|
|
// Add items to chest
|
|
int slotIndex = 0;
|
|
foreach (var item in items)
|
|
{
|
|
var chestItem = new DeathChestItem
|
|
{
|
|
DeathChestId = deathChest.Id,
|
|
ItemDefinitionId = item.ItemDefinitionId,
|
|
Quantity = item.Quantity,
|
|
SlotIndex = slotIndex++
|
|
};
|
|
db.DeathChestItems.Add(chestItem);
|
|
}
|
|
await db.SaveChangesAsync();
|
|
|
|
// Create runtime instance
|
|
var lootChest = new LootChestInstance
|
|
{
|
|
Id = dungeon.Simulation.GetNextLootChestId(),
|
|
DatabaseId = deathChest.Id,
|
|
X = x,
|
|
Y = y,
|
|
OwnerCharacterId = owner.CharacterId,
|
|
Gold = gold,
|
|
Items = items.Select((item, idx) => new LootChestItem
|
|
{
|
|
SlotIndex = idx,
|
|
ItemDefinitionId = item.ItemDefinitionId,
|
|
Quantity = item.Quantity
|
|
}).ToList()
|
|
};
|
|
|
|
dungeon.Simulation.LootChests.TryAdd(lootChest.Id, lootChest);
|
|
|
|
// Notify the owner about the chest
|
|
await SendAsync(owner.Connection, DungeonOpCodes.LOOT_CHEST_SPAWNED, new
|
|
{
|
|
chestId = lootChest.Id,
|
|
x = lootChest.X,
|
|
y = lootChest.Y,
|
|
itemCount = lootChest.Items.Count,
|
|
gold = lootChest.Gold,
|
|
message = "A loot chest appeared with your overflow items!"
|
|
}, CancellationToken.None);
|
|
|
|
_log.LogInformation("Spawned loot chest {ChestId} for player {Player} with {Items} items and {Gold} gold at ({X}, {Y})",
|
|
lootChest.Id, owner.Character.Name, items.Count, gold, x, y);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Adds loot directly to player's inventory in the database (legacy - kept for compatibility)
|
|
/// </summary>
|
|
private async Task AddLootToInventoryAsync(DungeonPlayerSession session, List<LootDrop> loot)
|
|
{
|
|
var (_, _, _) = await AddLootToInventoryWithOverflowAsync(session, loot, 0);
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// Sends loot popup to client showing what they received
|
|
/// </summary>
|
|
private async Task SendLootPopupAsync(DungeonPlayerSession session, List<LootDrop> loot)
|
|
{
|
|
var lootData = loot.Select(l => new
|
|
{
|
|
id = l.ItemDefinitionId,
|
|
name = l.Item.Name,
|
|
description = l.Item.Description,
|
|
type = l.Item.Type.ToString(),
|
|
rarity = l.Item.Rarity.ToString(),
|
|
quantity = l.Quantity,
|
|
spritePath = l.Item.SpritePath,
|
|
tintColor = l.Item.TintColor,
|
|
// Include stats for display
|
|
armor = l.Item.Armor,
|
|
minDamage = l.Item.MinDamage,
|
|
maxDamage = l.Item.MaxDamage,
|
|
bonusHealth = l.Item.BonusHealth,
|
|
bonusMana = l.Item.BonusMana,
|
|
healAmount = l.Item.HealAmount,
|
|
manaRestore = l.Item.ManaRestore
|
|
});
|
|
|
|
await SendAsync(session.Connection, DungeonOpCodes.LOOT_RECEIVED, new
|
|
{
|
|
items = lootData
|
|
}, CancellationToken.None);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Handle inventory request - sends current inventory and equipment
|
|
/// </summary>
|
|
private async Task HandleInventoryRequest(IConnection connection, DungeonPlayerSession session, CancellationToken ct)
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
// Get all inventory items
|
|
var inventoryItems = await db.Set<DungeonCharacterItem>()
|
|
.Include(i => i.CraftedItem)
|
|
.Where(i => i.CharacterId == session.CharacterId)
|
|
.ToListAsync(ct);
|
|
|
|
// Get item definitions for all items
|
|
var itemDefIds = inventoryItems.Select(i => i.ItemDefinitionId).Distinct().ToList();
|
|
var itemDefs = await db.Set<DungeonItemDefinition>()
|
|
.Where(d => itemDefIds.Contains(d.Id))
|
|
.ToDictionaryAsync(d => d.Id, ct);
|
|
|
|
// Build inventory array (30 slots, null for empty)
|
|
var items = new object?[30];
|
|
foreach (var invItem in inventoryItems.Where(i => !i.IsEquipped))
|
|
{
|
|
if (invItem.SlotIndex >= 0 && invItem.SlotIndex < 30 && itemDefs.TryGetValue(invItem.ItemDefinitionId, out var def))
|
|
{
|
|
// Calculate total stats (base + crafted bonuses)
|
|
var (totalStr, totalInt, totalWis, totalEnd, totalDex, totalHealth, totalMana) =
|
|
invItem.GetTotalStats(def);
|
|
|
|
// Build rolled damage/armor if crafted
|
|
int totalMinDamage = def.MinDamage + (invItem.CraftedItem?.RolledBonusMinDamage ?? 0);
|
|
int totalMaxDamage = def.MaxDamage + (invItem.CraftedItem?.RolledBonusMaxDamage ?? 0);
|
|
int totalArmor = def.Armor + (invItem.CraftedItem?.RolledBonusArmor ?? 0);
|
|
|
|
var itemData = new Dictionary<string, object>
|
|
{
|
|
["id"] = invItem.Id,
|
|
["definitionId"] = def.Id,
|
|
["name"] = invItem.CraftedItem?.DisplayName ?? def.Name,
|
|
["description"] = def.Description,
|
|
["type"] = def.Type.ToString(),
|
|
["rarity"] = def.Rarity.ToString(),
|
|
["quantity"] = invItem.Quantity,
|
|
["minDamage"] = totalMinDamage,
|
|
["maxDamage"] = totalMaxDamage,
|
|
["armor"] = totalArmor,
|
|
["bonusStrength"] = totalStr,
|
|
["bonusIntelligence"] = totalInt,
|
|
["bonusWisdom"] = totalWis,
|
|
["bonusEndurance"] = totalEnd,
|
|
["bonusDexterity"] = totalDex,
|
|
["bonusHealth"] = totalHealth,
|
|
["bonusMana"] = totalMana,
|
|
["healAmount"] = def.HealAmount + (invItem.CraftedItem?.RolledBonusHealAmount ?? 0),
|
|
["manaRestore"] = def.ManaRestore + (invItem.CraftedItem?.RolledBonusManaRestore ?? 0),
|
|
["spritePath"] = def.SpritePath,
|
|
["tintColor"] = def.TintColor
|
|
};
|
|
|
|
// Add crafting metadata if this is a crafted item
|
|
if (invItem.CraftedItem != null)
|
|
{
|
|
itemData["isCrafted"] = true;
|
|
itemData["crafterName"] = invItem.CraftedItem.CrafterName ?? "Unknown";
|
|
itemData["qualityRating"] = invItem.CraftedItem.QualityRating;
|
|
itemData["craftedAt"] = invItem.CraftedItem.CraftedAt.ToString("yyyy-MM-dd HH:mm:ss");
|
|
}
|
|
|
|
items[invItem.SlotIndex] = itemData;
|
|
}
|
|
}
|
|
// Load hotbar assignments
|
|
var hotbarItems = await db.Set<DungeonBeltItem>()
|
|
.Where(b => b.CharacterId == session.CharacterId)
|
|
.OrderBy(b => b.SlotIndex)
|
|
.ToListAsync(ct);
|
|
|
|
var hotbar = new object?[8];
|
|
foreach (var belt in hotbarItems)
|
|
{
|
|
if (belt.SlotIndex >= 0 && belt.SlotIndex < 8)
|
|
{
|
|
hotbar[belt.SlotIndex] = new
|
|
{
|
|
inventory_slot = belt.InventorySlotIndex
|
|
};
|
|
}
|
|
}
|
|
// Build equipment map - using your actual enum names
|
|
var equipment = new Dictionary<string, object?>();
|
|
foreach (var equippedItem in inventoryItems.Where(i => i.IsEquipped))
|
|
{
|
|
if (itemDefs.TryGetValue(equippedItem.ItemDefinitionId, out var def))
|
|
{
|
|
// Map enum to client slot names
|
|
var slotName = equippedItem.EquipSlot switch
|
|
{
|
|
DungeonEquipmentSlot.MainHand => "weapon",
|
|
DungeonEquipmentSlot.OffHand => "offhand",
|
|
DungeonEquipmentSlot.Head => "helm",
|
|
DungeonEquipmentSlot.Chest => "chest",
|
|
DungeonEquipmentSlot.Legs => "legs",
|
|
DungeonEquipmentSlot.Boots => "boots",
|
|
DungeonEquipmentSlot.Gloves => "gloves",
|
|
DungeonEquipmentSlot.Necklace => "necklace",
|
|
DungeonEquipmentSlot.Ring1 => "ring1",
|
|
DungeonEquipmentSlot.Ring2 => "ring2",
|
|
DungeonEquipmentSlot.Quiver => "quiver",
|
|
_ => "unknown"
|
|
};
|
|
|
|
// Calculate total stats for equipped item
|
|
var (totalStr, totalInt, totalWis, totalEnd, totalDex, totalHealth, totalMana) =
|
|
equippedItem.GetTotalStats(def);
|
|
|
|
int totalMinDamage = def.MinDamage + (equippedItem.CraftedItem?.RolledBonusMinDamage ?? 0);
|
|
int totalMaxDamage = def.MaxDamage + (equippedItem.CraftedItem?.RolledBonusMaxDamage ?? 0);
|
|
int totalArmor = def.Armor + (equippedItem.CraftedItem?.RolledBonusArmor ?? 0);
|
|
|
|
var equipData = new Dictionary<string, object>
|
|
{
|
|
["id"] = equippedItem.Id,
|
|
["definitionId"] = def.Id,
|
|
["name"] = equippedItem.CraftedItem?.DisplayName ?? def.Name,
|
|
["description"] = def.Description,
|
|
["type"] = def.Type.ToString(),
|
|
["rarity"] = def.Rarity.ToString(),
|
|
["minDamage"] = totalMinDamage,
|
|
["maxDamage"] = totalMaxDamage,
|
|
["armor"] = totalArmor,
|
|
["bonusStrength"] = totalStr,
|
|
["bonusIntelligence"] = totalInt,
|
|
["bonusWisdom"] = totalWis,
|
|
["bonusEndurance"] = totalEnd,
|
|
["bonusDexterity"] = totalDex,
|
|
["bonusHealth"] = totalHealth,
|
|
["bonusMana"] = totalMana,
|
|
["spritePath"] = def.SpritePath ?? "",
|
|
["quantity"] = equippedItem.Quantity,
|
|
["requiresAmmunition"] = def.RequiresAmmunition,
|
|
["projectileSpeed"] = def.ProjectileSpeed,
|
|
["projectileRange"] = def.ProjectileRange,
|
|
["isThrowable"] = def.IsThrowable,
|
|
["ammunitionType"] = def.AmmunitionType ?? ""
|
|
};
|
|
|
|
if (equippedItem.CraftedItem != null)
|
|
{
|
|
equipData["isCrafted"] = true;
|
|
equipData["qualityRating"] = equippedItem.CraftedItem.QualityRating;
|
|
}
|
|
|
|
equipment[slotName] = equipData;
|
|
}
|
|
}
|
|
|
|
await SendAsync(connection, DungeonOpCodes.INVENTORY_STATE, new
|
|
{
|
|
items,
|
|
equipment,
|
|
hotbar,
|
|
}, ct);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Handle equip item request
|
|
/// </summary>
|
|
private async Task HandleEquipItem(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
|
|
var request = System.Text.Json.JsonSerializer.Deserialize<EquipItemRequest>(json);
|
|
if (request == null) return;
|
|
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
// Get the item to equip
|
|
var item = await db.Set<DungeonCharacterItem>()
|
|
.Include(i => i.ItemDefinition)
|
|
.Include(i => i.CraftedItem)
|
|
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId && i.SlotIndex == request.SlotIndex && !i.IsEquipped, ct);
|
|
if (item?.ItemDefinition == null) return;
|
|
|
|
// Determine equipment slot based on item type
|
|
var equipSlot = GetEquipSlotForItem(item.ItemDefinition);
|
|
if (equipSlot == null)
|
|
{
|
|
_log.LogWarning("Cannot equip item {ItemName} - no valid equip slot", item.ItemDefinition.Name);
|
|
return;
|
|
}
|
|
|
|
// Unequip any existing item in that slot
|
|
var existingEquipped = await db.Set<DungeonCharacterItem>()
|
|
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId && i.IsEquipped && i.EquipSlot == equipSlot, ct);
|
|
// We'll need this for hotbar remapping
|
|
int? movedOldEquipToInventorySlot = null;
|
|
|
|
if (existingEquipped != null)
|
|
{
|
|
existingEquipped.IsEquipped = false;
|
|
existingEquipped.EquipSlot = null;
|
|
// Find first empty inventory slot
|
|
var usedSlots = await db.Set<DungeonCharacterItem>()
|
|
.Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped)
|
|
.Select(i => i.SlotIndex)
|
|
.ToListAsync(ct);
|
|
var emptySlot = Enumerable.Range(0, 30)
|
|
.Where(s => !usedSlots.Contains(s))
|
|
.DefaultIfEmpty(-1)
|
|
.First();
|
|
|
|
if (emptySlot == -1)
|
|
{
|
|
// Inventory full: decide your policy (swap into the source slot, reject equip, etc.)
|
|
// Safest is to reject equip rather than corrupting inventory/hotbar state.
|
|
_log.LogWarning("Cannot equip item {ItemName} - inventory full, nowhere to place unequipped item", item.ItemDefinition.Name);
|
|
return;
|
|
}
|
|
|
|
existingEquipped.SlotIndex = emptySlot;
|
|
movedOldEquipToInventorySlot = emptySlot;
|
|
// existingEquipped.SlotIndex = Enumerable.Range(0, 30).FirstOrDefault(s => !usedSlots.Contains(s));
|
|
}
|
|
|
|
// Any hotbar entries pointing at the *inventory slot being equipped from* should now point at
|
|
// the slot where the previous equipped item landed (if any), otherwise remove them.
|
|
var affectedHotbarEntries = await db.Set<DungeonBeltItem>()
|
|
.Where(b => b.CharacterId == session.CharacterId &&
|
|
b.InventorySlotIndex == request.SlotIndex)
|
|
.ToListAsync(ct);
|
|
|
|
if (affectedHotbarEntries.Count > 0)
|
|
{
|
|
if (movedOldEquipToInventorySlot.HasValue)
|
|
{
|
|
foreach (var belt in affectedHotbarEntries)
|
|
belt.InventorySlotIndex = movedOldEquipToInventorySlot.Value;
|
|
}
|
|
else
|
|
{
|
|
// No item replaced; the inventory slot becomes empty, so clear hotbar mapping
|
|
db.Set<DungeonBeltItem>().RemoveRange(affectedHotbarEntries);
|
|
}
|
|
}
|
|
|
|
// Equip the new item
|
|
item.IsEquipped = true;
|
|
item.EquipSlot = equipSlot;
|
|
item.SlotIndex = -1; // Not in regular inventory
|
|
|
|
await db.SaveChangesAsync(ct);
|
|
|
|
// Recalculate stats if player is in dungeon
|
|
if (session.PlayerInstance != null && session.State == PlayerState.InDungeon)
|
|
{
|
|
// Reload all equipped items with updated equip status
|
|
var equippedItems = await db.Set<DungeonCharacterItem>()
|
|
.Include(i => i.ItemDefinition)
|
|
.Include(i => i.CraftedItem)
|
|
.Where(i => i.CharacterId == session.CharacterId && i.IsEquipped)
|
|
.ToListAsync(ct);
|
|
|
|
// Recalculate combat stats with new equipment
|
|
var newStats = DungeonCharacterStats.GetCombatStats(session.Character, equippedItems);
|
|
|
|
// Update PlayerInstance (preserve current health/mana/stamina but cap to new max)
|
|
var player = session.PlayerInstance;
|
|
player.MaxHealth = newStats.MaxHealth;
|
|
player.MaxMana = newStats.MaxMana;
|
|
player.MaxStamina = newStats.MaxStamina;
|
|
player.Health = Math.Min(player.Health, newStats.MaxHealth);
|
|
player.Mana = Math.Min(player.Mana, newStats.MaxMana);
|
|
player.Stamina = Math.Min(player.Stamina, newStats.MaxStamina);
|
|
player.Armor = newStats.Armor;
|
|
player.Strength = newStats.Strength;
|
|
player.Intelligence = newStats.Intelligence;
|
|
player.Wisdom = newStats.Wisdom;
|
|
player.Endurance = newStats.Endurance;
|
|
player.Dexterity = newStats.Dexterity;
|
|
player.MoveSpeed = newStats.MoveSpeed;
|
|
player.AttackSpeed = newStats.AttackSpeed;
|
|
|
|
_log.LogInformation("Player {Name} equipped item {ItemName}, stats updated in dungeon",
|
|
session.Character.Name, item.ItemDefinition.Name);
|
|
}
|
|
|
|
// Send updated inventory
|
|
await HandleInventoryRequest(connection, session, ct);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Handle unequip item request
|
|
/// </summary>
|
|
private async Task HandleUnequipItem(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
|
|
var request = System.Text.Json.JsonSerializer.Deserialize<UnequipItemRequest>(json);
|
|
if (request == null) return;
|
|
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
// Map client slot name to enum
|
|
var equipSlot = request.Slot?.ToLower() switch
|
|
{
|
|
"weapon" => DungeonEquipmentSlot.MainHand,
|
|
"offhand" => DungeonEquipmentSlot.OffHand,
|
|
"helm" => DungeonEquipmentSlot.Head,
|
|
"chest" => DungeonEquipmentSlot.Chest,
|
|
"legs" => DungeonEquipmentSlot.Legs,
|
|
"boots" => DungeonEquipmentSlot.Boots,
|
|
"gloves" => DungeonEquipmentSlot.Gloves,
|
|
"necklace" => DungeonEquipmentSlot.Necklace,
|
|
"ring1" => DungeonEquipmentSlot.Ring1,
|
|
"ring2" => DungeonEquipmentSlot.Ring2,
|
|
"quiver" => DungeonEquipmentSlot.Quiver,
|
|
_ => (DungeonEquipmentSlot?)null
|
|
};
|
|
|
|
if (equipSlot == null) return;
|
|
|
|
var equippedItem = await db.Set<DungeonCharacterItem>()
|
|
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId && i.IsEquipped && i.EquipSlot == equipSlot, ct);
|
|
|
|
if (equippedItem == null) return;
|
|
|
|
// Find first empty inventory slot
|
|
var usedSlots = await db.Set<DungeonCharacterItem>()
|
|
.Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped)
|
|
.Select(i => i.SlotIndex)
|
|
.ToListAsync(ct);
|
|
|
|
if (usedSlots.Count >= 30)
|
|
{
|
|
_log.LogWarning("Cannot unequip - inventory full");
|
|
return;
|
|
}
|
|
|
|
var emptySlot = Enumerable.Range(0, 30).FirstOrDefault(s => !usedSlots.Contains(s));
|
|
|
|
// Store item name for logging before we modify it
|
|
string? itemName = null;
|
|
if (equippedItem.ItemDefinition != null)
|
|
{
|
|
itemName = equippedItem.ItemDefinition.Name;
|
|
}
|
|
|
|
equippedItem.IsEquipped = false;
|
|
equippedItem.EquipSlot = null;
|
|
equippedItem.SlotIndex = emptySlot;
|
|
|
|
await db.SaveChangesAsync(ct);
|
|
|
|
// Recalculate stats if player is in dungeon
|
|
if (session.PlayerInstance != null && session.State == PlayerState.InDungeon)
|
|
{
|
|
// Reload all equipped items with updated equip status
|
|
var equippedItems = await db.Set<DungeonCharacterItem>()
|
|
.Include(i => i.ItemDefinition)
|
|
.Include(i => i.CraftedItem)
|
|
.Where(i => i.CharacterId == session.CharacterId && i.IsEquipped)
|
|
.ToListAsync(ct);
|
|
|
|
// Recalculate combat stats with new equipment
|
|
var newStats = DungeonCharacterStats.GetCombatStats(session.Character, equippedItems);
|
|
|
|
// Update PlayerInstance (preserve current health/mana/stamina but cap to new max)
|
|
var player = session.PlayerInstance;
|
|
player.MaxHealth = newStats.MaxHealth;
|
|
player.MaxMana = newStats.MaxMana;
|
|
player.MaxStamina = newStats.MaxStamina;
|
|
player.Health = Math.Min(player.Health, newStats.MaxHealth);
|
|
player.Mana = Math.Min(player.Mana, newStats.MaxMana);
|
|
player.Stamina = Math.Min(player.Stamina, newStats.MaxStamina);
|
|
player.Armor = newStats.Armor;
|
|
player.Strength = newStats.Strength;
|
|
player.Intelligence = newStats.Intelligence;
|
|
player.Wisdom = newStats.Wisdom;
|
|
player.Endurance = newStats.Endurance;
|
|
player.Dexterity = newStats.Dexterity;
|
|
player.MoveSpeed = newStats.MoveSpeed;
|
|
player.AttackSpeed = newStats.AttackSpeed;
|
|
|
|
if (itemName != null)
|
|
{
|
|
_log.LogInformation("Player {Name} unequipped item {ItemName}, stats updated in dungeon",
|
|
session.Character.Name, itemName);
|
|
}
|
|
}
|
|
|
|
// Send updated inventory
|
|
await HandleInventoryRequest(connection, session, ct);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Handle use item request (consumables get used, equipment gets equipped)
|
|
/// </summary>
|
|
private async Task HandleUseItem(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
|
|
var request = System.Text.Json.JsonSerializer.Deserialize<UseItemRequest>(json);
|
|
if (request == null) return;
|
|
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
var item = await db.Set<DungeonCharacterItem>()
|
|
.Include(i => i.ItemDefinition)
|
|
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId && i.SlotIndex == request.SlotIndex && !i.IsEquipped, ct);
|
|
|
|
if (item?.ItemDefinition == null) return;
|
|
|
|
// If it's equipment, delegate to equip handler instead
|
|
if (item.ItemDefinition.Type == ItemType.Weapon ||
|
|
item.ItemDefinition.Type == ItemType.Armor ||
|
|
item.ItemDefinition.Type == ItemType.Accessory)
|
|
{
|
|
await HandleEquipItem(connection, session, payload, ct);
|
|
return;
|
|
}
|
|
|
|
// Only consumables can be used directly
|
|
if (item.ItemDefinition.Type != ItemType.Consumable) return;
|
|
|
|
// Apply effects
|
|
if (session.PlayerInstance != null)
|
|
{
|
|
if (item.ItemDefinition.HealAmount > 0)
|
|
{
|
|
session.PlayerInstance.Health = Math.Min(
|
|
session.PlayerInstance.Health + item.ItemDefinition.HealAmount,
|
|
session.PlayerInstance.MaxHealth
|
|
);
|
|
}
|
|
if (item.ItemDefinition.ManaRestore > 0)
|
|
{
|
|
session.PlayerInstance.Mana = Math.Min(
|
|
session.PlayerInstance.Mana + item.ItemDefinition.ManaRestore,
|
|
session.PlayerInstance.MaxMana
|
|
);
|
|
}
|
|
}
|
|
|
|
// Decrease quantity or remove
|
|
item.Quantity--;
|
|
if (item.Quantity <= 0)
|
|
{
|
|
db.Set<DungeonCharacterItem>().Remove(item);
|
|
}
|
|
|
|
await db.SaveChangesAsync(ct);
|
|
|
|
// Send updated inventory
|
|
await HandleInventoryRequest(connection, session, ct);
|
|
}
|
|
|
|
private async Task HandleStackItems(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
|
|
var request = System.Text.Json.JsonSerializer.Deserialize<StackItemsRequest>(json);
|
|
if (request == null) return;
|
|
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
// Get both items
|
|
var sourceItem = await db.Set<DungeonCharacterItem>()
|
|
.Include(i => i.ItemDefinition)
|
|
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId && i.SlotIndex == request.SourceSlot && !i.IsEquipped, ct);
|
|
|
|
var targetItem = await db.Set<DungeonCharacterItem>()
|
|
.Include(i => i.ItemDefinition)
|
|
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId && i.SlotIndex == request.TargetSlot && !i.IsEquipped, ct);
|
|
|
|
if (sourceItem?.ItemDefinition == null || targetItem?.ItemDefinition == null) return;
|
|
|
|
// Can only stack items with the same ID and that are stackable
|
|
if (sourceItem.ItemDefinitionId != targetItem.ItemDefinitionId) return;
|
|
if (!sourceItem.ItemDefinition.Stackable || !targetItem.ItemDefinition.Stackable) return;
|
|
|
|
// Check max stack
|
|
var maxStack = targetItem.ItemDefinition.MaxStack;
|
|
if (targetItem.Quantity >= maxStack) return;
|
|
|
|
// Stack as much as possible
|
|
var spaceAvailable = maxStack - targetItem.Quantity;
|
|
var amountToMove = Math.Min(sourceItem.Quantity, spaceAvailable);
|
|
|
|
targetItem.Quantity += amountToMove;
|
|
sourceItem.Quantity -= amountToMove;
|
|
|
|
// Remove source if empty
|
|
if (sourceItem.Quantity <= 0)
|
|
{
|
|
db.Set<DungeonCharacterItem>().Remove(sourceItem);
|
|
}
|
|
|
|
await db.SaveChangesAsync(ct);
|
|
|
|
// Send updated inventory
|
|
await HandleInventoryRequest(connection, session, ct);
|
|
}
|
|
|
|
private async Task HandleMoveItem(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
|
|
var request = System.Text.Json.JsonSerializer.Deserialize<MoveItemRequest>(json);
|
|
if (request == null) return;
|
|
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
// Get both items with their definitions and crafted data
|
|
var sourceItem = await db.Set<DungeonCharacterItem>()
|
|
.Include(i => i.ItemDefinition)
|
|
.Include(i => i.CraftedItem)
|
|
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId && i.SlotIndex == request.SourceSlot && !i.IsEquipped, ct);
|
|
|
|
var targetItem = await db.Set<DungeonCharacterItem>()
|
|
.Include(i => i.ItemDefinition)
|
|
.Include(i => i.CraftedItem)
|
|
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId && i.SlotIndex == request.TargetSlot && !i.IsEquipped, ct);
|
|
|
|
if (sourceItem == null) return; // Nothing to move
|
|
|
|
// Check if items can be stacked (same item definition, both stackable, and identical crafted items if any)
|
|
if (targetItem != null &&
|
|
sourceItem.ItemDefinition != null &&
|
|
targetItem.ItemDefinition != null &&
|
|
sourceItem.ItemDefinitionId == targetItem.ItemDefinitionId &&
|
|
sourceItem.ItemDefinition.Stackable &&
|
|
CanStackItems(sourceItem, targetItem))
|
|
{
|
|
// Combine stacks
|
|
var maxStack = sourceItem.ItemDefinition.MaxStack;
|
|
var spaceAvailable = maxStack - targetItem.Quantity;
|
|
var amountToMove = Math.Min(sourceItem.Quantity, spaceAvailable);
|
|
|
|
if (amountToMove > 0)
|
|
{
|
|
targetItem.Quantity += amountToMove;
|
|
sourceItem.Quantity -= amountToMove;
|
|
|
|
if (sourceItem.Quantity <= 0)
|
|
{
|
|
db.Set<DungeonCharacterItem>().Remove(sourceItem);
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// Simple swap of slot indices
|
|
if (targetItem != null)
|
|
{
|
|
targetItem.SlotIndex = request.SourceSlot;
|
|
}
|
|
sourceItem.SlotIndex = request.TargetSlot;
|
|
}
|
|
|
|
await db.SaveChangesAsync(ct);
|
|
|
|
// Send updated inventory
|
|
await HandleInventoryRequest(connection, session, ct);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Checks if two items can be stacked together.
|
|
/// Items without crafted data can always stack (if same definition and stackable).
|
|
/// Items with crafted data can stack if both have no actual rolled stats (all bonuses are 0),
|
|
/// or if they have the same CraftedItem.Id.
|
|
/// </summary>
|
|
private static bool CanStackItems(DungeonCharacterItem source, DungeonCharacterItem target)
|
|
{
|
|
// If neither has crafted data, they can stack
|
|
if (source.CraftedItem == null && target.CraftedItem == null)
|
|
return true;
|
|
|
|
// If one has crafted data and the other doesn't, check if the crafted one has no actual stats
|
|
if (source.CraftedItem == null)
|
|
return !HasRolledStats(target.CraftedItem);
|
|
if (target.CraftedItem == null)
|
|
return !HasRolledStats(source.CraftedItem);
|
|
|
|
// Both have crafted data - they can stack if neither has rolled stats, or if same crafted item
|
|
if (source.CraftedItem.Id == target.CraftedItem.Id)
|
|
return true;
|
|
|
|
// Different crafted items can stack if neither has actual rolled stats
|
|
return !HasRolledStats(source.CraftedItem) && !HasRolledStats(target.CraftedItem);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Checks if a crafted item has any non-zero rolled stats.
|
|
/// </summary>
|
|
private static bool HasRolledStats(DungeonCraftedItem crafted)
|
|
{
|
|
return crafted.RolledBonusStrength != 0 ||
|
|
crafted.RolledBonusIntelligence != 0 ||
|
|
crafted.RolledBonusWisdom != 0 ||
|
|
crafted.RolledBonusEndurance != 0 ||
|
|
crafted.RolledBonusDexterity != 0 ||
|
|
crafted.RolledBonusHealth != 0 ||
|
|
crafted.RolledBonusMana != 0 ||
|
|
crafted.RolledBonusArmor != 0 ||
|
|
crafted.RolledBonusMagicResist != 0 ||
|
|
crafted.RolledBonusMinDamage != 0 ||
|
|
crafted.RolledBonusMaxDamage != 0 ||
|
|
crafted.RolledBonusHealAmount != 0 ||
|
|
crafted.RolledBonusManaRestore != 0;
|
|
}
|
|
|
|
private async Task HandleAutoStackInventory(IConnection connection, DungeonPlayerSession session, CancellationToken ct)
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
// Get all inventory items
|
|
var items = await db.Set<DungeonCharacterItem>()
|
|
.Include(i => i.ItemDefinition)
|
|
.Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped)
|
|
.OrderBy(i => i.SlotIndex)
|
|
.ToListAsync(ct);
|
|
|
|
// Group stackable items by ItemDefinitionId
|
|
var stackableGroups = items
|
|
.Where(i => i.ItemDefinition.Stackable)
|
|
.GroupBy(i => i.ItemDefinitionId)
|
|
.Where(g => g.Count() > 1) // Only process if there are multiple stacks
|
|
.ToList();
|
|
|
|
foreach (var group in stackableGroups)
|
|
{
|
|
var maxStack = group.First().ItemDefinition.MaxStack;
|
|
var stacks = group.OrderBy(i => i.Quantity).ToList();
|
|
|
|
// Consolidate into as few stacks as possible
|
|
for (int i = 0; i < stacks.Count; i++)
|
|
{
|
|
if (stacks[i].Quantity >= maxStack) continue;
|
|
|
|
for (int j = i + 1; j < stacks.Count; j++)
|
|
{
|
|
if (stacks[j].Quantity == 0) continue;
|
|
|
|
var spaceAvailable = maxStack - stacks[i].Quantity;
|
|
var amountToMove = Math.Min(stacks[j].Quantity, spaceAvailable);
|
|
|
|
if (amountToMove > 0)
|
|
{
|
|
stacks[i].Quantity += amountToMove;
|
|
stacks[j].Quantity -= amountToMove;
|
|
|
|
if (stacks[j].Quantity <= 0)
|
|
{
|
|
db.Set<DungeonCharacterItem>().Remove(stacks[j]);
|
|
}
|
|
}
|
|
|
|
if (stacks[i].Quantity >= maxStack) break;
|
|
}
|
|
}
|
|
}
|
|
|
|
await db.SaveChangesAsync(ct);
|
|
|
|
// Send updated inventory
|
|
await HandleInventoryRequest(connection, session, ct);
|
|
}
|
|
|
|
private DungeonEquipmentSlot? GetEquipSlotForItem(DungeonItemDefinition item)
|
|
{
|
|
return item.Type switch
|
|
{
|
|
ItemType.Weapon => item.EquipSlot ?? DungeonEquipmentSlot.MainHand,
|
|
ItemType.Armor => item.EquipSlot ?? DungeonEquipmentSlot.Chest,
|
|
ItemType.Accessory => DungeonEquipmentSlot.Ring1, // Default to Ring1, but check if already equipped
|
|
_ => null
|
|
};
|
|
}
|
|
|
|
// Request DTOs
|
|
private class EquipItemRequest { public int SlotIndex { get; set; } }
|
|
private class UnequipItemRequest { public string Slot { get; set; } = ""; }
|
|
private class UseItemRequest { public int SlotIndex { get; set; } }
|
|
private class StackItemsRequest { public int SourceSlot { get; set; } public int TargetSlot { get; set; } }
|
|
private class MoveItemRequest { public int SourceSlot { get; set; } public int TargetSlot { get; set; } }
|
|
|
|
private async Task SendDungeonStateAsync(DungeonPlayerSession session, TickResult? tickResult)
|
|
{
|
|
var dungeon = _dungeons.GetValueOrDefault(session.CurrentDungeonId!.Value);
|
|
if (dungeon == null) return;
|
|
|
|
var sim = dungeon.Simulation;
|
|
|
|
var state = new
|
|
{
|
|
tick = _currentTick,
|
|
phase = sim.Phase.ToString().ToLower(),
|
|
|
|
// NOTE: tiles are NOT sent every tick - they're static and sent once on DUNGEON_ENTER_RESULT
|
|
|
|
players = sim.Players.Values.Select(p => new
|
|
{
|
|
id = p.CharacterId,
|
|
name = p.CharacterName,
|
|
x = p.X,
|
|
y = p.Y,
|
|
rotation = p.Rotation,
|
|
health = (int)p.Health,
|
|
maxHealth = (int)p.MaxHealth,
|
|
mana = (int)p.Mana,
|
|
maxMana = (int)p.MaxMana,
|
|
stamina = (int)p.Stamina,
|
|
maxStamina = (int)p.MaxStamina,
|
|
isAlive = p.IsAlive,
|
|
isInCombat = p.IsInCombat
|
|
}),
|
|
|
|
mobs = sim.Mobs.Values.Select(m => new
|
|
{
|
|
id = m.Id,
|
|
name = m.Name,
|
|
x = m.X,
|
|
y = m.Y,
|
|
rotation = m.Rotation,
|
|
health = m.Health,
|
|
maxHealth = m.MaxHealth,
|
|
state = m.State.ToString().ToLower(),
|
|
spriteConfig = string.IsNullOrEmpty(m.SpriteConfigJson) ? null :
|
|
System.Text.Json.JsonSerializer.Deserialize<object>(m.SpriteConfigJson),
|
|
tintColor = m.TintColor,
|
|
scale = m.Scale
|
|
}),
|
|
|
|
chests = sim.Chests.Values.Select(c => new
|
|
{
|
|
id = c.Id,
|
|
x = c.X,
|
|
y = c.Y,
|
|
opened = c.IsOpened
|
|
}),
|
|
|
|
droppedItems = sim.DroppedItems.Values.Select(i => new
|
|
{
|
|
id = i.Id,
|
|
itemId = i.ItemDefinitionId,
|
|
quantity = i.Quantity,
|
|
x = i.X,
|
|
y = i.Y
|
|
}),
|
|
|
|
portals = sim.Portals.Values.Where(p => p.IsActive).Select(p => new
|
|
{
|
|
id = p.Id,
|
|
x = p.X,
|
|
y = p.Y,
|
|
type = p.Type.ToString().ToLower()
|
|
}),
|
|
|
|
// Loot chests are only visible to their owner
|
|
lootChests = sim.LootChests.Values
|
|
.Where(c => c.OwnerCharacterId == session.CharacterId)
|
|
.Select(c => new
|
|
{
|
|
id = c.Id,
|
|
x = c.X,
|
|
y = c.Y,
|
|
itemCount = c.Items.Count,
|
|
gold = c.Gold,
|
|
isOpen = c.IsOpen
|
|
}),
|
|
|
|
events = tickResult == null ? null : new
|
|
{
|
|
damage = tickResult.DamageEvents.Select(e => new
|
|
{
|
|
sourceType = e.SourceType.ToString().ToLower(),
|
|
sourceId = e.SourceId,
|
|
targetType = e.TargetType.ToString().ToLower(),
|
|
targetId = e.TargetId,
|
|
damage = e.Damage,
|
|
damageTypeKey = e.DamageTypeKey,
|
|
wasResisted = e.WasResisted,
|
|
wasWeakness = e.WasWeakness
|
|
}),
|
|
deaths = tickResult.DeathEvents.Select(e => new
|
|
{
|
|
entityType = e.EntityType.ToString().ToLower(),
|
|
entityId = e.EntityId,
|
|
entityName = e.EntityName,
|
|
killerType = e.KillerType.ToString().ToLower(),
|
|
killerId = e.KillerId,
|
|
killerName = e.KillerName,
|
|
xp = e.XpReward
|
|
}),
|
|
projectileHits = tickResult.ProjectileHitEvents.Select(e => new
|
|
{
|
|
projectileId = e.ProjectileId,
|
|
targetType = e.TargetType.ToString().ToLower(),
|
|
targetId = e.TargetId,
|
|
x = e.X,
|
|
y = e.Y
|
|
}),
|
|
projectileExpired = tickResult.ProjectileExpiredEvents.Select(e => new
|
|
{
|
|
projectileId = e.ProjectileId,
|
|
x = e.X,
|
|
y = e.Y,
|
|
reason = e.Reason
|
|
})
|
|
},
|
|
|
|
exitPosition = sim.Layout.ExitPosition != null ? new
|
|
{
|
|
x = sim.Layout.ExitPosition.Value.X * 32 + 16,
|
|
y = sim.Layout.ExitPosition.Value.Y * 32 + 16
|
|
} : null
|
|
};
|
|
|
|
await SendAsync(session.Connection, DungeonOpCodes.DUNGEON_STATE, state, CancellationToken.None);
|
|
}
|
|
|
|
private async Task CompleteEscapeAsync(DungeonPlayerSession session)
|
|
{
|
|
session.IsEscaping = false;
|
|
|
|
await SendAsync(session.Connection, DungeonOpCodes.ESCAPE_SUCCESS, new { }, CancellationToken.None);
|
|
await RemoveFromDungeonAsync(session, true, CancellationToken.None);
|
|
await SendAsync(session.Connection, DungeonOpCodes.HUB_STATE, GetHubState(session.Character), CancellationToken.None);
|
|
}
|
|
/// <summary>
|
|
/// Handle dungeon cleared - return player to hub with all loot
|
|
/// </summary>
|
|
private async Task HandleDungeonClearedAsync(DungeonPlayerSession session)
|
|
{
|
|
_log.LogInformation("Dungeon cleared! Player {Name} can now exit via portal", session.Character.Name);
|
|
|
|
// Send dungeon cleared notification (but don't force exit)
|
|
await SendAsync(session.Connection, DungeonOpCodes.DUNGEON_STATE, new
|
|
{
|
|
phase = "cleared",
|
|
message = "Dungeon cleared! Use the portal to exit."
|
|
}, CancellationToken.None);
|
|
|
|
// Don't automatically remove from dungeon - let them use the portal
|
|
}
|
|
|
|
private async Task HandlePlayerDeathAsync(DungeonPlayerSession session)
|
|
{
|
|
await RemoveFromDungeonAsync(session, false, CancellationToken.None);
|
|
|
|
// Reset health on death
|
|
session.Character.CurrentHealth = DungeonCharacterStats.GetMaxHealth(session.Character);
|
|
session.Character.CurrentMana = DungeonCharacterStats.GetMaxMana(session.Character);
|
|
session.Character.TotalDeaths++;
|
|
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
db.Attach(session.Character);
|
|
db.Entry(session.Character).State = EntityState.Modified;
|
|
await db.SaveChangesAsync();
|
|
|
|
await SendAsync(session.Connection, DungeonOpCodes.HUB_STATE, GetHubState(session.Character), CancellationToken.None);
|
|
}
|
|
|
|
private async Task RemoveFromDungeonAsync(DungeonPlayerSession session, bool extracted, CancellationToken ct)
|
|
{
|
|
if (!session.CurrentDungeonId.HasValue) return;
|
|
|
|
if (_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
|
|
{
|
|
dungeon.Simulation.Players.TryRemove(session.CharacterId, out var player);
|
|
|
|
if (player != null)
|
|
{
|
|
await SaveCharacterStateAsync(session.Character, player, extracted, ct);
|
|
}
|
|
}
|
|
|
|
session.State = PlayerState.InHub;
|
|
session.CurrentDungeonId = null;
|
|
session.PlayerInstance = null;
|
|
session.IsEscaping = false;
|
|
}
|
|
|
|
private async Task SaveCharacterStateAsync(DungeonCharacter character, PlayerInstance player, bool extracted, CancellationToken ct)
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
// Add XP earned
|
|
character.Experience += player.XpGained;
|
|
character.TotalKills += player.MobsKilled;
|
|
character.PlayersKilled += player.PlayersKilled;
|
|
|
|
if (extracted)
|
|
{
|
|
character.DungeonsCompleted++;
|
|
character.CurrentHealth = (int)player.Health;
|
|
character.CurrentMana = (int)player.Mana;
|
|
}
|
|
else
|
|
{
|
|
character.TotalDeaths++;
|
|
character.CurrentHealth = DungeonCharacterStats.GetMaxHealth(character);
|
|
character.CurrentMana = DungeonCharacterStats.GetMaxMana(character);
|
|
}
|
|
|
|
// Check for level up
|
|
while (character.Experience >= LevelSystem.GetTotalXpForLevel(character.Level + 1))
|
|
{
|
|
character.Level++;
|
|
character.UnspentStatPoints += 5;
|
|
}
|
|
|
|
character.LastPlayedAt = DateTime.UtcNow;
|
|
|
|
db.Attach(character);
|
|
db.Entry(character).State = EntityState.Modified;
|
|
await db.SaveChangesAsync(ct);
|
|
|
|
_log.LogInformation("Saved character {Name}: Level {Level}, XP {Xp}, Extracted={Extracted}",
|
|
character.Name, character.Level, character.Experience, extracted);
|
|
}
|
|
|
|
private object GetHubState(DungeonCharacter character)
|
|
{
|
|
return new
|
|
{
|
|
character = new
|
|
{
|
|
id = character.Id,
|
|
name = character.Name,
|
|
level = character.Level,
|
|
xp = character.Experience,
|
|
xpNext = LevelSystem.GetXpForLevel(character.Level + 1),
|
|
unspentPoints = character.UnspentStatPoints,
|
|
strength = character.Strength,
|
|
intelligence = character.Intelligence,
|
|
wisdom = character.Wisdom,
|
|
endurance = character.Endurance,
|
|
dexterity = character.Dexterity,
|
|
maxHealth = DungeonCharacterStats.GetMaxHealth(character),
|
|
maxMana = DungeonCharacterStats.GetMaxMana(character),
|
|
maxStamina = DungeonCharacterStats.GetMaxStamina(character),
|
|
gold = character.Gold
|
|
}
|
|
};
|
|
}
|
|
|
|
private async Task SendAsync(IConnection connection, int opCode, object payload, CancellationToken ct)
|
|
{
|
|
try
|
|
{
|
|
var payloadBytes = _ser.Serialize(payload);
|
|
var msg = new ServerMessage(opCode, payloadBytes);
|
|
var wire = _ser.Serialize(msg);
|
|
await connection.SendAsync(wire, ct);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_log.LogWarning(ex, "Failed to send message to connection {Id}", connection.Id);
|
|
}
|
|
}
|
|
|
|
private async Task SendErrorAsync(IConnection connection, string error, CancellationToken ct)
|
|
{
|
|
_log.LogWarning("Sending error to client: {Error}", error);
|
|
await SendAsync(connection, OpCodes.ERROR, new { error }, ct);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Called when a connection is closed - cleanup session
|
|
/// </summary>
|
|
public void OnDisconnect(Guid connectionId)
|
|
{
|
|
if (_playerSessions.TryRemove(connectionId, out var session))
|
|
{
|
|
// Track disconnection in Redis
|
|
_ = TrackPlayerDisconnectedAsync(session);
|
|
|
|
if (session.CurrentDungeonId.HasValue)
|
|
{
|
|
// Delay removal from dungeon by 25 seconds to allow for reconnection
|
|
// and to prevent abuse (disconnecting to avoid combat)
|
|
_ = Task.Run(async () =>
|
|
{
|
|
await Task.Delay(TimeSpan.FromSeconds(25));
|
|
await RemoveFromDungeonAsync(session, false, CancellationToken.None);
|
|
_log.LogInformation("Player {CharacterName} removed from dungeon after 25s disconnect timeout",
|
|
session.Character?.Name ?? "Unknown");
|
|
});
|
|
|
|
_log.LogInformation("Dungeon session for {CharacterName} will be removed in 25s after disconnect",
|
|
session.Character?.Name ?? "Unknown");
|
|
}
|
|
else
|
|
{
|
|
_log.LogInformation("Dungeon session cleaned up for connection {Id}", connectionId);
|
|
}
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// Handle chat message from player
|
|
/// </summary>
|
|
private async Task HandleChatSend(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
|
|
var request = System.Text.Json.JsonSerializer.Deserialize<ChatSendRequest>(json);
|
|
if (request == null || string.IsNullOrWhiteSpace(request.Message)) return;
|
|
|
|
// Sanitize message (basic - remove excessive whitespace, limit length)
|
|
var message = request.Message.Trim();
|
|
if (message.Length > 200) message = message.Substring(0, 200);
|
|
|
|
var senderName = session.Character?.Name ?? "Unknown";
|
|
|
|
// Determine chat scope based on player state
|
|
if (session.CurrentDungeonId.HasValue && _dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
|
|
{
|
|
// In dungeon - broadcast to all players in same dungeon
|
|
foreach (var player in dungeon.Simulation.Players.Values)
|
|
{
|
|
|
|
await SendAsync(_playerSessions.Values.Where(p => p.CharacterId == player.CharacterId).FirstOrDefault().Connection, DungeonOpCodes.CHAT_MESSAGE, new
|
|
{
|
|
sender = senderName,
|
|
message = message,
|
|
type = "normal"
|
|
}, ct);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// In hub - broadcast to all connected players in hub
|
|
foreach (var playerSession in _playerSessions.Values.Where(p => !p.CurrentDungeonId.HasValue))
|
|
{
|
|
await SendAsync(playerSession.Connection, DungeonOpCodes.CHAT_MESSAGE, new
|
|
{
|
|
sender = senderName,
|
|
message = message,
|
|
type = "normal"
|
|
}, ct);
|
|
}
|
|
}
|
|
|
|
_log.LogDebug("Chat from {Player}: {Message}", senderName, message);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Broadcast a system message to all players in a dungeon
|
|
/// </summary>
|
|
private async Task BroadcastSystemMessage(DungeonInstance dungeon, string message, CancellationToken ct)
|
|
{
|
|
foreach (var player in dungeon.Simulation.Players.Values)
|
|
{
|
|
await SendAsync(_playerSessions.Values.Where(p => p.CharacterId == player.CharacterId).FirstOrDefault().Connection, DungeonOpCodes.CHAT_MESSAGE, new
|
|
{
|
|
sender = "System",
|
|
message = message,
|
|
type = "system"
|
|
}, ct);
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// Broadcast a system message to all connected players
|
|
/// </summary>
|
|
private async Task BroadcastGlobalSystemMessage(string message, CancellationToken ct)
|
|
{
|
|
foreach (var session in _playerSessions.Values)
|
|
{
|
|
await SendAsync(session.Connection, DungeonOpCodes.CHAT_MESSAGE, new
|
|
{
|
|
sender = "System",
|
|
message = message,
|
|
type = "system"
|
|
}, ct);
|
|
}
|
|
}
|
|
|
|
|
|
}
|
|
|
|
// Request/Input DTOs
|
|
|
|
|
|
|