445 lines
15 KiB
C#
445 lines
15 KiB
C#
using DataServer.Data;
|
|
using DataServer.Data.Entities;
|
|
using GameServer.Dungeon;
|
|
using GameServer.Shared;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Server.Networking;
|
|
using Server.Networking.Messages;
|
|
|
|
namespace GameServer.World;
|
|
|
|
public sealed partial class WorldHandler
|
|
{
|
|
private sealed class WorldAttackRequest
|
|
{
|
|
public string TargetType { get; set; } = "mob"; // "mob" or "player"
|
|
public int? TargetMobId { get; set; }
|
|
public ulong? TargetPlayerId { get; set; }
|
|
}
|
|
|
|
private sealed class WorldMobLootRequest
|
|
{
|
|
public int MobId { get; set; }
|
|
}
|
|
|
|
private async Task HandleWorldAttackAsync(IConnection conn, WorldSessionState s, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
var req = WorldInputParser.Parse<WorldAttackRequest>(payload);
|
|
if (req == null) return;
|
|
|
|
var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ);
|
|
if (!_activeZones.TryGetValue(zoneKey, out var zoneSim)) return;
|
|
|
|
if (!zoneSim.Players.TryGetValue(s.CharacterId, out var attacker))
|
|
return;
|
|
|
|
if (!attacker.IsAlive || attacker.IsStunned)
|
|
{
|
|
await _broadcast.SendAsync(conn, OpCodes.WORLD_COMBAT_STATE, new
|
|
{
|
|
events = new[] { new { type = "AttackFailed", error = attacker.IsAlive ? "stunned" : "dead" } }
|
|
}, ct);
|
|
return;
|
|
}
|
|
|
|
if (req.TargetType == "mob" && req.TargetMobId.HasValue)
|
|
{
|
|
await HandleAttackMobAsync(conn, s, zoneSim, attacker, req.TargetMobId.Value, ct);
|
|
}
|
|
else if (req.TargetType == "player" && req.TargetPlayerId.HasValue)
|
|
{
|
|
await HandleAttackPlayerAsync(conn, s, zoneSim, attacker, req.TargetPlayerId.Value, ct);
|
|
}
|
|
}
|
|
|
|
private async Task HandleAttackMobAsync(
|
|
IConnection conn, WorldSessionState s,
|
|
WorldZoneSimulation zoneSim, WorldPlayerCombatState attacker,
|
|
int targetMobId, CancellationToken ct)
|
|
{
|
|
if (!zoneSim.Mobs.TryGetValue(targetMobId, out var mob) || !mob.IsAlive)
|
|
{
|
|
await _broadcast.SendAsync(conn, OpCodes.WORLD_COMBAT_STATE, new
|
|
{
|
|
events = new[] { new { type = "AttackFailed", error = "target_not_found" } }
|
|
}, ct);
|
|
return;
|
|
}
|
|
|
|
// Check range
|
|
float distance = MathF.Sqrt(MathF.Pow(mob.X - attacker.X, 2) + MathF.Pow(mob.Y - attacker.Y, 2));
|
|
if (distance > 80f) // ~2.5 tiles melee range
|
|
{
|
|
await _broadcast.SendAsync(conn, OpCodes.WORLD_COMBAT_STATE, new
|
|
{
|
|
events = new[] { new { type = "AttackFailed", error = "out_of_range" } }
|
|
}, ct);
|
|
return;
|
|
}
|
|
|
|
// Calculate damage
|
|
int baseDamage = Math.Max(1, attacker.Strength * 2 + 5); // Base melee damage formula
|
|
var result = CombatCalculator.CalculatePlayerToMobDamage(
|
|
attacker, mob, attacker.WeaponDamageTypeKey, baseDamage);
|
|
|
|
mob.Health -= result.FinalDamage;
|
|
attacker.IsInCombat = true;
|
|
attacker.LastCombatTick = zoneSim.CurrentTick;
|
|
|
|
// Alert mob to attacker
|
|
if (mob.TargetId == null)
|
|
{
|
|
mob.TargetId = attacker.CharacterId;
|
|
mob.State = MobState.Chasing;
|
|
}
|
|
|
|
var events = new List<object>
|
|
{
|
|
new
|
|
{
|
|
type = "PlayerAttack",
|
|
sourcePlayerId = attacker.CharacterId,
|
|
targetMobId = mob.Id,
|
|
damage = result.FinalDamage,
|
|
damageTypeKey = attacker.WeaponDamageTypeKey,
|
|
x = mob.X,
|
|
y = mob.Y,
|
|
wasResisted = result.WasResisted,
|
|
wasWeakness = result.WasWeakness
|
|
}
|
|
};
|
|
|
|
if (mob.Health <= 0)
|
|
{
|
|
mob.Health = 0;
|
|
mob.IsAlive = false;
|
|
mob.State = MobState.Dead;
|
|
mob.CurrentAnimation = mob.GetDirectionalAnimation("death");
|
|
zoneSim.MobSpawnTracker?.OnMobDied(mob.Id);
|
|
|
|
events.Add(new
|
|
{
|
|
type = "MobDeath",
|
|
targetMobId = mob.Id,
|
|
sourcePlayerId = attacker.CharacterId,
|
|
x = mob.X,
|
|
y = mob.Y,
|
|
xpReward = mob.Stats.XpReward,
|
|
lootAvailable = true
|
|
});
|
|
|
|
// Award XP
|
|
_ = AwardXpAsync(s.CharacterId, mob.Stats.XpReward);
|
|
}
|
|
|
|
// Broadcast attack event to all players in zone
|
|
foreach (var player in zoneSim.Players.Values)
|
|
{
|
|
await _broadcast.SendAsync(player.Session.Connection, OpCodes.WORLD_COMBAT_STATE, new { events }, ct);
|
|
}
|
|
}
|
|
|
|
private async Task HandleAttackPlayerAsync(
|
|
IConnection conn, WorldSessionState s,
|
|
WorldZoneSimulation zoneSim, WorldPlayerCombatState attacker,
|
|
ulong targetPlayerId, CancellationToken ct)
|
|
{
|
|
// Check PvP enabled
|
|
if (!zoneSim.IsPvpEnabled)
|
|
{
|
|
await _broadcast.SendAsync(conn, OpCodes.WORLD_COMBAT_STATE, new
|
|
{
|
|
events = new[] { new { type = "AttackFailed", error = "pvp_disabled_in_zone" } }
|
|
}, ct);
|
|
return;
|
|
}
|
|
|
|
if (!zoneSim.Players.TryGetValue(targetPlayerId, out var defender) || !defender.IsAlive)
|
|
{
|
|
await _broadcast.SendAsync(conn, OpCodes.WORLD_COMBAT_STATE, new
|
|
{
|
|
events = new[] { new { type = "AttackFailed", error = "target_not_found" } }
|
|
}, ct);
|
|
return;
|
|
}
|
|
|
|
if (defender.IsInvulnerable)
|
|
{
|
|
await _broadcast.SendAsync(conn, OpCodes.WORLD_COMBAT_STATE, new
|
|
{
|
|
events = new[] { new { type = "AttackFailed", error = "target_invulnerable" } }
|
|
}, ct);
|
|
return;
|
|
}
|
|
|
|
// Check range
|
|
float distance = MathF.Sqrt(MathF.Pow(defender.X - attacker.X, 2) + MathF.Pow(defender.Y - attacker.Y, 2));
|
|
if (distance > 80f)
|
|
{
|
|
await _broadcast.SendAsync(conn, OpCodes.WORLD_COMBAT_STATE, new
|
|
{
|
|
events = new[] { new { type = "AttackFailed", error = "out_of_range" } }
|
|
}, ct);
|
|
return;
|
|
}
|
|
|
|
// PvP damage (includes 30% PvP reduction from CombatCalculator)
|
|
int baseDamage = Math.Max(1, attacker.Strength * 2 + 5);
|
|
var result = CombatCalculator.CalculatePlayerToPlayerDamage(
|
|
attacker, defender, attacker.WeaponDamageTypeKey, baseDamage);
|
|
|
|
defender.Health -= result.FinalDamage;
|
|
attacker.IsInCombat = true;
|
|
attacker.LastCombatTick = zoneSim.CurrentTick;
|
|
defender.IsInCombat = true;
|
|
defender.LastCombatTick = zoneSim.CurrentTick;
|
|
|
|
var events = new List<object>
|
|
{
|
|
new
|
|
{
|
|
type = "PvpDamage",
|
|
sourcePlayerId = attacker.CharacterId,
|
|
targetPlayerId = defender.CharacterId,
|
|
damage = result.FinalDamage,
|
|
damageTypeKey = attacker.WeaponDamageTypeKey,
|
|
x = defender.X,
|
|
y = defender.Y
|
|
}
|
|
};
|
|
|
|
if (defender.Health <= 0)
|
|
{
|
|
defender.Health = 0;
|
|
defender.IsAlive = false;
|
|
|
|
events.Add(new
|
|
{
|
|
type = "PlayerDeath",
|
|
targetPlayerId = defender.CharacterId,
|
|
sourcePlayerId = attacker.CharacterId,
|
|
x = defender.X,
|
|
y = defender.Y,
|
|
isPvpKill = true
|
|
});
|
|
}
|
|
|
|
// Broadcast to all players in zone
|
|
foreach (var player in zoneSim.Players.Values)
|
|
{
|
|
await _broadcast.SendAsync(player.Session.Connection, OpCodes.WORLD_COMBAT_STATE, new { events }, ct);
|
|
}
|
|
}
|
|
|
|
private async Task HandleWorldMobLootAsync(IConnection conn, WorldSessionState s, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
var req = WorldInputParser.Parse<WorldMobLootRequest>(payload);
|
|
if (req == null) return;
|
|
|
|
var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ);
|
|
if (!_activeZones.TryGetValue(zoneKey, out var zoneSim)) return;
|
|
|
|
if (!zoneSim.Mobs.TryGetValue(req.MobId, out var mob))
|
|
{
|
|
await _broadcast.SendAsync(conn, OpCodes.WORLD_MOB_LOOT_RESULT, new
|
|
{
|
|
success = false,
|
|
error = "mob_not_found"
|
|
}, ct);
|
|
return;
|
|
}
|
|
|
|
if (mob.IsAlive)
|
|
{
|
|
await _broadcast.SendAsync(conn, OpCodes.WORLD_MOB_LOOT_RESULT, new
|
|
{
|
|
success = false,
|
|
error = "mob_still_alive"
|
|
}, ct);
|
|
return;
|
|
}
|
|
|
|
// Check distance
|
|
float distance = MathF.Sqrt(MathF.Pow(mob.X - s.X, 2) + MathF.Pow(mob.Y - s.Y, 2));
|
|
if (distance > 128f)
|
|
{
|
|
await _broadcast.SendAsync(conn, OpCodes.WORLD_MOB_LOOT_RESULT, new
|
|
{
|
|
success = false,
|
|
error = "too_far"
|
|
}, ct);
|
|
return;
|
|
}
|
|
|
|
// Generate loot from mob's definition loot table
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
|
|
if (!_mobDefinitions.TryGetValue(mob.DefinitionId, out var mobDef))
|
|
{
|
|
await _broadcast.SendAsync(conn, OpCodes.WORLD_MOB_LOOT_RESULT, new
|
|
{
|
|
success = true,
|
|
mobId = mob.Id,
|
|
items = Array.Empty<object>(),
|
|
gold = 0
|
|
}, ct);
|
|
return;
|
|
}
|
|
|
|
// Use LootService to generate loot from configured loot tables
|
|
var lootResult = _lootService.GenerateMobLoot(mob.DefinitionId, 1, 1.0f);
|
|
|
|
// Fallback gold if loot table has no gold: use XP-based formula
|
|
long goldDrop = lootResult.Gold > 0 ? lootResult.Gold : Math.Max(1, mob.Stats.XpReward / 2);
|
|
|
|
var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == s.CharacterId, ct);
|
|
if (character != null)
|
|
{
|
|
character.Gold += goldDrop;
|
|
|
|
// Add item drops to character inventory
|
|
foreach (var drop in lootResult.Items)
|
|
{
|
|
await AddWorldItemToInventoryAsync(db, s.CharacterId, drop.ItemDefinitionId, drop.Quantity, ct);
|
|
}
|
|
|
|
await db.SaveChangesAsync(ct);
|
|
}
|
|
|
|
// Mark mob as looted (it will be cleaned up eventually)
|
|
mob.LootEmptiedAtTick = zoneSim.CurrentTick;
|
|
|
|
var lootItems = lootResult.Items.Select(d => new
|
|
{
|
|
itemDefinitionId = d.ItemDefinitionId,
|
|
itemName = d.Item?.Name ?? $"Item {d.ItemDefinitionId}",
|
|
quantity = d.Quantity
|
|
}).ToArray();
|
|
|
|
await _broadcast.SendAsync(conn, OpCodes.WORLD_MOB_LOOT_RESULT, new
|
|
{
|
|
success = true,
|
|
mobId = mob.Id,
|
|
gold = goldDrop,
|
|
items = lootItems
|
|
}, ct);
|
|
}
|
|
|
|
private async Task HandleWorldRespawnAsync(IConnection conn, WorldSessionState s, CancellationToken ct)
|
|
{
|
|
var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ);
|
|
if (!_activeZones.TryGetValue(zoneKey, out var zoneSim)) return;
|
|
|
|
if (!zoneSim.Players.TryGetValue(s.CharacterId, out var playerCombat))
|
|
return;
|
|
|
|
// Must actually be dead to respawn
|
|
if (playerCombat.IsAlive)
|
|
{
|
|
await _broadcast.SendAsync(conn, OpCodes.WORLD_RESPAWN_RESULT, new
|
|
{
|
|
success = false,
|
|
error = "not_dead"
|
|
}, ct);
|
|
return;
|
|
}
|
|
|
|
// Respawn at zone center (tile center of chunk 0,0)
|
|
var region = await _cache.GetRegionAsync(s.RegionId, ct);
|
|
if (region == null) return;
|
|
|
|
float spawnX = WorldMovementService.WorldPxX(region, s.ZoneX, 0, region.ChunkWidthTiles / 2);
|
|
float spawnY = WorldMovementService.WorldPxY(region, s.ZoneY, 0, region.ChunkHeightTiles / 2);
|
|
|
|
// Reset combat state
|
|
playerCombat.Health = playerCombat.MaxHealth;
|
|
playerCombat.IsAlive = true;
|
|
playerCombat.IsInCombat = false;
|
|
playerCombat.IsInvulnerable = true;
|
|
playerCombat.InvulnerabilityTimer = RespawnInvulnerabilitySeconds;
|
|
playerCombat.StatusEffects.Clear();
|
|
|
|
// Move player to spawn position
|
|
s.X = spawnX;
|
|
s.Y = spawnY;
|
|
s.VelX = 0;
|
|
s.VelY = 0;
|
|
s.IsMoving = false;
|
|
|
|
// Update chunk position
|
|
var (pzX, pzY, pcX, pcY) = WorldMovementService.ToChunkPos(region, spawnX, spawnY);
|
|
s.ChunkX = pcX;
|
|
s.ChunkY = pcY;
|
|
|
|
// Increment death counter
|
|
_ = IncrementDeathCounterAsync(s.CharacterId);
|
|
|
|
await _broadcast.SendAsync(conn, OpCodes.WORLD_RESPAWN_RESULT, new
|
|
{
|
|
success = true,
|
|
x = spawnX,
|
|
y = spawnY,
|
|
health = playerCombat.Health,
|
|
maxHealth = playerCombat.MaxHealth,
|
|
invulnerableSeconds = RespawnInvulnerabilitySeconds
|
|
}, ct);
|
|
|
|
// Broadcast to other players
|
|
foreach (var player in zoneSim.Players.Values)
|
|
{
|
|
if (player.CharacterId == s.CharacterId) continue;
|
|
await _broadcast.SendAsync(player.Session.Connection, OpCodes.WORLD_COMBAT_STATE, new
|
|
{
|
|
events = new[] { new
|
|
{
|
|
type = "PlayerRespawn",
|
|
targetPlayerId = s.CharacterId,
|
|
x = spawnX,
|
|
y = spawnY
|
|
}}
|
|
}, ct);
|
|
}
|
|
}
|
|
|
|
private async Task IncrementDeathCounterAsync(ulong characterId)
|
|
{
|
|
try
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == characterId);
|
|
if (character != null)
|
|
{
|
|
character.TotalDeaths++;
|
|
await db.SaveChangesAsync();
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_log.LogWarning(ex, "Failed to increment death counter for character {CharacterId}", characterId);
|
|
}
|
|
}
|
|
|
|
private async Task AwardXpAsync(ulong characterId, int xpAmount)
|
|
{
|
|
if (xpAmount <= 0) return;
|
|
|
|
try
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
|
var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == characterId);
|
|
if (character == null) return;
|
|
|
|
character.Experience += xpAmount;
|
|
await db.SaveChangesAsync();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_log.LogWarning(ex, "Failed to award XP to character {CharacterId}", characterId);
|
|
}
|
|
}
|
|
}
|