World changes

This commit is contained in:
dingo
2026-02-17 11:18:55 -05:00
parent cae32f6157
commit 14d74fa9ce
23 changed files with 3029 additions and 157 deletions
+7
View File
@@ -0,0 +1,7 @@
{
"permissions": {
"allow": [
"Bash(dotnet build:*)"
]
}
}
+49 -3
View File
@@ -1,4 +1,5 @@
using DataServer.Data.Entities;
using GameServer.Shared;
namespace GameServer.Dungeon;
@@ -11,7 +12,7 @@ public static class CombatCalculator
/// Calculate damage dealt from player to mob
/// </summary>
public static DamageResult CalculatePlayerToMobDamage(
PlayerInstance player,
IPlayerTarget player,
MobInstance mob,
string damageTypeKey,
int baseDamage)
@@ -70,7 +71,7 @@ public static class CombatCalculator
/// </summary>
public static DamageResult CalculateMobToPlayerDamage(
MobInstance mob,
PlayerInstance player,
IPlayerTarget player,
string damageTypeKey,
int baseDamage,
Dictionary<string, float> playerTotalResistances)
@@ -148,7 +149,7 @@ public static class CombatCalculator
/// Calculate player weapon damage range
/// </summary>
public static (int min, int max, string damageTypeKey) GetPlayerWeaponDamage(
PlayerInstance player,
IPlayerTarget player,
DungeonItemDefinition? weapon)
{
if (weapon == null)
@@ -191,6 +192,51 @@ public static class CombatCalculator
return (true, null);
}
/// <summary>
/// Calculate damage dealt from player to player (PvP)
/// </summary>
public static DamageResult CalculatePlayerToPlayerDamage(
IPlayerTarget attacker,
IPlayerTarget defender,
string damageTypeKey,
int baseDamage)
{
// 1. Base damage modified by attacker stats
float damage = baseDamage;
if (damageTypeKey == "physical")
damage *= 1 + (attacker.Strength * 0.05f);
else
damage *= 1 + (attacker.Intelligence * 0.05f);
// 2. Apply defender armor
float armorMitigation = defender.Armor / (float)(defender.Armor + 100);
damage *= (1 - armorMitigation);
// 3. Apply defender resistances (capped at 75%)
float defenderResist = 0f;
if (defender.Resistances.TryGetValue(damageTypeKey, out float resist))
defenderResist = Math.Min(resist, 0.75f);
if (defenderResist != 0)
damage *= (1 - defenderResist);
// 4. Endurance reduction (capped at 50%)
float enduranceReduction = Math.Min(defender.Endurance / (float)(defender.Endurance + 100), 0.50f);
damage *= (1.0f - enduranceReduction);
// 5. PvP damage reduction (30% global reduction to make fights last longer)
damage *= 0.7f;
int finalDamage = Math.Max(1, (int)damage);
return new DamageResult
{
FinalDamage = finalDamage,
WasResisted = defenderResist > 0,
WasWeakness = defenderResist < 0,
DamageTypeKey = damageTypeKey
};
}
}
public class DamageResult
+10 -1
View File
@@ -2,13 +2,14 @@ using System.Collections.Concurrent;
using System.Text.Json;
using DataServer.Data.Entities;
using DataServer.Data.Enums;
using GameServer.Shared;
namespace GameServer.Dungeon;
/// <summary>
/// Runtime simulation for an active dungeon instance
/// </summary>
public partial class DungeonSimulation
public partial class DungeonSimulation : ICombatEnvironment
{
public DungeonLayout Layout { get; }
public int Tier { get; }
@@ -1887,6 +1888,14 @@ public partial class DungeonSimulation
_pendingSummons.Add((mobDefinitionId, x, y, tier));
}
// ---- ICombatEnvironment implementation ----
IEnumerable<IPlayerTarget> ICombatEnvironment.GetAlivePlayers()
=> Players.Values.Where(p => p.IsAlive);
IPlayerTarget? ICombatEnvironment.GetPlayer(ulong characterId)
=> Players.TryGetValue(characterId, out var p) ? p : null;
public int AllocateRuntimeMobId()
{
lock (_mobIdLock)
+93 -94
View File
@@ -1,5 +1,6 @@
using DataServer.Data.Entities;
using DataServer.Data.Enums;
using GameServer.Shared;
namespace GameServer.Dungeon;
@@ -13,7 +14,7 @@ public static class MobAI
/// <summary>
/// Main AI update - called each tick for each mob
/// </summary>
public static void UpdateMob(MobInstance mob, DungeonSimulation sim, float deltaTime)
public static void UpdateMob(MobInstance mob, ICombatEnvironment env, float deltaTime)
{
if (!mob.IsAlive || mob.IsStunned) return;
@@ -21,7 +22,7 @@ public static class MobAI
UpdateCooldowns(mob, deltaTime);
// Update status effects
UpdateStatusEffects(mob, sim, deltaTime);
UpdateStatusEffects(mob, env, deltaTime);
// Check for phase transitions (for bosses)
CheckPhaseTransition(mob);
@@ -35,7 +36,7 @@ public static class MobAI
mob.CastTimeRemaining -= deltaTime;
if (mob.CastTimeRemaining <= 0)
{
ExecuteAbility(mob, mob.CastingAbility, sim);
ExecuteAbility(mob, mob.CastingAbility, env);
mob.CastingAbility = null;
mob.State = MobState.Idle;
mob.StateTime = 0;
@@ -47,37 +48,37 @@ public static class MobAI
switch (mob.Behavior)
{
case MobBehavior.Aggressive:
UpdateAggressive(mob, sim, deltaTime);
UpdateAggressive(mob, env, deltaTime);
break;
case MobBehavior.Defensive:
UpdateDefensive(mob, sim, deltaTime);
UpdateDefensive(mob, env, deltaTime);
break;
case MobBehavior.Ranged:
UpdateRanged(mob, sim, deltaTime);
UpdateRanged(mob, env, deltaTime);
break;
case MobBehavior.Skirmisher:
UpdateSkirmisher(mob, sim, deltaTime);
UpdateSkirmisher(mob, env, deltaTime);
break;
case MobBehavior.Tank:
UpdateTank(mob, sim, deltaTime);
UpdateTank(mob, env, deltaTime);
break;
case MobBehavior.Assassin:
UpdateAssassin(mob, sim, deltaTime);
UpdateAssassin(mob, env, deltaTime);
break;
case MobBehavior.Healer:
UpdateHealer(mob, sim, deltaTime);
UpdateHealer(mob, env, deltaTime);
break;
case MobBehavior.Patrol:
UpdatePatrol(mob, sim, deltaTime);
UpdatePatrol(mob, env, deltaTime);
break;
case MobBehavior.Pack:
UpdatePack(mob, sim, deltaTime);
UpdatePack(mob, env, deltaTime);
break;
case MobBehavior.Summoner:
UpdateSummoner(mob, sim, deltaTime);
UpdateSummoner(mob, env, deltaTime);
break;
default:
UpdateAggressive(mob, sim, deltaTime);
UpdateAggressive(mob, env, deltaTime);
break;
}
}
@@ -87,14 +88,14 @@ public static class MobAI
/// <summary>
/// Aggressive: Charges player on sight, melee attacks. Wanders when idle.
/// </summary>
private static void UpdateAggressive(MobInstance mob, DungeonSimulation sim, float deltaTime)
private static void UpdateAggressive(MobInstance mob, ICombatEnvironment env, float deltaTime)
{
var target = FindNearestPlayer(mob, sim);
var target = FindNearestPlayer(mob, env);
if (target == null)
{
// No target - wander or return to spawn area
UpdateIdleWander(mob, sim, deltaTime);
UpdateIdleWander(mob, env, deltaTime);
return;
}
@@ -104,7 +105,7 @@ public static class MobAI
// Check leash range
if (distFromSpawn > mob.Stats.LeashRange)
{
ReturnToSpawn(mob, sim, deltaTime);
ReturnToSpawn(mob, env, deltaTime);
return;
}
@@ -125,16 +126,16 @@ public static class MobAI
// Chase
mob.State = MobState.Chasing;
mob.CurrentAnimation = mob.GetDirectionalAnimation("walk");
MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, sim);
MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, env);
}
}
/// <summary>
/// Defensive: Only attacks if player comes close to spawn. Wanders near spawn.
/// </summary>
private static void UpdateDefensive(MobInstance mob, DungeonSimulation sim, float deltaTime)
private static void UpdateDefensive(MobInstance mob, ICombatEnvironment env, float deltaTime)
{
var target = FindNearestPlayer(mob, sim);
var target = FindNearestPlayer(mob, env);
float distFromSpawn = GetDistance(mob.X, mob.Y, mob.SpawnX, mob.SpawnY);
if (target != null)
@@ -148,7 +149,7 @@ public static class MobAI
// Don't stray too far from spawn
if (distFromSpawn > mob.Stats.LeashRange * 0.5f)
{
ReturnToSpawn(mob, sim, deltaTime);
ReturnToSpawn(mob, env, deltaTime);
return;
}
@@ -164,7 +165,7 @@ public static class MobAI
else
{
mob.State = MobState.Chasing;
MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * 0.7f * deltaTime, sim);
MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * 0.7f * deltaTime, env);
}
return;
}
@@ -172,19 +173,19 @@ public static class MobAI
// No threat - wander near spawn
mob.TargetId = null;
UpdateIdleWander(mob, sim, deltaTime, wanderRadius: 80f);
UpdateIdleWander(mob, env, deltaTime, wanderRadius: 80f);
}
/// <summary>
/// Ranged: Keeps distance, fires projectiles
/// </summary>
private static void UpdateRanged(MobInstance mob, DungeonSimulation sim, float deltaTime)
private static void UpdateRanged(MobInstance mob, ICombatEnvironment env, float deltaTime)
{
var target = FindNearestPlayer(mob, sim);
var target = FindNearestPlayer(mob, env);
if (target == null)
{
UpdateIdleWander(mob, sim, deltaTime);
UpdateIdleWander(mob, env, deltaTime);
return;
}
@@ -193,7 +194,7 @@ public static class MobAI
if (distFromSpawn > mob.Stats.LeashRange)
{
ReturnToSpawn(mob, sim, deltaTime);
ReturnToSpawn(mob, env, deltaTime);
return;
}
@@ -209,14 +210,14 @@ public static class MobAI
// Too close, back up
mob.State = MobState.Kiting;
mob.CurrentAnimation = mob.GetDirectionalAnimation("walk");
MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, sim);
MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, env);
}
else if (distance > preferredRange * 1.3f && distance <= mob.Stats.LeashRange)
{
// Too far, move closer
mob.State = MobState.Chasing;
mob.CurrentAnimation = mob.GetDirectionalAnimation("walk");
MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, sim);
MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, env);
}
else
{
@@ -229,13 +230,13 @@ public static class MobAI
/// <summary>
/// Skirmisher: Hit-and-run tactics
/// </summary>
private static void UpdateSkirmisher(MobInstance mob, DungeonSimulation sim, float deltaTime)
private static void UpdateSkirmisher(MobInstance mob, ICombatEnvironment env, float deltaTime)
{
var target = FindNearestPlayer(mob, sim);
var target = FindNearestPlayer(mob, env);
if (target == null)
{
UpdateIdleWander(mob, sim, deltaTime);
UpdateIdleWander(mob, env, deltaTime);
return;
}
@@ -247,13 +248,13 @@ public static class MobAI
{
mob.State = MobState.Fleeing;
mob.CurrentAnimation = mob.GetDirectionalAnimation("walk");
MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * 1.3f * deltaTime, sim);
MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * 1.3f * deltaTime, env);
return;
}
if (distFromSpawn > mob.Stats.LeashRange)
{
ReturnToSpawn(mob, sim, deltaTime);
ReturnToSpawn(mob, env, deltaTime);
return;
}
@@ -274,7 +275,7 @@ public static class MobAI
else
{
mob.State = MobState.Chasing;
MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * 1.2f * deltaTime, sim);
MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * 1.2f * deltaTime, env);
}
}
else
@@ -282,20 +283,20 @@ public static class MobAI
// Retreat phase
mob.State = MobState.Kiting;
mob.CurrentAnimation = mob.GetDirectionalAnimation("walk");
MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, sim);
MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, env);
}
}
/// <summary>
/// Tank: Slow but tough, always moves toward target
/// </summary>
private static void UpdateTank(MobInstance mob, DungeonSimulation sim, float deltaTime)
private static void UpdateTank(MobInstance mob, ICombatEnvironment env, float deltaTime)
{
var target = FindNearestPlayer(mob, sim);
var target = FindNearestPlayer(mob, env);
if (target == null)
{
UpdateIdleWander(mob, sim, deltaTime, wanderRadius: 50f);
UpdateIdleWander(mob, env, deltaTime, wanderRadius: 50f);
return;
}
@@ -304,7 +305,7 @@ public static class MobAI
if (distFromSpawn > mob.Stats.LeashRange)
{
ReturnToSpawn(mob, sim, deltaTime);
ReturnToSpawn(mob, env, deltaTime);
return;
}
@@ -322,25 +323,24 @@ public static class MobAI
mob.State = MobState.Chasing;
mob.CurrentAnimation = mob.GetDirectionalAnimation("walk");
// Tanks move at 60% speed
MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * 0.6f * deltaTime, sim);
MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * 0.6f * deltaTime, env);
}
}
/// <summary>
/// Assassin: Targets lowest HP player, moves fast
/// </summary>
private static void UpdateAssassin(MobInstance mob, DungeonSimulation sim, float deltaTime)
private static void UpdateAssassin(MobInstance mob, ICombatEnvironment env, float deltaTime)
{
// Target lowest HP player
var target = sim.Players.Values
.Where(p => p.IsAlive)
var target = env.GetAlivePlayers()
.Where(p => GetDistance(mob.X, mob.Y, p.X, p.Y) <= mob.Stats.AggroRange)
.OrderBy(p => p.Health / p.MaxHealth)
.FirstOrDefault();
if (target == null)
{
UpdateIdleWander(mob, sim, deltaTime);
UpdateIdleWander(mob, env, deltaTime);
return;
}
@@ -349,7 +349,7 @@ public static class MobAI
if (distFromSpawn > mob.Stats.LeashRange)
{
ReturnToSpawn(mob, sim, deltaTime);
ReturnToSpawn(mob, env, deltaTime);
return;
}
@@ -366,17 +366,17 @@ public static class MobAI
mob.State = MobState.Chasing;
mob.CurrentAnimation = mob.GetDirectionalAnimation("walk");
// Assassins move at 130% speed
MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * 1.3f * deltaTime, sim);
MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * 1.3f * deltaTime, env);
}
}
/// <summary>
/// Healer: Heals nearby mobs, stays back from combat
/// </summary>
private static void UpdateHealer(MobInstance mob, DungeonSimulation sim, float deltaTime)
private static void UpdateHealer(MobInstance mob, ICombatEnvironment env, float deltaTime)
{
// Check for injured allies first
var injuredAlly = sim.Mobs.Values
var injuredAlly = env.Mobs.Values
.Where(m => m.IsAlive && m.Id != mob.Id)
.Where(m => GetDistance(mob.X, mob.Y, m.X, m.Y) <= 150f)
.Where(m => m.HpPercent < 0.7f)
@@ -402,7 +402,7 @@ public static class MobAI
}
// Otherwise, stay back from combat
var target = FindNearestPlayer(mob, sim);
var target = FindNearestPlayer(mob, env);
if (target != null)
{
float distance = GetDistance(mob.X, mob.Y, target.X, target.Y);
@@ -411,7 +411,7 @@ public static class MobAI
if (distance < preferredRange)
{
mob.State = MobState.Kiting;
MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, sim);
MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, env);
}
else if (distance <= mob.Stats.AttackRange)
{
@@ -420,69 +420,69 @@ public static class MobAI
}
else
{
UpdateIdleWander(mob, sim, deltaTime);
UpdateIdleWander(mob, env, deltaTime);
}
}
/// <summary>
/// Patrol: Walks a path, alerts others when seeing players
/// </summary>
private static void UpdatePatrol(MobInstance mob, DungeonSimulation sim, float deltaTime)
private static void UpdatePatrol(MobInstance mob, ICombatEnvironment env, float deltaTime)
{
var target = FindNearestPlayer(mob, sim);
var target = FindNearestPlayer(mob, env);
if (target != null)
{
// Alert nearby mobs
if (!mob.HasCalledForHelp)
{
CallForHelp(mob, sim);
CallForHelp(mob, env);
}
// Then fight like aggressive
UpdateAggressive(mob, sim, deltaTime);
UpdateAggressive(mob, env, deltaTime);
}
else
{
mob.HasCalledForHelp = false;
// Patrol - wander in a larger area
UpdateIdleWander(mob, sim, deltaTime, wanderRadius: 150f);
UpdateIdleWander(mob, env, deltaTime, wanderRadius: 150f);
}
}
/// <summary>
/// Pack: Calls nearby mobs when engaged
/// </summary>
private static void UpdatePack(MobInstance mob, DungeonSimulation sim, float deltaTime)
private static void UpdatePack(MobInstance mob, ICombatEnvironment env, float deltaTime)
{
var target = FindNearestPlayer(mob, sim);
var target = FindNearestPlayer(mob, env);
if (target != null)
{
if (!mob.HasCalledForHelp)
{
CallForHelp(mob, sim);
CallForHelp(mob, env);
}
UpdateAggressive(mob, sim, deltaTime);
UpdateAggressive(mob, env, deltaTime);
}
else
{
mob.HasCalledForHelp = false;
UpdateIdleWander(mob, sim, deltaTime);
UpdateIdleWander(mob, env, deltaTime);
}
}
/// <summary>
/// Summoner: Stays back and summons minions
/// </summary>
private static void UpdateSummoner(MobInstance mob, DungeonSimulation sim, float deltaTime)
private static void UpdateSummoner(MobInstance mob, ICombatEnvironment env, float deltaTime)
{
var target = FindNearestPlayer(mob, sim);
var target = FindNearestPlayer(mob, env);
if (target == null)
{
UpdateIdleWander(mob, sim, deltaTime);
UpdateIdleWander(mob, env, deltaTime);
return;
}
@@ -512,7 +512,7 @@ public static class MobAI
if (distance < preferredRange * 0.5f)
{
mob.State = MobState.Kiting;
MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, sim);
MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, env);
}
else
{
@@ -528,7 +528,7 @@ public static class MobAI
/// <summary>
/// Wander around spawn area when no targets
/// </summary>
private static void UpdateIdleWander(MobInstance mob, DungeonSimulation sim, float deltaTime, float wanderRadius = 0f)
private static void UpdateIdleWander(MobInstance mob, ICombatEnvironment env, float deltaTime, float wanderRadius = 0f)
{
// Use leash range if no wander radius specified
if (wanderRadius <= 0)
@@ -539,7 +539,7 @@ public static class MobAI
// Too far from spawn? Return first
if (distFromSpawn > wanderRadius)
{
ReturnToSpawn(mob, sim, deltaTime);
ReturnToSpawn(mob, env, deltaTime);
return;
}
@@ -572,7 +572,7 @@ public static class MobAI
float targetY = mob.SpawnY + MathF.Sin(angle) * dist;
// Check if target is walkable
if (sim.CanActorMoveTo(targetX, targetY))
if (env.CanActorMoveTo(targetX, targetY))
{
mob.WanderTargetX = targetX;
mob.WanderTargetY = targetY;
@@ -610,12 +610,12 @@ public static class MobAI
// Keep moving toward target (30% speed for casual wandering)
mob.UpdateFacingDirection(mob.WanderTargetX, mob.WanderTargetY);
mob.CurrentAnimation = mob.GetDirectionalAnimation("walk");
MoveToward(mob, mob.WanderTargetX, mob.WanderTargetY, mob.Stats.MoveSpeed * 0.3f * deltaTime, sim);
MoveToward(mob, mob.WanderTargetX, mob.WanderTargetY, mob.Stats.MoveSpeed * 0.3f * deltaTime, env);
}
}
}
private static void ReturnToSpawn(MobInstance mob, DungeonSimulation sim, float deltaTime)
private static void ReturnToSpawn(MobInstance mob, ICombatEnvironment env, float deltaTime)
{
float dist = GetDistance(mob.X, mob.Y, mob.SpawnX, mob.SpawnY);
@@ -636,7 +636,7 @@ public static class MobAI
mob.TargetId = null;
mob.UpdateFacingDirection(mob.SpawnX, mob.SpawnY);
mob.CurrentAnimation = mob.GetDirectionalAnimation("walk");
MoveToward(mob, mob.SpawnX, mob.SpawnY, mob.Stats.MoveSpeed * deltaTime, sim);
MoveToward(mob, mob.SpawnX, mob.SpawnY, mob.Stats.MoveSpeed * deltaTime, env);
// Heal while returning
if (mob.Health < mob.MaxHealth)
@@ -650,12 +650,12 @@ public static class MobAI
}
}
private static void CallForHelp(MobInstance mob, DungeonSimulation sim)
private static void CallForHelp(MobInstance mob, ICombatEnvironment env)
{
mob.HasCalledForHelp = true;
float helpRadius = mob.Stats.AggroRange * 1.5f;
foreach (var ally in sim.Mobs.Values.Where(m => m.IsAlive && m.Id != mob.Id))
foreach (var ally in env.Mobs.Values.Where(m => m.IsAlive && m.Id != mob.Id))
{
if (GetDistance(mob.X, mob.Y, ally.X, ally.Y) <= helpRadius)
{
@@ -673,7 +673,7 @@ public static class MobAI
#region Movement with Collision
private static void MoveToward(MobInstance mob, float targetX, float targetY, float speed, DungeonSimulation sim)
private static void MoveToward(MobInstance mob, float targetX, float targetY, float speed, ICombatEnvironment env)
{
if (mob.IsRooted) return;
@@ -693,7 +693,7 @@ public static class MobAI
float newY = mob.Y + moveY;
// Check collision for each axis separately
if (sim.CanActorMoveTo(newX, mob.Y))
if (env.CanActorMoveTo(newX, mob.Y))
{
mob.X = newX;
}
@@ -703,7 +703,7 @@ public static class MobAI
mob.StuckTime += 0.05f;
}
if (sim.CanActorMoveTo(mob.X, newY))
if (env.CanActorMoveTo(mob.X, newY))
{
mob.Y = newY;
}
@@ -715,12 +715,12 @@ public static class MobAI
// If stuck for too long, try to unstick
if (mob.StuckTime > 1f)
{
TryUnstick(mob, sim);
TryUnstick(mob, env);
mob.StuckTime = 0;
}
}
private static void MoveAwayFrom(MobInstance mob, float targetX, float targetY, float speed, DungeonSimulation sim)
private static void MoveAwayFrom(MobInstance mob, float targetX, float targetY, float speed, ICombatEnvironment env)
{
if (mob.IsRooted) return;
@@ -736,25 +736,25 @@ public static class MobAI
float newX = mob.X + moveX;
float newY = mob.Y + moveY;
if (sim.CanActorMoveTo(newX, mob.Y))
if (env.CanActorMoveTo(newX, mob.Y))
{
mob.X = newX;
}
if (sim.CanActorMoveTo(mob.X, newY))
if (env.CanActorMoveTo(mob.X, newY))
{
mob.Y = newY;
}
}
private static void TryUnstick(MobInstance mob, DungeonSimulation sim)
private static void TryUnstick(MobInstance mob, ICombatEnvironment env)
{
// Try moving in cardinal directions to get unstuck
float[] offsets = { 16, -16 };
foreach (float ox in offsets)
{
if (sim.CanActorMoveTo(mob.X + ox, mob.Y))
if (env.CanActorMoveTo(mob.X + ox, mob.Y))
{
mob.X += ox * 0.5f;
return;
@@ -763,7 +763,7 @@ public static class MobAI
foreach (float oy in offsets)
{
if (sim.CanActorMoveTo(mob.X, mob.Y + oy))
if (env.CanActorMoveTo(mob.X, mob.Y + oy))
{
mob.Y += oy * 0.5f;
return;
@@ -775,7 +775,7 @@ public static class MobAI
#region Ability System
private static void ExecuteAbility(MobInstance mob, MobAbilityState ability, DungeonSimulation sim)
private static void ExecuteAbility(MobInstance mob, MobAbilityState ability, ICombatEnvironment env)
{
ability.CooldownRemaining = ability.Definition.Cooldown;
mob.Mana -= ability.Definition.ManaCost;
@@ -786,7 +786,7 @@ public static class MobAI
{
case MobAbilityType.SummonSingle:
case MobAbilityType.SummonBulk:
ExecuteSummon(mob, ability, sim);
ExecuteSummon(mob, ability, env);
break;
// TODO: Implement other ability types
@@ -796,7 +796,7 @@ public static class MobAI
}
}
private static void ExecuteSummon(MobInstance mob, MobAbilityState ability, DungeonSimulation sim)
private static void ExecuteSummon(MobInstance mob, MobAbilityState ability, ICombatEnvironment env)
{
if (!ability.Definition.SummonMobId.HasValue)
{
@@ -819,7 +819,7 @@ public static class MobAI
float spawnY = mob.Y + (float)Math.Sin(angle) * summonDistance;
// Make sure spawn position is walkable
if (!sim.CanActorMoveTo(spawnX, spawnY))
if (!env.CanActorMoveTo(spawnX, spawnY))
{
// Try closer
spawnX = mob.X + (float)Math.Cos(angle) * (summonDistance * 0.5f);
@@ -827,7 +827,7 @@ public static class MobAI
}
// Request mob spawn (this will be handled by DungeonSimulation)
sim.RequestMobSummon(summonMobId, spawnX, spawnY, sim.Tier);
env.RequestMobSummon(summonMobId, spawnX, spawnY, env.Tier);
}
}
@@ -844,7 +844,7 @@ public static class MobAI
}
}
private static void UpdateStatusEffects(MobInstance mob, DungeonSimulation sim, float deltaTime)
private static void UpdateStatusEffects(MobInstance mob, ICombatEnvironment env, float deltaTime)
{
var expired = new List<MobStatusEffect>();
@@ -898,10 +898,9 @@ public static class MobAI
}
}
private static PlayerInstance? FindNearestPlayer(MobInstance mob, DungeonSimulation sim)
private static IPlayerTarget? FindNearestPlayer(MobInstance mob, ICombatEnvironment env)
{
return sim.Players.Values
.Where(p => p.IsAlive)
return env.GetAlivePlayers()
.Where(p => GetDistance(mob.X, mob.Y, p.X, p.Y) <= mob.Stats.AggroRange)
.OrderBy(p => GetDistance(mob.X, mob.Y, p.X, p.Y))
.FirstOrDefault();
+3 -1
View File
@@ -1,9 +1,11 @@
using GameServer.Shared;
namespace GameServer.Dungeon;
/// <summary>
/// Runtime instance of a player in a dungeon
/// </summary>
public class PlayerInstance
public class PlayerInstance : IPlayerTarget
{
public ulong CharacterId { get; set; }
public string CharacterName { get; set; } = "";
+40
View File
@@ -0,0 +1,40 @@
using System.Collections.Concurrent;
using GameServer.Dungeon;
namespace GameServer.Shared;
/// <summary>
/// Abstraction over the spatial/entity environment that MobAI and combat systems need.
/// Implemented by both DungeonSimulation (dungeons) and WorldZoneSimulation (overworld).
/// </summary>
public interface ICombatEnvironment
{
// ---- Spatial ----
/// <summary>Check if an actor-sized entity can move to the given world-pixel position.</summary>
bool CanActorMoveTo(float x, float y);
// ---- Entity lookups ----
/// <summary>All alive players in this environment.</summary>
IEnumerable<IPlayerTarget> GetAlivePlayers();
/// <summary>All alive mobs in this environment.</summary>
ConcurrentDictionary<int, MobInstance> Mobs { get; }
/// <summary>Get a specific player by character ID.</summary>
IPlayerTarget? GetPlayer(ulong characterId);
// ---- Mob summoning ----
/// <summary>Request spawning a new mob (summoner ability).</summary>
void RequestMobSummon(int mobDefinitionId, float x, float y, int tier);
// ---- Context ----
/// <summary>The tier/difficulty level of this environment (dungeon tier or world zone level).</summary>
int Tier { get; }
/// <summary>Current simulation tick.</summary>
long CurrentTick { get; }
}
+43
View File
@@ -0,0 +1,43 @@
using GameServer.Dungeon;
namespace GameServer.Shared;
/// <summary>
/// Interface for player combat state, implemented by both dungeon PlayerInstance
/// and world WorldPlayerCombatState. Provides the combat-relevant surface that
/// MobAI and CombatCalculator need.
/// </summary>
public interface IPlayerTarget
{
ulong CharacterId { get; }
string CharacterName { get; }
// Position
float X { get; }
float Y { get; }
// Vitals
float Health { get; set; }
float MaxHealth { get; }
bool IsAlive { get; set; }
bool IsInvulnerable { get; }
// Combat stats
int Strength { get; }
int Intelligence { get; }
int Endurance { get; }
int Dexterity { get; }
int Armor { get; }
string WeaponDamageTypeKey { get; }
Dictionary<string, float> Resistances { get; }
// Status effects
List<PlayerStatusEffect> StatusEffects { get; }
bool IsStunned { get; }
bool IsRooted { get; }
bool IsFeared { get; }
// Combat tracking
bool IsInCombat { get; set; }
long LastCombatTick { get; set; }
}
+14 -10
View File
@@ -44,12 +44,12 @@ public sealed class WorldBroadcastService
var zy = ay / region.ChunksPerZoneY;
var cx = ax % region.ChunksPerZoneX;
var cy = ay % region.ChunksPerZoneY;
var key = $"{region.Id}:{zx}:{zy}:{cx}:{cy}";
var key = WorldChunkCache.ChunkKey(region.Id, zx, zy, s.ZoneZ, cx, cy);
required.Add(key);
if (!s.ChunkVersions.ContainsKey(key))
{
var cached = await _cache.GetChunkAsync(region.Id, zx, zy, cx, cy, ct);
var cached = await _cache.GetChunkAsync(region.Id, zx, zy, s.ZoneZ, cx, cy, ct);
s.ChunkVersions[key] = cached?.Version ?? 0;
if (cached != null)
{
@@ -82,15 +82,19 @@ public sealed class WorldBroadcastService
{
s.ChunkVersions.Remove(stale);
var p = stale.Split(':');
list.Add(("chunk_unload", new
if (p.Length >= 6)
{
type = "chunk_unload",
regionId = int.Parse(p[0]),
zoneX = int.Parse(p[1]),
zoneY = int.Parse(p[2]),
chunkX = int.Parse(p[3]),
chunkY = int.Parse(p[4])
}));
list.Add(("chunk_unload", new
{
type = "chunk_unload",
regionId = int.Parse(p[0]),
zoneX = int.Parse(p[1]),
zoneY = int.Parse(p[2]),
zoneZ = int.Parse(p[3]),
chunkX = int.Parse(p[4]),
chunkY = int.Parse(p[5])
}));
}
}
return list;
}
+34 -24
View File
@@ -45,6 +45,7 @@ public sealed class WorldChunkCache
public int RegionId { get; init; }
public int ZoneX { get; init; }
public int ZoneY { get; init; }
public int ZoneZ { get; init; }
public int ChunkX { get; init; }
public int ChunkY { get; init; }
public int WidthTiles { get; init; }
@@ -136,9 +137,9 @@ public sealed class WorldChunkCache
return cached;
}
public async ValueTask<CachedChunk?> GetChunkAsync(int regionId, int zoneX, int zoneY, int chunkX, int chunkY, CancellationToken ct = default)
public async ValueTask<CachedChunk?> GetChunkAsync(int regionId, int zoneX, int zoneY, int zoneZ, int chunkX, int chunkY, CancellationToken ct = default)
{
var key = ChunkKey(regionId, zoneX, zoneY, chunkX, chunkY);
var key = ChunkKey(regionId, zoneX, zoneY, zoneZ, chunkX, chunkY);
if (_chunks.TryGetValue(key, out var cached))
return cached;
@@ -150,7 +151,7 @@ public sealed class WorldChunkCache
if (_chunks.TryGetValue(key, out cached))
return cached;
cached = await LoadChunkFromDbAsync(regionId, zoneX, zoneY, chunkX, chunkY, ct);
cached = await LoadChunkFromDbAsync(regionId, zoneX, zoneY, zoneZ, chunkX, chunkY, ct);
_chunks[key] = cached;
return cached;
}
@@ -160,7 +161,7 @@ public sealed class WorldChunkCache
}
}
public bool IsTileWalkable(CachedRegion region, float wx, float wy, bool isVip)
public bool IsTileWalkable(CachedRegion region, int zoneZ, float wx, float wy, bool isVip)
{
var gx = (int)MathF.Floor(wx / TileSize);
var gy = (int)MathF.Floor(wy / TileSize);
@@ -181,7 +182,7 @@ public sealed class WorldChunkCache
var tx = lzx % region.ChunkWidthTiles;
var ty = lzy % region.ChunkHeightTiles;
var key = ChunkKey(region.Id, zx, zy, cx, cy);
var key = ChunkKey(region.Id, zx, zy, zoneZ, cx, cy);
if (!_chunks.TryGetValue(key, out var chunk) || chunk == null) return true;
var idx = (ty * chunk.WidthTiles) + tx;
@@ -192,17 +193,17 @@ public sealed class WorldChunkCache
return true;
}
public bool IsPositionWalkable(CachedRegion region, float wx, float wy, bool isVip)
public bool IsPositionWalkable(CachedRegion region, int zoneZ, float wx, float wy, bool isVip)
{
if (!IsTileWalkable(region, wx, wy, isVip)) return false;
if (!IsTileWalkable(region, wx + 8f, wy, isVip)) return false;
if (!IsTileWalkable(region, wx - 8f, wy, isVip)) return false;
if (!IsTileWalkable(region, wx, wy + 8f, isVip)) return false;
if (!IsTileWalkable(region, wx, wy - 8f, isVip)) return false;
if (!IsTileWalkable(region, zoneZ, wx, wy, isVip)) return false;
if (!IsTileWalkable(region, zoneZ, wx + 8f, wy, isVip)) return false;
if (!IsTileWalkable(region, zoneZ, wx - 8f, wy, isVip)) return false;
if (!IsTileWalkable(region, zoneZ, wx, wy + 8f, isVip)) return false;
if (!IsTileWalkable(region, zoneZ, wx, wy - 8f, isVip)) return false;
return true;
}
public CachedPortalObject? FindPortalAtPosition(CachedRegion region, float wx, float wy)
public CachedPortalObject? FindPortalAtPosition(CachedRegion region, int zoneZ, float wx, float wy)
{
var gx = (int)MathF.Floor(wx / TileSize);
var gy = (int)MathF.Floor(wy / TileSize);
@@ -223,7 +224,7 @@ public sealed class WorldChunkCache
var tx = lzx % region.ChunkWidthTiles;
var ty = lzy % region.ChunkHeightTiles;
var key = ChunkKey(region.Id, zx, zy, cx, cy);
var key = ChunkKey(region.Id, zx, zy, zoneZ, cx, cy);
if (!_chunks.TryGetValue(key, out var chunk) || chunk == null) return null;
foreach (var portal in chunk.Portals)
@@ -235,9 +236,9 @@ public sealed class WorldChunkCache
return null;
}
public void InvalidateChunk(int regionId, int zoneX, int zoneY, int chunkX, int chunkY)
public void InvalidateChunk(int regionId, int zoneX, int zoneY, int zoneZ, int chunkX, int chunkY)
{
var key = ChunkKey(regionId, zoneX, zoneY, chunkX, chunkY);
var key = ChunkKey(regionId, zoneX, zoneY, zoneZ, chunkX, chunkY);
_chunks.TryRemove(key, out _);
_log.LogInformation("Invalidated chunk cache: {Key}", key);
}
@@ -259,8 +260,9 @@ public sealed class WorldChunkCache
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Only auto-create Z=0 (ground level) zones
var existing = await db.WorldZones
.Where(z => z.RegionId == regionId)
.Where(z => z.RegionId == regionId && z.ZoneZ == 0)
.Select(z => new { z.ZoneX, z.ZoneY })
.ToListAsync(ct);
@@ -277,6 +279,7 @@ public sealed class WorldChunkCache
RegionId = regionId,
ZoneX = x,
ZoneY = y,
ZoneZ = 0,
Name = $"Zone {x},{y}",
IsEnabled = true,
CreatedAt = now,
@@ -289,10 +292,13 @@ public sealed class WorldChunkCache
// ---- Internal ----
private static string ChunkKey(int regionId, int zoneX, int zoneY, int chunkX, int chunkY)
=> $"{regionId}:{zoneX}:{zoneY}:{chunkX}:{chunkY}";
public static string ChunkKey(int regionId, int zoneX, int zoneY, int zoneZ, int chunkX, int chunkY)
=> $"{regionId}:{zoneX}:{zoneY}:{zoneZ}:{chunkX}:{chunkY}";
private async Task<CachedChunk?> LoadChunkFromDbAsync(int regionId, int zoneX, int zoneY, int chunkX, int chunkY, CancellationToken ct)
public static string ZoneKey(int regionId, int zoneX, int zoneY, int zoneZ)
=> $"{regionId}:{zoneX}:{zoneY}:{zoneZ}";
private async Task<CachedChunk?> LoadChunkFromDbAsync(int regionId, int zoneX, int zoneY, int zoneZ, int chunkX, int chunkY, CancellationToken ct)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
@@ -301,17 +307,17 @@ public sealed class WorldChunkCache
if (region == null) return null;
var zone = await db.WorldZones.AsNoTracking()
.FirstOrDefaultAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY && z.IsEnabled, ct);
.FirstOrDefaultAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY && z.ZoneZ == zoneZ && z.IsEnabled, ct);
if (zone == null)
{
return BuildEmptyChunk(region, zoneX, zoneY, chunkX, chunkY);
return BuildEmptyChunk(region, zoneX, zoneY, zoneZ, chunkX, chunkY);
}
var chunk = await db.WorldChunks.AsNoTracking()
.FirstOrDefaultAsync(c => c.WorldZoneId == zone.Id && c.ChunkX == chunkX && c.ChunkY == chunkY, ct);
if (chunk == null)
{
return BuildEmptyChunk(region, zoneX, zoneY, chunkX, chunkY);
return BuildEmptyChunk(region, zoneX, zoneY, zoneZ, chunkX, chunkY);
}
var tiles = await db.WorldChunkTiles.AsNoTracking()
@@ -428,6 +434,7 @@ public sealed class WorldChunkCache
regionId,
zoneX,
zoneY,
zoneZ,
chunkX,
chunkY,
version = chunk.Version,
@@ -436,7 +443,7 @@ public sealed class WorldChunkCache
};
_log.LogDebug("Loaded chunk {Key} from DB: {TileCount} tiles, {ObjectCount} objects, {PortalCount} portals",
ChunkKey(regionId, zoneX, zoneY, chunkX, chunkY), tiles.Count, objects.Count, portals.Length);
ChunkKey(regionId, zoneX, zoneY, zoneZ, chunkX, chunkY), tiles.Count, objects.Count, portals.Length);
return new CachedChunk
{
@@ -445,6 +452,7 @@ public sealed class WorldChunkCache
RegionId = regionId,
ZoneX = zoneX,
ZoneY = zoneY,
ZoneZ = zoneZ,
ChunkX = chunkX,
ChunkY = chunkY,
WidthTiles = w,
@@ -460,7 +468,7 @@ public sealed class WorldChunkCache
};
}
private static CachedChunk BuildEmptyChunk(CachedRegion region, int zoneX, int zoneY, int chunkX, int chunkY)
private static CachedChunk BuildEmptyChunk(CachedRegion region, int zoneX, int zoneY, int zoneZ, int chunkX, int chunkY)
{
var w = region.ChunkWidthTiles;
var h = region.ChunkHeightTiles;
@@ -474,6 +482,7 @@ public sealed class WorldChunkCache
RegionId = region.Id,
ZoneX = zoneX,
ZoneY = zoneY,
ZoneZ = zoneZ,
ChunkX = chunkX,
ChunkY = chunkY,
WidthTiles = w,
@@ -485,6 +494,7 @@ public sealed class WorldChunkCache
regionId = region.Id,
zoneX,
zoneY,
zoneZ,
chunkX,
chunkY,
version = 0,
+331
View File
@@ -0,0 +1,331 @@
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;
}
// Award gold based on mob tier
int goldDrop = 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;
await db.SaveChangesAsync(ct);
}
// Mark mob as looted (it will be cleaned up eventually)
mob.LootEmptiedAtTick = zoneSim.CurrentTick;
await _broadcast.SendAsync(conn, OpCodes.WORLD_MOB_LOOT_RESULT, new
{
success = true,
mobId = mob.Id,
gold = goldDrop,
items = Array.Empty<object>() // TODO: Loot table integration in future
}, ct);
}
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);
}
}
}
+562
View File
@@ -0,0 +1,562 @@
using DataServer.Data;
using DataServer.Data.Entities;
using DataServer.Data.Enums;
using GameServer.Dungeon;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Server.Networking;
using Server.Networking.Messages;
namespace GameServer.World;
public sealed partial class WorldHandler
{
private sealed class WorldNpcInteractRequest
{
public int NpcId { get; set; }
}
private sealed class WorldNpcDialogSelectRequest
{
public int NpcId { get; set; }
public int OptionId { get; set; }
}
private sealed class WorldNpcShopActionRequest
{
public int NpcId { get; set; }
public string Action { get; set; } = "buy";
public int SlotIndex { get; set; }
public int Quantity { get; set; } = 1;
}
/// <summary>
/// Find the NPC in the player's current zone simulation.
/// </summary>
private NpcInstance? FindWorldNpc(WorldSessionState s, int npcId)
{
var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ);
if (!_activeZones.TryGetValue(zoneKey, out var zoneSim)) return null;
return zoneSim.Npcs.TryGetValue(npcId, out var npc) ? npc : null;
}
private async Task HandleWorldNpcInteract(IConnection conn, WorldSessionState s, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var req = WorldInputParser.Parse<WorldNpcInteractRequest>(payload);
if (req == null) return;
var npc = FindWorldNpc(s, req.NpcId);
if (npc == null)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_INTERACT_STATE, new
{
success = false,
error = "npc_not_found"
}, ct);
return;
}
// Check distance (NPC must be within interaction range)
float dist = MathF.Sqrt(MathF.Pow(npc.X - s.X, 2) + MathF.Pow(npc.Y - s.Y, 2));
if (dist > 128f) // ~4 tiles
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_INTERACT_STATE, new
{
success = false,
error = "too_far"
}, ct);
return;
}
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_INTERACT_STATE, new
{
success = true,
npc = new
{
id = npc.Id,
definitionId = npc.DefinitionId,
name = npc.Name,
canShop = npc.CanShop,
hasDialog = npc.HasDialog,
isKillable = npc.IsKillable,
behavior = npc.BehaviorMode.ToString().ToLower(),
onAttackBehavior = npc.OnAttackBehavior.ToString().ToLower(),
shopId = npc.ShopId,
dialogTreeId = npc.DialogTreeId
}
}, ct);
if (npc.HasDialog && npc.DialogTreeId.HasValue)
{
await SendWorldNpcDialogNodeAsync(conn, s, npc, null, ct);
}
if (npc.CanShop && npc.ShopId.HasValue)
{
await SendWorldNpcShopStateAsync(conn, npc.ShopId.Value, ct);
}
}
private async Task HandleWorldNpcDialogSelect(IConnection conn, WorldSessionState s, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var req = WorldInputParser.Parse<WorldNpcDialogSelectRequest>(payload);
if (req == null) return;
var npc = FindWorldNpc(s, req.NpcId);
if (npc == null || !npc.HasDialog || !npc.DialogTreeId.HasValue)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_DIALOG_RESULT, new
{
success = false,
error = "npc_dialog_unavailable"
}, ct);
return;
}
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var option = await db.DungeonNpcDialogOptions
.Include(o => o.Node)
.FirstOrDefaultAsync(o => o.Id == req.OptionId, ct);
if (option == null || option.Node == null || option.Node.DialogTreeId != npc.DialogTreeId.Value)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_DIALOG_RESULT, new
{
success = false,
error = "invalid_option"
}, ct);
return;
}
var (conditionMet, conditionError) = await EvaluateWorldDialogConditionAsync(db, s.CharacterId, option, ct);
if (!conditionMet)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_DIALOG_RESULT, new
{
success = false,
error = conditionError ?? "condition_failed"
}, ct);
return;
}
if (option.ConsumeConditionItem &&
option.ConditionType == NpcDialogConditionType.HasItem &&
int.TryParse(option.ConditionValue, out var consumeItemDefId))
{
await ConsumeWorldCharacterItemAsync(db, s.CharacterId, consumeItemDefId, Math.Max(1, option.ConditionQuantity), ct);
}
var nextNode = option.NextNodeId.HasValue
? await db.DungeonNpcDialogNodes.FirstOrDefaultAsync(n => n.Id == option.NextNodeId.Value && n.DialogTreeId == npc.DialogTreeId.Value, ct)
: null;
if (nextNode != null)
{
await ApplyWorldDialogRewardsAsync(db, s.CharacterId, nextNode, ct);
await SendWorldNpcDialogNodeAsync(conn, s, npc, nextNode.Id, ct);
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_DIALOG_RESULT, new
{
success = true,
npcId = npc.Id,
nextNodeId = nextNode.Id,
isTerminal = nextNode.IsTerminal
}, ct);
return;
}
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_DIALOG_RESULT, new
{
success = true,
npcId = npc.Id,
nextNodeId = (int?)null,
isTerminal = true
}, ct);
}
private async Task HandleWorldNpcShopAction(IConnection conn, WorldSessionState s, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var req = WorldInputParser.Parse<WorldNpcShopActionRequest>(payload);
if (req == null) return;
var npc = FindWorldNpc(s, req.NpcId);
if (npc == null || !npc.CanShop || !npc.ShopId.HasValue)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new
{
success = false,
error = "npc_shop_unavailable"
}, ct);
return;
}
if (!string.Equals(req.Action, "buy", StringComparison.OrdinalIgnoreCase))
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new
{
success = false,
error = "unsupported_shop_action"
}, ct);
return;
}
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var shopItem = await db.DungeonNpcShopItems
.Include(si => si.ItemDefinition)
.FirstOrDefaultAsync(si => si.ShopId == npc.ShopId.Value && si.SlotIndex == req.SlotIndex, ct);
if (shopItem == null || shopItem.ItemDefinition == null)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new
{
success = false,
error = "shop_item_not_found"
}, ct);
return;
}
var quantity = Math.Max(1, req.Quantity);
if (!shopItem.Restocks)
{
quantity = Math.Min(quantity, shopItem.Quantity);
if (quantity <= 0)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new
{
success = false,
error = "out_of_stock"
}, ct);
return;
}
}
var totalPrice = shopItem.PriceGold * quantity;
var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == s.CharacterId, ct);
if (character == null)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new
{
success = false,
error = "character_not_found"
}, ct);
return;
}
if (character.Gold < totalPrice)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new
{
success = false,
error = "not_enough_gold",
requiredGold = totalPrice,
currentGold = character.Gold
}, ct);
return;
}
var added = await AddWorldItemToInventoryAsync(db, s.CharacterId, shopItem.ItemDefinitionId, quantity, ct);
if (!added)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new
{
success = false,
error = "inventory_full"
}, ct);
return;
}
character.Gold -= totalPrice;
if (!shopItem.Restocks)
{
shopItem.Quantity = Math.Max(0, shopItem.Quantity - quantity);
}
await db.SaveChangesAsync(ct);
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new
{
success = true,
npcId = npc.Id,
action = "buy",
itemDefinitionId = shopItem.ItemDefinitionId,
quantity,
totalPrice,
remainingGold = character.Gold,
remainingStock = shopItem.Quantity
}, ct);
// Re-send updated shop state
await SendWorldNpcShopStateAsync(conn, npc.ShopId.Value, ct);
}
// ---- World NPC Helpers ----
private async Task SendWorldNpcDialogNodeAsync(IConnection conn, WorldSessionState s, NpcInstance npc, int? nodeId, CancellationToken ct)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
DungeonNpcDialogNode? node;
if (nodeId.HasValue)
{
node = await db.DungeonNpcDialogNodes
.FirstOrDefaultAsync(n => n.Id == nodeId.Value && n.DialogTreeId == npc.DialogTreeId, ct);
}
else
{
node = await db.DungeonNpcDialogNodes
.FirstOrDefaultAsync(n => n.DialogTreeId == npc.DialogTreeId && n.IsRoot, ct);
}
if (node == null)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_DIALOG_RESULT, new
{
success = false,
error = "dialog_node_not_found",
npcId = npc.Id
}, ct);
return;
}
var options = await db.DungeonNpcDialogOptions
.Where(o => o.NodeId == node.Id)
.OrderBy(o => o.SortOrder)
.ToListAsync(ct);
var filtered = new List<object>();
foreach (var option in options)
{
var (ok, _) = await EvaluateWorldDialogConditionAsync(db, s.CharacterId, option, ct);
if (!ok) continue;
filtered.Add(new
{
id = option.Id,
text = option.PlayerText,
nextNodeId = option.NextNodeId
});
}
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_INTERACT_STATE, new
{
success = true,
npcId = npc.Id,
dialogNode = new
{
id = node.Id,
text = node.Text,
isTerminal = node.IsTerminal,
rewardGold = node.RewardGold,
rewardXp = node.RewardXp,
rewardItemDefinitionId = node.RewardItemDefinitionId,
rewardItemQuantity = node.RewardItemQuantity
},
options = filtered
}, ct);
}
private async Task SendWorldNpcShopStateAsync(IConnection conn, int shopId, CancellationToken ct)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var shop = await db.DungeonNpcShops
.Include(s => s.Items)
.ThenInclude(i => i.ItemDefinition)
.FirstOrDefaultAsync(s => s.Id == shopId && s.IsEnabled, ct);
if (shop == null)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new
{
success = false,
error = "shop_not_found"
}, ct);
return;
}
// Handle restocking
var now = DateTime.UtcNow;
foreach (var item in shop.Items.Where(i => i.Restocks && i.RestockIntervalSeconds > 0 && i.LastRestockAt.HasValue))
{
if ((now - item.LastRestockAt!.Value).TotalSeconds >= item.RestockIntervalSeconds)
{
item.LastRestockAt = now;
}
}
await db.SaveChangesAsync(ct);
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_INTERACT_STATE, new
{
success = true,
shop = new
{
id = shop.Id,
name = shop.Name,
items = shop.Items.OrderBy(i => i.SlotIndex).Select(i => new
{
slotIndex = i.SlotIndex,
itemDefinitionId = i.ItemDefinitionId,
itemName = i.ItemDefinition != null ? i.ItemDefinition.Name : $"Item {i.ItemDefinitionId}",
quantity = i.Quantity,
priceGold = i.PriceGold,
restocks = i.Restocks,
restockIntervalSeconds = i.RestockIntervalSeconds
})
}
}, ct);
}
private async Task<(bool Ok, string? Error)> EvaluateWorldDialogConditionAsync(
GameDbContext db, ulong characterId, DungeonNpcDialogOption option, CancellationToken ct)
{
switch (option.ConditionType)
{
case NpcDialogConditionType.None:
return (true, null);
case NpcDialogConditionType.HasItem:
if (!int.TryParse(option.ConditionValue, out var itemDefId))
return (false, "invalid_condition_value");
var itemCount = await db.DungeonCharacterItems
.Where(i => i.CharacterId == characterId && i.ItemDefinitionId == itemDefId)
.SumAsync(i => (int?)i.Quantity, ct) ?? 0;
return itemCount >= Math.Max(1, option.ConditionQuantity)
? (true, null) : (false, "requires_item");
case NpcDialogConditionType.CharacterLevelAtLeast:
if (!int.TryParse(option.ConditionValue, out var minLevel))
return (false, "invalid_condition_value");
var charLevel = await db.DungeonCharacters
.Where(c => c.Id == characterId)
.Select(c => c.Level)
.FirstOrDefaultAsync(ct);
return charLevel >= minLevel ? (true, null) : (false, "level_too_low");
case NpcDialogConditionType.CharacterLevelAtMost:
if (!int.TryParse(option.ConditionValue, out var maxLevel))
return (false, "invalid_condition_value");
var charLvl = await db.DungeonCharacters
.Where(c => c.Id == characterId)
.Select(c => c.Level)
.FirstOrDefaultAsync(ct);
return charLvl <= maxLevel ? (true, null) : (false, "level_too_high");
case NpcDialogConditionType.GoldAtLeast:
if (!long.TryParse(option.ConditionValue, out var minGold))
return (false, "invalid_condition_value");
var gold = await db.DungeonCharacters
.Where(c => c.Id == characterId)
.Select(c => c.Gold)
.FirstOrDefaultAsync(ct);
return gold >= minGold ? (true, null) : (false, "not_enough_gold");
case NpcDialogConditionType.QuestCompleted:
case NpcDialogConditionType.QuestActive:
return (false, "quest_system_not_ready");
default:
return (false, "unsupported_condition");
}
}
private async Task ApplyWorldDialogRewardsAsync(GameDbContext db, ulong characterId, DungeonNpcDialogNode node, CancellationToken ct)
{
var modified = false;
var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == characterId, ct);
if (character == null) return;
if (node.RewardGold > 0)
{
character.Gold += node.RewardGold;
modified = true;
}
if (node.RewardXp > 0)
{
character.Experience += node.RewardXp;
modified = true;
}
if (node.RewardItemDefinitionId.HasValue && node.RewardItemQuantity > 0)
{
var added = await AddWorldItemToInventoryAsync(db, characterId, node.RewardItemDefinitionId.Value, node.RewardItemQuantity, ct);
modified = modified || added;
}
if (modified) await db.SaveChangesAsync(ct);
}
private async Task<bool> AddWorldItemToInventoryAsync(GameDbContext db, ulong characterId, int itemDefinitionId, int quantity, CancellationToken ct)
{
if (quantity <= 0) return true;
var itemDef = await db.DungeonItemDefinitions.FirstOrDefaultAsync(i => i.Id == itemDefinitionId, ct);
if (itemDef == null) return false;
var inventoryItems = await db.DungeonCharacterItems
.Where(i => i.CharacterId == characterId && !i.IsEquipped)
.ToListAsync(ct);
var remaining = quantity;
if (itemDef.Stackable)
{
foreach (var stack in inventoryItems.Where(i => i.ItemDefinitionId == itemDefinitionId && i.Quantity < itemDef.MaxStack))
{
var canAdd = Math.Min(remaining, itemDef.MaxStack - stack.Quantity);
if (canAdd <= 0) continue;
stack.Quantity += canAdd;
remaining -= canAdd;
if (remaining <= 0) return true;
}
}
var usedSlots = inventoryItems.Select(i => i.SlotIndex).ToHashSet();
for (var slot = 0; slot < 30 && remaining > 0; slot++)
{
if (usedSlots.Contains(slot)) continue;
var addQty = itemDef.Stackable ? Math.Min(remaining, itemDef.MaxStack) : 1;
db.DungeonCharacterItems.Add(new DungeonCharacterItem
{
CharacterId = characterId,
ItemDefinitionId = itemDefinitionId,
Quantity = addQty,
SlotIndex = slot,
IsEquipped = false
});
usedSlots.Add(slot);
remaining -= addQty;
}
return remaining <= 0;
}
private async Task ConsumeWorldCharacterItemAsync(GameDbContext db, ulong characterId, int itemDefinitionId, int quantity, CancellationToken ct)
{
if (quantity <= 0) return;
var items = await db.DungeonCharacterItems
.Where(i => i.CharacterId == characterId && i.ItemDefinitionId == itemDefinitionId && !i.IsEquipped)
.OrderBy(i => i.SlotIndex)
.ToListAsync(ct);
var remaining = quantity;
foreach (var item in items)
{
if (remaining <= 0) break;
var take = Math.Min(item.Quantity, remaining);
item.Quantity -= take;
remaining -= take;
if (item.Quantity <= 0)
{
db.DungeonCharacterItems.Remove(item);
}
}
await db.SaveChangesAsync(ct);
}
}
+255
View File
@@ -0,0 +1,255 @@
using DataServer.Data;
using DataServer.Data.Entities;
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 WorldObjectInteractRequest
{
public long ObjectId { get; set; }
public string Action { get; set; } = "interact"; // "interact", "break", "loot"
}
private async Task HandleWorldObjectInteract(IConnection conn, WorldSessionState s, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var req = WorldInputParser.Parse<WorldObjectInteractRequest>(payload);
if (req == null) return;
// Look up the object from the chunk cache to get its definition
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var worldObj = await db.WorldChunkObjects
.Include(o => o.ObjectDefinition)
.FirstOrDefaultAsync(o => o.Id == req.ObjectId, ct);
if (worldObj == null || worldObj.ObjectDefinition == null)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_OBJECT_INTERACT_RESULT, new
{
success = false,
error = "object_not_found"
}, ct);
return;
}
var objDef = worldObj.ObjectDefinition;
// Check interaction distance (convert tile position to world pixels)
// We need the chunk's world offset - approximate from the object's chunk
var chunk = await db.WorldChunks
.Include(c => c.Zone)
.FirstOrDefaultAsync(c => c.Id == worldObj.WorldChunkId, ct);
if (chunk?.Zone == null)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_OBJECT_INTERACT_RESULT, new
{
success = false,
error = "object_chunk_not_found"
}, ct);
return;
}
var region = await _cache.GetRegionAsync(s.RegionId, ct);
if (region == null) return;
float objWorldX = (chunk.Zone.ZoneX * region.ChunksPerZoneX + chunk.ChunkX) * region.ChunkWidthTiles * TileSize
+ worldObj.TileX * TileSize + TileSize / 2f;
float objWorldY = (chunk.Zone.ZoneY * region.ChunksPerZoneY + chunk.ChunkY) * region.ChunkHeightTiles * TileSize
+ worldObj.TileY * TileSize + TileSize / 2f;
float dist = MathF.Sqrt(MathF.Pow(objWorldX - s.X, 2) + MathF.Pow(objWorldY - s.Y, 2));
if (dist > 128f)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_OBJECT_INTERACT_RESULT, new
{
success = false,
error = "too_far"
}, ct);
return;
}
// Handle destructible objects first (checked by IsDestructible flag, not InteractionType)
if (objDef.IsDestructible && req.Action == "break")
{
await HandleBreakableObjectAsync(conn, s, worldObj, objDef, ct);
return;
}
// Handle interaction based on InteractionType
switch (objDef.InteractionType)
{
case ObjectInteractionType.OpenContainer:
await HandleLootableObjectAsync(conn, s, worldObj, objDef, ct);
break;
case ObjectInteractionType.Teleport:
// Portals are handled by the movement system
await _broadcast.SendAsync(conn, OpCodes.WORLD_OBJECT_INTERACT_RESULT, new
{
success = true,
objectId = worldObj.Id,
type = "teleport",
message = "Portal triggered by movement."
}, ct);
break;
case ObjectInteractionType.Trigger:
// Trigger objects return metadata text (signs, plaques, etc.)
await HandleReadableObjectAsync(conn, worldObj, objDef, ct);
break;
default:
await _broadcast.SendAsync(conn, OpCodes.WORLD_OBJECT_INTERACT_RESULT, new
{
success = true,
objectId = worldObj.Id,
type = objDef.InteractionType.ToString().ToLower(),
name = objDef.Name,
metadataJson = worldObj.MetadataJson
}, ct);
break;
}
}
private async Task HandleBreakableObjectAsync(
IConnection conn, WorldSessionState s,
WorldChunkObject worldObj, DungeonObjectDefinition objDef,
CancellationToken ct)
{
// For breakable objects, the client sends "break" action
// Server validates and fires a destroy event + potential loot
var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ);
// Generate loot if the object has a loot table (from metadata)
var lootItems = new List<object>();
int goldDrop = 0;
// Parse metadata for loot info
if (!string.IsNullOrEmpty(worldObj.MetadataJson))
{
try
{
using var doc = System.Text.Json.JsonDocument.Parse(worldObj.MetadataJson);
var root = doc.RootElement;
if (root.TryGetProperty("goldDrop", out var gp))
goldDrop = gp.GetInt32();
}
catch { /* ignore malformed metadata */ }
}
if (goldDrop > 0)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == s.CharacterId, ct);
if (character != null)
{
character.Gold += goldDrop;
await db.SaveChangesAsync(ct);
}
}
// Broadcast object break to all players in zone
if (_activeZones.TryGetValue(zoneKey, out var zoneSim))
{
foreach (var player in zoneSim.Players.Values)
{
await _broadcast.SendAsync(player.Session.Connection, OpCodes.WORLD_OBJECT_STATE, new
{
objectId = worldObj.Id,
state = "broken",
x = worldObj.TileX,
y = worldObj.TileY
}, ct);
}
}
await _broadcast.SendAsync(conn, OpCodes.WORLD_OBJECT_INTERACT_RESULT, new
{
success = true,
objectId = worldObj.Id,
type = "break",
gold = goldDrop,
items = lootItems
}, ct);
}
private async Task HandleLootableObjectAsync(
IConnection conn, WorldSessionState s,
WorldChunkObject worldObj, DungeonObjectDefinition objDef,
CancellationToken ct)
{
int goldDrop = 0;
var lootItems = new List<object>();
// Parse metadata for loot
if (!string.IsNullOrEmpty(worldObj.MetadataJson))
{
try
{
using var doc = System.Text.Json.JsonDocument.Parse(worldObj.MetadataJson);
var root = doc.RootElement;
if (root.TryGetProperty("goldDrop", out var gp))
goldDrop = gp.GetInt32();
}
catch { /* ignore */ }
}
if (goldDrop > 0)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == s.CharacterId, ct);
if (character != null)
{
character.Gold += goldDrop;
await db.SaveChangesAsync(ct);
}
}
await _broadcast.SendAsync(conn, OpCodes.WORLD_OBJECT_INTERACT_RESULT, new
{
success = true,
objectId = worldObj.Id,
type = "loot",
gold = goldDrop,
items = lootItems
}, ct);
}
private async Task HandleReadableObjectAsync(
IConnection conn,
WorldChunkObject worldObj, DungeonObjectDefinition objDef,
CancellationToken ct)
{
// Readable objects just return their text content from metadata
string readableText = "";
if (!string.IsNullOrEmpty(worldObj.MetadataJson))
{
try
{
using var doc = System.Text.Json.JsonDocument.Parse(worldObj.MetadataJson);
var root = doc.RootElement;
if (root.TryGetProperty("text", out var tp))
readableText = tp.GetString() ?? "";
}
catch { /* ignore */ }
}
await _broadcast.SendAsync(conn, OpCodes.WORLD_OBJECT_INTERACT_RESULT, new
{
success = true,
objectId = worldObj.Id,
type = "readable",
name = objDef.Name,
text = readableText
}, ct);
}
}
+353 -12
View File
@@ -2,6 +2,7 @@ using System.Collections.Concurrent;
using System.Text.Json;
using DataServer.Data;
using DataServer.Data.Entities;
using GameServer.Dungeon;
using GameServices;
using GameServices.Auth;
using Microsoft.EntityFrameworkCore;
@@ -13,9 +14,10 @@ using Server.Networking.Messages;
namespace GameServer.World;
public sealed class WorldHandler : IClientMessageHandler
public sealed partial class WorldHandler : IClientMessageHandler
{
private const int TileSize = 32;
private const float TickDeltaSeconds = 0.1f; // 10Hz
private static readonly TimeSpan NeutralInputGrace = TimeSpan.FromMilliseconds(180);
private static readonly TimeSpan DirectionalPriorityGrace = TimeSpan.FromMilliseconds(450);
@@ -31,6 +33,13 @@ public sealed class WorldHandler : IClientMessageHandler
private readonly ConcurrentDictionary<ulong, long> _portalCooldownByCharacter = new();
private readonly bool _debugInput;
// Zone simulations (keyed by "{regionId}:{zoneX}:{zoneY}:{zoneZ}")
private readonly ConcurrentDictionary<string, WorldZoneSimulation> _activeZones = new();
// Mob/NPC definition caches (loaded once at init)
private Dictionary<int, DungeonMobDefinition> _mobDefinitions = new();
private Dictionary<int, DungeonNpcDefinition> _npcDefinitions = new();
private Task? _tickTask;
private CancellationTokenSource? _tickCts;
private long _tick;
@@ -62,18 +71,50 @@ public sealed class WorldHandler : IClientMessageHandler
{
OpCodes.WORLD_SPAWN_REQUEST,
OpCodes.WORLD_INPUT,
OpCodes.PONG
OpCodes.PONG,
// World combat
OpCodes.WORLD_ATTACK,
OpCodes.WORLD_MOB_LOOT_REQUEST,
// World NPC
OpCodes.WORLD_NPC_INTERACT,
OpCodes.WORLD_NPC_DIALOG_SELECT,
OpCodes.WORLD_NPC_SHOP_ACTION,
// World objects
OpCodes.WORLD_OBJECT_INTERACT
};
public Task InitializeAsync()
public async Task InitializeAsync()
{
if (_initialized) return Task.CompletedTask;
if (_initialized) return;
// Load mob and NPC definitions for zone simulations
await LoadWorldDefinitionsAsync();
_tickCts = new CancellationTokenSource();
_tickTask = Task.Run(() => TickLoopAsync(_tickCts.Token), _tickCts.Token);
_deltaHub.OnDeltaPublished += OnWorldEditDelta;
_initialized = true;
_log.LogInformation("WorldHandler initialized (cached movement pipeline + live delta forwarding)");
return Task.CompletedTask;
_log.LogInformation(
"WorldHandler initialized with {MobCount} mob defs, {NpcCount} NPC defs",
_mobDefinitions.Count, _npcDefinitions.Count);
}
private async Task LoadWorldDefinitionsAsync()
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var mobs = await db.Set<DungeonMobDefinition>()
.Where(m => m.IsEnabled)
.Include(m => m.AbilityAssignments)
.ThenInclude(a => a.AbilityDefinition)
.ToListAsync();
_mobDefinitions = mobs.ToDictionary(m => m.Id);
var npcs = await db.Set<DungeonNpcDefinition>()
.Where(n => n.IsEnabled)
.ToListAsync();
_npcDefinitions = npcs.ToDictionary(n => n.Id);
}
public async Task HandleAsync(int opCode, IConnection connection, ReadOnlyMemory<byte> payload, CancellationToken ct)
@@ -97,6 +138,35 @@ public sealed class WorldHandler : IClientMessageHandler
if (opCode == OpCodes.WORLD_INPUT)
{
HandleInput(connection, accountId, payload);
return;
}
// All remaining opcodes require the player to be spawned
if (!_players.TryGetValue(connection.Id, out var session)) return;
switch (opCode)
{
// Combat
case OpCodes.WORLD_ATTACK:
await HandleWorldAttackAsync(connection, session, payload, ct);
break;
case OpCodes.WORLD_MOB_LOOT_REQUEST:
await HandleWorldMobLootAsync(connection, session, payload, ct);
break;
// NPC
case OpCodes.WORLD_NPC_INTERACT:
await HandleWorldNpcInteract(connection, session, payload, ct);
break;
case OpCodes.WORLD_NPC_DIALOG_SELECT:
await HandleWorldNpcDialogSelect(connection, session, payload, ct);
break;
case OpCodes.WORLD_NPC_SHOP_ACTION:
await HandleWorldNpcShopAction(connection, session, payload, ct);
break;
// Objects
case OpCodes.WORLD_OBJECT_INTERACT:
await HandleWorldObjectInteract(connection, session, payload, ct);
break;
}
}
@@ -104,6 +174,13 @@ public sealed class WorldHandler : IClientMessageHandler
{
if (_players.TryRemove(connectionId, out var s))
{
// Remove from zone simulation
var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ);
if (_activeZones.TryGetValue(zoneKey, out var zoneSim))
{
zoneSim.RemovePlayer(s.CharacterId);
}
_ = PersistPlayerLocationAsync(s);
_ = _broadcast.BroadcastToRegionAsync(
OpCodes.WORLD_DESPAWN,
@@ -139,6 +216,7 @@ public sealed class WorldHandler : IClientMessageHandler
var requestedExplicitChunk = req.ZoneX.HasValue || req.ZoneY.HasValue || req.ChunkX.HasValue || req.ChunkY.HasValue;
var zx = Math.Clamp(req.ZoneX ?? character.WorldZoneX ?? 0, 0, Math.Max(0, region.ZonesPerRegionX - 1));
var zy = Math.Clamp(req.ZoneY ?? character.WorldZoneY ?? 0, 0, Math.Max(0, region.ZonesPerRegionY - 1));
var zz = character.WorldZoneZ ?? 0;
var cx = Math.Clamp(req.ChunkX ?? character.WorldChunkX ?? 0, 0, Math.Max(0, region.ChunksPerZoneX - 1));
var cy = Math.Clamp(req.ChunkY ?? character.WorldChunkY ?? 0, 0, Math.Max(0, region.ChunksPerZoneY - 1));
var tx = Math.Max(0, Math.Min(region.ChunkWidthTiles - 1, region.ChunkWidthTiles / 2));
@@ -165,6 +243,7 @@ public sealed class WorldHandler : IClientMessageHandler
RegionId = region.Id,
ZoneX = pzX,
ZoneY = pzY,
ZoneZ = zz,
ChunkX = pcX,
ChunkY = pcY,
X = x,
@@ -175,6 +254,7 @@ public sealed class WorldHandler : IClientMessageHandler
character.WorldRegionId = s.RegionId;
character.WorldZoneX = s.ZoneX;
character.WorldZoneY = s.ZoneY;
character.WorldZoneZ = s.ZoneZ;
character.WorldChunkX = s.ChunkX;
character.WorldChunkY = s.ChunkY;
character.WorldX = s.X;
@@ -307,12 +387,24 @@ public sealed class WorldHandler : IClientMessageHandler
private async Task SendStatesAsync(CancellationToken ct)
{
if (_players.IsEmpty) return;
if (_players.IsEmpty && _activeZones.IsEmpty) return;
var tick = Interlocked.Read(ref _tick);
// Process all players in parallel instead of sequentially
// 1. Ensure players are registered in zone simulations
await EnsurePlayersInZoneSimsAsync(tick, ct);
// 2. Tick all active zone simulations (mob AI, combat, projectiles, etc.)
TickActiveZones(tick);
// 3. Broadcast combat events from zone simulations
await BroadcastCombatEventsAsync(ct);
// 4. Process all players (movement, chunk updates, state broadcast)
var tasks = _players.Values.Select(s => ProcessPlayerTickAsync(s, tick, ct));
await Task.WhenAll(tasks);
// 5. Clean up deactivated zones
CleanupInactiveZones();
}
private async Task ProcessPlayerTickAsync(WorldSessionState s, long tick, CancellationToken ct)
@@ -333,12 +425,31 @@ public sealed class WorldHandler : IClientMessageHandler
var errs = s.Errors.Count == 0 ? null : s.Errors.Distinct().ToArray();
s.Errors.Clear();
// Get mob/NPC data from zone simulation if active
var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ);
object[]? nearbyMobs = null;
object[]? nearbyNpcs = null;
if (_activeZones.TryGetValue(zoneKey, out var zoneSim))
{
float visRange = TileSize * 48;
nearbyMobs = zoneSim.Mobs.Values
.Where(m => Math.Abs(m.X - s.X) <= visRange && Math.Abs(m.Y - s.Y) <= visRange)
.Select(m => zoneSim.SerializeMob(m))
.ToArray();
nearbyNpcs = zoneSim.Npcs.Values
.Where(n => Math.Abs(n.X - s.X) <= visRange && Math.Abs(n.Y - s.Y) <= visRange)
.Select(n => zoneSim.SerializeNpc(n))
.ToArray();
}
await _broadcast.SendAsync(s.Connection, OpCodes.WORLD_STATE, new
{
tick,
ackSeq = s.Seq,
self = new { x = s.X, y = s.Y, velocityX = s.VelX, velocityY = s.VelY, regionId = s.RegionId, zoneX = s.ZoneX, zoneY = s.ZoneY, chunkX = s.ChunkX, chunkY = s.ChunkY },
players = VisiblePlayers(s).Select(p => new { id = p.CharacterId, name = p.Name, x = p.X, y = p.Y, facing = p.Facing, speed = p.Speed, isMoving = p.IsMoving, regionId = p.RegionId, zoneX = p.ZoneX, zoneY = p.ZoneY, chunkX = p.ChunkX, chunkY = p.ChunkY }),
mobs = nearbyMobs,
npcs = nearbyNpcs,
chunkUpdates = updates.Select(u => u.payload),
portalEvent = s.PendingPortalEvent,
errors = errs
@@ -355,6 +466,7 @@ public sealed class WorldHandler : IClientMessageHandler
=> _players.Values.Where(p =>
p.ConnectionId != self.ConnectionId &&
p.RegionId == self.RegionId &&
p.ZoneZ == self.ZoneZ &&
Math.Abs(p.ZoneX - self.ZoneX) <= 1 &&
Math.Abs(p.ZoneY - self.ZoneY) <= 1 &&
Math.Abs(p.X - self.X) <= (TileSize * 48) &&
@@ -380,15 +492,16 @@ public sealed class WorldHandler : IClientMessageHandler
// Parse chunk coordinates from the key for cache invalidation
var parts = chunkKey.Split(':');
if (parts.Length == 5 &&
if (parts.Length == 6 &&
int.TryParse(parts[0], out var regionId) &&
int.TryParse(parts[1], out var zoneX) &&
int.TryParse(parts[2], out var zoneY) &&
int.TryParse(parts[3], out var chunkX) &&
int.TryParse(parts[4], out var chunkY))
int.TryParse(parts[3], out var zoneZ) &&
int.TryParse(parts[4], out var chunkX) &&
int.TryParse(parts[5], out var chunkY))
{
// Invalidate cache so next access reloads fresh data from DB
_cache.InvalidateChunk(regionId, zoneX, zoneY, chunkX, chunkY);
_cache.InvalidateChunk(regionId, zoneX, zoneY, zoneZ, chunkX, chunkY);
// Deserialize the delta to a dynamic object for forwarding to clients.
// The raw JSON from the hub already has all the fields the client needs.
@@ -405,6 +518,233 @@ public sealed class WorldHandler : IClientMessageHandler
}
}
// ---- Zone Simulation Lifecycle ----
/// <summary>
/// Ensure all players are registered in their zone's simulation.
/// Activates new zone simulations as needed.
/// </summary>
private async Task EnsurePlayersInZoneSimsAsync(long tick, CancellationToken ct)
{
foreach (var s in _players.Values)
{
var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ);
if (!_activeZones.TryGetValue(zoneKey, out var zoneSim))
{
// Activate zone simulation
zoneSim = await ActivateZoneSimulationAsync(zoneKey, s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ, ct);
if (zoneSim == null) continue;
}
// Ensure player is in the simulation
if (!zoneSim.Players.ContainsKey(s.CharacterId))
{
var combatState = new WorldPlayerCombatState(s);
// Initialize with basic stats (character stats would come from DB/gear)
// For now use defaults — Phase 4 will flesh out stat loading from gear
combatState.InitializeFromCharacter(
strength: 10, intelligence: 10, endurance: 10, dexterity: 10,
armor: 0, maxHealth: 100, weaponDamageTypeKey: "physical",
resistances: new Dictionary<string, float>());
zoneSim.AddPlayer(combatState);
}
}
}
/// <summary>
/// Activate a new zone simulation by loading mob/NPC spawn data from cached chunks.
/// </summary>
private async Task<WorldZoneSimulation?> ActivateZoneSimulationAsync(
string zoneKey, int regionId, int zoneX, int zoneY, int zoneZ, CancellationToken ct)
{
try
{
var region = await _cache.GetRegionAsync(regionId, ct);
if (region == null) return null;
var zoneSim = new WorldZoneSimulation(zoneKey, regionId, zoneX, zoneY, zoneZ, _cache);
zoneSim.SetRegion(region);
// Collect mob and NPC spawns from all chunks in this zone
var mobSpawns = new List<(WorldChunkMobSpawnData, int, int)>();
var npcSpawns = new List<(NpcInstance, int, int)>();
int nextNpcId = 1;
for (int cx = 0; cx < region.ChunksPerZoneX; cx++)
for (int cy = 0; cy < region.ChunksPerZoneY; cy++)
{
var chunk = await _cache.GetChunkAsync(regionId, zoneX, zoneY, zoneZ, cx, cy, ct);
if (chunk == null) continue;
// Calculate world pixel offset for this chunk
int chunkWorldOffsetX = (zoneX * region.ChunksPerZoneX + cx) * region.ChunkWidthTiles * TileSize;
int chunkWorldOffsetY = (zoneY * region.ChunksPerZoneY + cy) * region.ChunkHeightTiles * TileSize;
// Extract mob spawns from MobDtos (anonymous objects)
ExtractMobSpawnsFromChunk(chunk, chunkWorldOffsetX, chunkWorldOffsetY, mobSpawns);
// Extract NPC spawns from NpcDtos
ExtractNpcSpawnsFromChunk(chunk, chunkWorldOffsetX, chunkWorldOffsetY, npcSpawns, ref nextNpcId);
}
zoneSim.Initialize(_mobDefinitions, mobSpawns, npcSpawns);
if (_activeZones.TryAdd(zoneKey, zoneSim))
{
_log.LogInformation(
"Activated zone simulation {ZoneKey}: {MobCount} mobs, {NpcCount} NPCs",
zoneKey, zoneSim.Mobs.Count, zoneSim.Npcs.Count);
return zoneSim;
}
// Another thread beat us, use their version
return _activeZones.TryGetValue(zoneKey, out var existing) ? existing : null;
}
catch (Exception ex)
{
_log.LogWarning(ex, "Failed to activate zone simulation {ZoneKey}", zoneKey);
return null;
}
}
/// <summary>
/// Extract mob spawn data from a cached chunk's MobDtos.
/// The MobDtos are anonymous objects serialized from WorldChunkMobSpawn entities.
/// </summary>
private static void ExtractMobSpawnsFromChunk(
WorldChunkCache.CachedChunk chunk,
int chunkWorldOffsetX, int chunkWorldOffsetY,
List<(WorldChunkMobSpawnData, int, int)> mobSpawns)
{
foreach (var mobDto in chunk.MobDtos)
{
// MobDtos are anonymous objects with: id, x, y, mobDefinitionId, mobName, rotation, spawnCount, respawnSeconds, metadataJson
// Use JSON round-trip to extract values
var json = JsonSerializer.Serialize(mobDto);
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
var spawnData = new WorldChunkMobSpawnData
{
Id = root.TryGetProperty("id", out var idProp) ? idProp.GetInt64() : 0,
MobDefinitionId = root.TryGetProperty("mobDefinitionId", out var mobDefProp) ? mobDefProp.GetInt32() : 0,
TileX = root.TryGetProperty("x", out var xProp) ? xProp.GetInt32() : 0,
TileY = root.TryGetProperty("y", out var yProp) ? yProp.GetInt32() : 0,
SpawnCount = root.TryGetProperty("spawnCount", out var scProp) ? scProp.GetInt32() : 1,
RespawnSeconds = root.TryGetProperty("respawnSeconds", out var rsProp) ? rsProp.GetSingle() : 30f
};
if (spawnData.MobDefinitionId > 0)
{
mobSpawns.Add((spawnData, chunkWorldOffsetX, chunkWorldOffsetY));
}
}
}
/// <summary>
/// Extract NPC instances from a cached chunk's NpcDtos.
/// </summary>
private void ExtractNpcSpawnsFromChunk(
WorldChunkCache.CachedChunk chunk,
int chunkWorldOffsetX, int chunkWorldOffsetY,
List<(NpcInstance, int, int)> npcSpawns,
ref int nextNpcId)
{
foreach (var npcDto in chunk.NpcDtos)
{
var json = JsonSerializer.Serialize(npcDto);
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
int npcDefId = root.TryGetProperty("npcDefinitionId", out var defProp) ? defProp.GetInt32() : 0;
if (npcDefId <= 0 || !_npcDefinitions.TryGetValue(npcDefId, out var npcDef)) continue;
int tileX = root.TryGetProperty("x", out var xProp) ? xProp.GetInt32() : 0;
int tileY = root.TryGetProperty("y", out var yProp) ? yProp.GetInt32() : 0;
float worldX = chunkWorldOffsetX + (tileX * TileSize) + (TileSize / 2f);
float worldY = chunkWorldOffsetY + (tileY * TileSize) + (TileSize / 2f);
var npc = NpcInstance.FromDefinition(npcDef, nextNpcId++, worldX, worldY);
npcSpawns.Add((npc, chunkWorldOffsetX, chunkWorldOffsetY));
}
}
/// <summary>
/// Tick all active zone simulations.
/// </summary>
private void TickActiveZones(long tick)
{
foreach (var (zoneKey, zoneSim) in _activeZones)
{
try
{
zoneSim.Tick(tick, TickDeltaSeconds);
}
catch (Exception ex)
{
_log.LogWarning(ex, "Error ticking zone simulation {ZoneKey}", zoneKey);
}
}
}
/// <summary>
/// Broadcast pending combat events from all zone simulations.
/// </summary>
private async Task BroadcastCombatEventsAsync(CancellationToken ct)
{
foreach (var (_, zoneSim) in _activeZones)
{
var events = new List<object>();
while (zoneSim.PendingEvents.TryDequeue(out var evt))
{
events.Add(new
{
type = evt.Type.ToString(),
sourceMobId = evt.SourceMobId,
sourcePlayerId = evt.SourcePlayerId,
targetMobId = evt.TargetMobId,
targetPlayerId = evt.TargetPlayerId,
damage = evt.Damage,
damageTypeKey = evt.DamageTypeKey,
x = evt.X,
y = evt.Y,
mobData = evt.MobData
});
}
if (events.Count == 0) continue;
// Send combat state to all players in this zone
foreach (var player in zoneSim.Players.Values)
{
await _broadcast.SendAsync(
player.Session.Connection,
OpCodes.WORLD_COMBAT_STATE,
new { events },
ct);
}
}
}
/// <summary>
/// Remove deactivated zone simulations.
/// </summary>
private void CleanupInactiveZones()
{
foreach (var (zoneKey, zoneSim) in _activeZones)
{
if (!zoneSim.IsActive)
{
if (_activeZones.TryRemove(zoneKey, out var removed))
{
removed.Deactivate();
_log.LogInformation("Deactivated zone simulation {ZoneKey}", zoneKey);
}
}
}
}
// ---- Persistence (only on disconnect) ----
private async Task PersistPlayerLocationAsync(WorldSessionState s)
@@ -419,6 +759,7 @@ public sealed class WorldHandler : IClientMessageHandler
character.WorldRegionId = s.RegionId;
character.WorldZoneX = s.ZoneX;
character.WorldZoneY = s.ZoneY;
character.WorldZoneZ = s.ZoneZ;
character.WorldChunkX = s.ChunkX;
character.WorldChunkY = s.ChunkY;
character.WorldX = s.X;
+229
View File
@@ -0,0 +1,229 @@
using DataServer.Data.Entities;
using DataServer.Data.Enums;
using GameServer.Dungeon;
namespace GameServer.World;
/// <summary>
/// Tracks mob spawn points in a zone, handles respawn timers, and creates MobInstance objects.
/// Each spawn point can have multiple mobs (SpawnCount) that respawn independently.
/// </summary>
public sealed class WorldMobSpawnTracker
{
private readonly Dictionary<int, DungeonMobDefinition> _mobDefinitions;
private readonly List<SpawnPoint> _spawnPoints = new();
private int _nextMobId = 1;
private readonly Random _rng = new();
public WorldMobSpawnTracker(Dictionary<int, DungeonMobDefinition> mobDefinitions)
{
_mobDefinitions = mobDefinitions;
}
/// <summary>
/// Register a mob spawn point from chunk data.
/// Returns any initially spawned mobs.
/// </summary>
public List<MobInstance> RegisterSpawnPoint(WorldChunkMobSpawnData data, int chunkWorldOffsetX, int chunkWorldOffsetY)
{
if (!_mobDefinitions.TryGetValue(data.MobDefinitionId, out var mobDef))
return new List<MobInstance>();
var spawnPoint = new SpawnPoint
{
SpawnDataId = data.Id,
MobDefinitionId = data.MobDefinitionId,
WorldX = chunkWorldOffsetX + (data.TileX * 32) + 16,
WorldY = chunkWorldOffsetY + (data.TileY * 32) + 16,
SpawnCount = Math.Max(1, data.SpawnCount),
RespawnSeconds = Math.Max(5f, data.RespawnSeconds),
ActiveMobIds = new List<int>(),
RespawnTimers = new List<float>()
};
_spawnPoints.Add(spawnPoint);
// Spawn initial mobs
var mobs = new List<MobInstance>();
for (int i = 0; i < spawnPoint.SpawnCount; i++)
{
var mob = CreateMob(mobDef, spawnPoint);
if (mob != null)
{
spawnPoint.ActiveMobIds.Add(mob.Id);
mobs.Add(mob);
}
}
return mobs;
}
/// <summary>
/// Notify that a mob has died. Start respawn timer for its spawn point.
/// </summary>
public void OnMobDied(int mobId)
{
foreach (var sp in _spawnPoints)
{
int idx = sp.ActiveMobIds.IndexOf(mobId);
if (idx >= 0)
{
sp.ActiveMobIds.RemoveAt(idx);
sp.RespawnTimers.Add(sp.RespawnSeconds);
break;
}
}
}
/// <summary>
/// Update respawn timers and return any newly spawned mobs.
/// </summary>
public List<MobInstance> Update(float deltaTime)
{
var newMobs = new List<MobInstance>();
foreach (var sp in _spawnPoints)
{
for (int i = sp.RespawnTimers.Count - 1; i >= 0; i--)
{
sp.RespawnTimers[i] -= deltaTime;
if (sp.RespawnTimers[i] <= 0)
{
sp.RespawnTimers.RemoveAt(i);
if (!_mobDefinitions.TryGetValue(sp.MobDefinitionId, out var mobDef))
continue;
var mob = CreateMob(mobDef, sp);
if (mob != null)
{
sp.ActiveMobIds.Add(mob.Id);
newMobs.Add(mob);
}
}
}
}
return newMobs;
}
private MobInstance? CreateMob(DungeonMobDefinition mobDef, SpawnPoint sp)
{
var stats = mobDef.GetStatsForBracket(1); // World mobs use bracket 1 (base stats)
int id = _nextMobId++;
// Randomize spawn position slightly around the spawn point
float offsetX = ((float)_rng.NextDouble() - 0.5f) * 64f;
float offsetY = ((float)_rng.NextDouble() - 0.5f) * 64f;
float spawnX = sp.WorldX + offsetX;
float spawnY = sp.WorldY + offsetY;
var mob = new MobInstance
{
Id = id,
DefinitionId = mobDef.Id,
Name = mobDef.Name,
X = spawnX,
Y = spawnY,
SpawnX = sp.WorldX,
SpawnY = sp.WorldY,
Health = stats.MaxHealth,
MaxHealth = stats.MaxHealth,
Mana = mobDef.BaseMana,
MaxMana = mobDef.BaseMana,
Stats = stats,
State = MobState.Idle,
StateTime = (float)(_rng.NextDouble() * 3f),
SpriteConfigJson = mobDef.SpriteConfigJson,
TintColor = mobDef.TintColor,
Scale = mobDef.Scale,
Type = mobDef.Type,
Behavior = mobDef.Behavior,
PreferredRange = mobDef.PreferredRange,
FleeThreshold = mobDef.FleeThreshold,
Phases = mobDef.Phases,
CurrentAnimation = "idle_down",
FacingDirection = "down"
};
// Initialize abilities
InitializeMobAbilities(mob, mobDef, stats);
return mob;
}
private void InitializeMobAbilities(MobInstance mob, DungeonMobDefinition mobDef, DungeonMobCombatStats stats)
{
mob.Abilities.Clear();
// Load abilities from assignments (same pattern as DungeonSimulation)
if (mobDef.AbilityAssignments != null)
{
foreach (var assignment in mobDef.AbilityAssignments.Where(a => a.IsEnabled))
{
var abilityDef = assignment.AbilityDefinition;
if (abilityDef == null) continue;
mob.Abilities.Add(new MobAbilityState
{
AbilityId = abilityDef.Id,
Definition = abilityDef,
ResolvedAnimationKey = abilityDef.AnimationKey,
CooldownRemaining = 0f,
Priority = assignment.PriorityOverride ?? abilityDef.Priority,
Phase = assignment.Phase,
MinHpPercent = assignment.MinHpPercent,
MaxHpPercent = assignment.MaxHpPercent
});
}
}
// Ensure at least a basic melee attack
bool hasBasicMelee = mob.Abilities.Any(a => a.Definition.AbilityType == MobAbilityType.MeleeAttack);
if (!hasBasicMelee)
{
mob.Abilities.Add(new MobAbilityState
{
Definition = new MobAbilityDefinition
{
Name = "Melee Attack",
AbilityType = MobAbilityType.MeleeAttack,
BaseDamage = stats.PhysicalDamage > 0 ? stats.PhysicalDamage : 10,
Range = stats.AttackRange > 0 ? stats.AttackRange : 40f,
Cooldown = stats.AttackSpeed > 0 ? 1f / stats.AttackSpeed : 1.5f,
ManaCost = 0,
AnimationKey = "attack"
},
CooldownRemaining = 0f
});
}
}
public int SpawnPointCount => _spawnPoints.Count;
public int TotalActiveMobs => _spawnPoints.Sum(sp => sp.ActiveMobIds.Count);
private class SpawnPoint
{
public long SpawnDataId { get; set; }
public int MobDefinitionId { get; set; }
public float WorldX { get; set; }
public float WorldY { get; set; }
public int SpawnCount { get; set; }
public float RespawnSeconds { get; set; }
public List<int> ActiveMobIds { get; set; } = new();
public List<float> RespawnTimers { get; set; } = new();
}
}
/// <summary>
/// Serializable mob spawn data extracted from CachedChunk's MobDtos.
/// </summary>
public sealed class WorldChunkMobSpawnData
{
public long Id { get; set; }
public int MobDefinitionId { get; set; }
public int TileX { get; set; }
public int TileY { get; set; }
public int SpawnCount { get; set; } = 1;
public float RespawnSeconds { get; set; } = 30f;
}
+45 -4
View File
@@ -86,12 +86,12 @@ public sealed class WorldMovementService
if (moving)
{
// Slide collision: try each axis independently (same behavior as original)
if (_cache.IsPositionWalkable(region, nextX, s.Y, s.IsVip))
if (_cache.IsPositionWalkable(region, s.ZoneZ, nextX, s.Y, s.IsVip))
s.X = nextX;
else
s.Errors.Add("blocked_non_walkable");
if (_cache.IsPositionWalkable(region, s.X, nextY, s.IsVip))
if (_cache.IsPositionWalkable(region, s.ZoneZ, s.X, nextY, s.IsVip))
s.Y = nextY;
else
s.Errors.Add("blocked_non_walkable");
@@ -150,6 +150,7 @@ public sealed class WorldMovementService
s.RegionId = targetRegion.Id;
s.X = nx;
s.Y = ny;
s.ZoneZ = req.TargetZoneZ;
var (zx, zy, cx, cy) = ToChunkPos(targetRegion, s.X, s.Y);
s.ZoneX = zx;
s.ZoneY = zy;
@@ -164,6 +165,7 @@ public sealed class WorldMovementService
regionId = s.RegionId,
zoneX = s.ZoneX,
zoneY = s.ZoneY,
zoneZ = s.ZoneZ,
chunkX = s.ChunkX,
chunkY = s.ChunkY,
x = s.X,
@@ -187,7 +189,7 @@ public sealed class WorldMovementService
if (portalCooldowns.TryGetValue(s.CharacterId, out var untilTick) && untilTick > currentTick)
return;
var portal = _cache.FindPortalAtPosition(region, s.X, s.Y);
var portal = _cache.FindPortalAtPosition(region, s.ZoneZ, s.X, s.Y);
if (portal == null || string.IsNullOrWhiteSpace(portal.MetadataJson))
return;
@@ -196,10 +198,45 @@ public sealed class WorldMovementService
portalCooldowns[s.CharacterId] = currentTick + PortalCooldownTicks;
// Building portals (Z-level change within same zone)
if (meta.IsBuildingPortal)
{
var targetZ = meta.TargetZoneZ ?? 0;
var tileX = meta.TargetTileX ?? (int)MathF.Floor(s.X / TileSize) % (region.ChunkWidthTiles > 0 ? region.ChunkWidthTiles : 1);
var tileY = meta.TargetTileY ?? (int)MathF.Floor(s.Y / TileSize) % (region.ChunkHeightTiles > 0 ? region.ChunkHeightTiles : 1);
var cX = meta.TargetChunkX ?? s.ChunkX;
var cY = meta.TargetChunkY ?? s.ChunkY;
var nx = WorldPxX(region, s.ZoneX, cX, tileX);
var ny = WorldPxY(region, s.ZoneY, cY, tileY);
s.X = nx;
s.Y = ny;
s.ZoneZ = targetZ;
var (zx, zy, cx, cy) = ToChunkPos(region, s.X, s.Y);
s.ZoneX = zx;
s.ZoneY = zy;
s.ChunkX = cx;
s.ChunkY = cy;
s.ChunkVersions.Clear();
s.PendingPortalEvent = new
{
type = "building_teleport",
sourceObjectId = portal.Id,
regionId = s.RegionId,
zoneX = s.ZoneX,
zoneY = s.ZoneY,
zoneZ = s.ZoneZ,
chunkX = s.ChunkX,
chunkY = s.ChunkY,
x = s.X,
y = s.Y
};
return;
}
if (meta.PortalType.Equals("world", StringComparison.OrdinalIgnoreCase))
{
if (WorldPortalMetadata.TryResolveWorldTarget(meta,
out var targetRegionId, out var targetZoneX, out var targetZoneY,
out var targetRegionId, out var targetZoneX, out var targetZoneY, out var targetZoneZ,
out var targetChunkX, out var targetChunkY, out var targetTileX, out var targetTileY))
{
// If same region, resolve immediately
@@ -209,6 +246,7 @@ public sealed class WorldMovementService
var ny = WorldPxY(region, targetZoneY, targetChunkY, targetTileY);
s.X = nx;
s.Y = ny;
s.ZoneZ = targetZoneZ;
var (zx, zy, cx, cy) = ToChunkPos(region, s.X, s.Y);
s.ZoneX = zx;
s.ZoneY = zy;
@@ -222,6 +260,7 @@ public sealed class WorldMovementService
regionId = s.RegionId,
zoneX = s.ZoneX,
zoneY = s.ZoneY,
zoneZ = s.ZoneZ,
chunkX = s.ChunkX,
chunkY = s.ChunkY,
x = s.X,
@@ -237,6 +276,7 @@ public sealed class WorldMovementService
TargetRegionId = targetRegionId,
TargetZoneX = targetZoneX,
TargetZoneY = targetZoneY,
TargetZoneZ = targetZoneZ,
TargetChunkX = targetChunkX,
TargetChunkY = targetChunkY,
TargetTileX = targetTileX,
@@ -305,6 +345,7 @@ public sealed class WorldMovementService
public int TargetRegionId { get; init; }
public int TargetZoneX { get; init; }
public int TargetZoneY { get; init; }
public int TargetZoneZ { get; init; }
public int TargetChunkX { get; init; }
public int TargetChunkY { get; init; }
public int TargetTileX { get; init; }
+120
View File
@@ -0,0 +1,120 @@
using GameServer.Dungeon;
using GameServer.Shared;
namespace GameServer.World;
/// <summary>
/// Implements IPlayerTarget for a world player, built from character stats on spawn.
/// Position delegates to the WorldSessionState so movement updates are reflected in combat.
/// </summary>
public sealed class WorldPlayerCombatState : IPlayerTarget
{
private readonly WorldSessionState _session;
public ulong CharacterId => _session.CharacterId;
public string CharacterName => _session.Name;
// Position delegates to session
public float X => _session.X;
public float Y => _session.Y;
// Vitals
public float Health { get; set; }
public float MaxHealth { get; private set; }
public bool IsAlive { get; set; } = true;
public bool IsInvulnerable { get; set; }
// Combat stats (computed from character + gear at spawn)
public int Strength { get; set; }
public int Intelligence { get; set; }
public int Endurance { get; set; }
public int Dexterity { get; set; }
public int Armor { get; set; }
public string WeaponDamageTypeKey { get; set; } = "physical";
public Dictionary<string, float> Resistances { get; set; } = new();
// Status effects
public List<PlayerStatusEffect> StatusEffects { get; set; } = new();
public bool IsStunned => StatusEffects.Any(e => e.EffectType == "stun" && e.Duration > 0);
public bool IsRooted => StatusEffects.Any(e => e.EffectType == "root" && e.Duration > 0);
public bool IsFeared => StatusEffects.Any(e => e.EffectType == "fear" && e.Duration > 0);
// Combat tracking
public bool IsInCombat { get; set; }
public long LastCombatTick { get; set; }
// Invulnerability timer (for respawn protection)
public float InvulnerabilityTimer { get; set; }
// Reference to the session for direct access
public WorldSessionState Session => _session;
public WorldPlayerCombatState(WorldSessionState session)
{
_session = session;
}
/// <summary>
/// Initialize combat state from character stats.
/// Called when player enters a zone with active simulation.
/// </summary>
public void InitializeFromCharacter(
int strength, int intelligence, int endurance, int dexterity,
int armor, float maxHealth, string weaponDamageTypeKey,
Dictionary<string, float> resistances)
{
Strength = strength;
Intelligence = intelligence;
Endurance = endurance;
Dexterity = dexterity;
Armor = armor;
MaxHealth = maxHealth;
Health = maxHealth;
WeaponDamageTypeKey = weaponDamageTypeKey;
Resistances = resistances;
IsAlive = true;
IsInvulnerable = false;
InvulnerabilityTimer = 0;
StatusEffects.Clear();
}
/// <summary>
/// Update per tick (status effect durations, invulnerability timer, combat timeout)
/// </summary>
public void Update(float deltaTime, long currentTick)
{
// Update invulnerability timer
if (InvulnerabilityTimer > 0)
{
InvulnerabilityTimer -= deltaTime;
if (InvulnerabilityTimer <= 0)
{
InvulnerabilityTimer = 0;
IsInvulnerable = false;
}
}
// Update status effects
var expired = new List<PlayerStatusEffect>();
foreach (var effect in StatusEffects)
{
effect.Duration -= deltaTime;
if (effect.Duration <= 0)
expired.Add(effect);
}
foreach (var e in expired)
StatusEffects.Remove(e);
// Combat timeout (5 seconds out of combat)
if (IsInCombat && currentTick - LastCombatTick > 50)
{
IsInCombat = false;
}
// Passive health regen when not in combat
if (!IsInCombat && IsAlive && Health < MaxHealth)
{
Health = Math.Min(MaxHealth, Health + MaxHealth * 0.02f * deltaTime);
}
}
}
+11
View File
@@ -8,6 +8,7 @@ public sealed class WorldPortalMetadata
public int? TargetRegionId { get; set; }
public int? TargetZoneX { get; set; }
public int? TargetZoneY { get; set; }
public int? TargetZoneZ { get; set; }
public int? TargetChunkX { get; set; }
public int? TargetChunkY { get; set; }
public int? TargetTileX { get; set; }
@@ -41,6 +42,7 @@ public sealed class WorldPortalMetadata
out int targetRegionId,
out int targetZoneX,
out int targetZoneY,
out int targetZoneZ,
out int targetChunkX,
out int targetChunkY,
out int targetTileX,
@@ -49,10 +51,19 @@ public sealed class WorldPortalMetadata
targetRegionId = m.TargetRegionId ?? 0;
targetZoneX = m.TargetZoneX ?? 0;
targetZoneY = m.TargetZoneY ?? 0;
targetZoneZ = m.TargetZoneZ ?? 0;
targetChunkX = m.TargetChunkX ?? 0;
targetChunkY = m.TargetChunkY ?? 0;
targetTileX = m.TargetTileX ?? 0;
targetTileY = m.TargetTileY ?? 0;
return targetRegionId > 0;
}
/// <summary>
/// Returns true if this is a building portal (Z-level change within same zone).
/// Building portals may omit TargetRegionId/ZoneX/ZoneY and only specify TargetZoneZ.
/// </summary>
public bool IsBuildingPortal =>
PortalType.Equals("building", StringComparison.OrdinalIgnoreCase) ||
PortalType.Equals("building_exit", StringComparison.OrdinalIgnoreCase);
}
+1
View File
@@ -13,6 +13,7 @@ public sealed class WorldSessionState
public int RegionId { get; set; }
public int ZoneX { get; set; }
public int ZoneY { get; set; }
public int ZoneZ { get; set; }
public int ChunkX { get; set; }
public int ChunkY { get; set; }
public float X { get; set; }
+771
View File
@@ -0,0 +1,771 @@
using System.Collections.Concurrent;
using DataServer.Data.Entities;
using DataServer.Data.Enums;
using GameServer.Dungeon;
using GameServer.Shared;
namespace GameServer.World;
/// <summary>
/// Per-zone runtime simulation implementing ICombatEnvironment.
/// Manages mobs, NPCs, projectiles, hazard zones, and interactive objects for a single world zone.
/// Activated when a player enters, deactivated after all players leave (with grace period).
/// </summary>
public sealed class WorldZoneSimulation : ICombatEnvironment
{
private const float DeactivateGraceSeconds = 60f;
public string ZoneKey { get; }
public int RegionId { get; }
public int ZoneX { get; }
public int ZoneY { get; }
public int ZoneZ { get; }
public bool IsPvpEnabled { get; set; }
// ICombatEnvironment
public ConcurrentDictionary<int, MobInstance> Mobs { get; } = new();
public ConcurrentDictionary<int, ProjectileInstance> Projectiles { get; } = new();
public ConcurrentDictionary<int, HazardZone> HazardZones { get; } = new();
public ConcurrentDictionary<int, NpcInstance> Npcs { get; } = new();
// Player tracking (keyed by CharacterId)
public ConcurrentDictionary<ulong, WorldPlayerCombatState> Players { get; } = new();
// Events queue for broadcasting to clients
public ConcurrentQueue<WorldCombatEvent> PendingEvents { get; } = new();
// Spawn management
public WorldMobSpawnTracker? MobSpawnTracker { get; private set; }
// Tick state
public long CurrentTick { get; private set; }
public int Tier => 1; // World mobs use base tier
private float _tickDelta = 0.1f; // 10Hz = 100ms
// Lifecycle
public bool IsActive { get; private set; }
public int PlayerCount => Players.Count;
private float _emptyTimer;
private bool _initialized;
// ID allocators
private int _nextProjectileId = 1;
private int _nextHazardId = 1;
private readonly List<(int MobDefinitionId, float X, float Y, int Tier)> _pendingSummons = new();
// Reference to walkability checker
private readonly WorldChunkCache _cache;
private WorldChunkCache.CachedRegion? _cachedRegion;
public WorldZoneSimulation(string zoneKey, int regionId, int zoneX, int zoneY, int zoneZ, WorldChunkCache cache)
{
ZoneKey = zoneKey;
RegionId = regionId;
ZoneX = zoneX;
ZoneY = zoneY;
ZoneZ = zoneZ;
_cache = cache;
}
/// <summary>
/// Set the cached region reference for walkability checks.
/// Must be called before ticking.
/// </summary>
public void SetRegion(WorldChunkCache.CachedRegion region)
{
_cachedRegion = region;
}
/// <summary>
/// Initialize the zone simulation with mob/NPC spawn data.
/// Called once when the zone first activates.
/// </summary>
public void Initialize(
Dictionary<int, DungeonMobDefinition> mobDefinitions,
List<(WorldChunkMobSpawnData spawnData, int chunkWorldOffsetX, int chunkWorldOffsetY)> mobSpawns,
List<(NpcInstance npc, int chunkWorldOffsetX, int chunkWorldOffsetY)> npcSpawns)
{
if (_initialized) return;
// Initialize mob spawns
MobSpawnTracker = new WorldMobSpawnTracker(mobDefinitions);
foreach (var (spawnData, offsetX, offsetY) in mobSpawns)
{
var mobs = MobSpawnTracker.RegisterSpawnPoint(spawnData, offsetX, offsetY);
foreach (var mob in mobs)
{
Mobs[mob.Id] = mob;
}
}
// Initialize NPCs
foreach (var (npc, _, _) in npcSpawns)
{
Npcs[npc.Id] = npc;
}
_initialized = true;
IsActive = true;
_emptyTimer = 0;
}
/// <summary>
/// Add a player to this zone simulation.
/// </summary>
public void AddPlayer(WorldPlayerCombatState player)
{
Players[player.CharacterId] = player;
_emptyTimer = 0; // Reset deactivation timer
}
/// <summary>
/// Remove a player from this zone simulation.
/// </summary>
public void RemovePlayer(ulong characterId)
{
Players.TryRemove(characterId, out _);
}
/// <summary>
/// Main tick - called each frame by WorldHandler (10Hz).
/// Returns true if zone should remain active, false if ready to deactivate.
/// </summary>
public bool Tick(long tick, float deltaTime)
{
if (!IsActive || !_initialized) return false;
CurrentTick = tick;
_tickDelta = deltaTime;
// Check if zone should deactivate
if (Players.IsEmpty)
{
_emptyTimer += deltaTime;
if (_emptyTimer >= DeactivateGraceSeconds)
{
IsActive = false;
return false;
}
}
else
{
_emptyTimer = 0;
}
// Update player combat states
foreach (var player in Players.Values)
{
player.Update(deltaTime, tick);
}
// Update mob AI
foreach (var mob in Mobs.Values)
{
if (!mob.IsAlive) continue;
MobAI.UpdateMob(mob, this, deltaTime);
}
// Process mob attacks (mobs in Attacking state)
ProcessMobAttacks(deltaTime);
// Update projectiles
UpdateProjectiles(deltaTime);
// Update hazard zones
UpdateHazardZones(deltaTime);
// Update NPC wander
UpdateNpcs(deltaTime);
// Process respawns
if (MobSpawnTracker != null)
{
var newMobs = MobSpawnTracker.Update(deltaTime);
foreach (var mob in newMobs)
{
Mobs[mob.Id] = mob;
PendingEvents.Enqueue(new WorldCombatEvent
{
Type = WorldCombatEventType.MobSpawn,
TargetMobId = mob.Id,
X = mob.X,
Y = mob.Y,
MobData = SerializeMob(mob)
});
}
}
// Process pending summons
ProcessPendingSummons();
return true;
}
#region Mob Attacks
private void ProcessMobAttacks(float deltaTime)
{
foreach (var mob in Mobs.Values)
{
if (!mob.IsAlive || mob.State != MobState.Attacking) continue;
if (!mob.TargetId.HasValue) continue;
// Find available ability
float hpPercent = mob.HpPercent;
var ability = mob.Abilities
.Where(a => a.IsAvailable(hpPercent) && mob.Mana >= a.Definition.ManaCost)
.FirstOrDefault();
if (ability == null) continue;
// Check range
var target = GetPlayer(mob.TargetId.Value);
if (target == null) { mob.TargetId = null; continue; }
float distance = GetDistance(mob.X, mob.Y, target.X, target.Y);
float abilityRange = ability.Definition.Range > 0 ? ability.Definition.Range : mob.Stats.AttackRange;
if (distance > abilityRange) continue;
// Execute ability
ability.CooldownRemaining = ability.Definition.Cooldown;
mob.Mana -= ability.Definition.ManaCost;
switch (ability.Definition.AbilityType)
{
case MobAbilityType.MeleeAttack:
case MobAbilityType.Cleave:
case MobAbilityType.ConeAttack:
ProcessMobDamageAbility(mob, target, ability);
break;
case MobAbilityType.ProjectileSingle:
case MobAbilityType.ProjectileAoe:
SpawnMobProjectile(mob, target, ability);
break;
case MobAbilityType.GroundAoe:
ProcessMobAoeAbility(mob, target, ability);
break;
case MobAbilityType.SummonSingle:
case MobAbilityType.SummonBulk:
// Handled by MobAI casting system
break;
default:
// Fallback to basic damage
ProcessMobDamageAbility(mob, target, ability);
break;
}
}
}
private void ProcessMobDamageAbility(MobInstance mob, IPlayerTarget target, MobAbilityState ability)
{
if (target.IsInvulnerable || !target.IsAlive) return;
int baseDamage = ability.Definition.BaseDamage;
string damageType = !string.IsNullOrEmpty(ability.Definition.DamageTypeKey)
? ability.Definition.DamageTypeKey
: mob.Stats.DamageTypeKey;
var result = CombatCalculator.CalculateMobToPlayerDamage(
mob, target, damageType, baseDamage,
target.Resistances);
target.Health -= result.FinalDamage;
target.IsInCombat = true;
target.LastCombatTick = CurrentTick;
PendingEvents.Enqueue(new WorldCombatEvent
{
Type = WorldCombatEventType.Damage,
SourceMobId = mob.Id,
TargetPlayerId = target.CharacterId,
Damage = result.FinalDamage,
DamageTypeKey = damageType,
X = target.X,
Y = target.Y
});
if (target.Health <= 0)
{
target.Health = 0;
target.IsAlive = false;
PendingEvents.Enqueue(new WorldCombatEvent
{
Type = WorldCombatEventType.PlayerDeath,
TargetPlayerId = target.CharacterId,
X = target.X,
Y = target.Y
});
}
}
private void SpawnMobProjectile(MobInstance mob, IPlayerTarget target, MobAbilityState ability)
{
float dx = target.X - mob.X;
float dy = target.Y - mob.Y;
float dist = MathF.Sqrt(dx * dx + dy * dy);
if (dist < 1f) return;
float speed = ability.Definition.ProjectileSpeed > 0 ? ability.Definition.ProjectileSpeed : 300f;
int id = Interlocked.Increment(ref _nextProjectileId);
var proj = new ProjectileInstance
{
Id = id,
SpawnTick = CurrentTick,
SourceType = ProjectileSource.Mob,
SourceMobId = mob.Id,
X = mob.X,
Y = mob.Y,
VelocityX = (dx / dist) * speed,
VelocityY = (dy / dist) * speed,
Speed = speed,
TargetX = target.X,
TargetY = target.Y,
Damage = ability.Definition.BaseDamage,
DamageTypeKey = !string.IsNullOrEmpty(ability.Definition.DamageTypeKey)
? ability.Definition.DamageTypeKey : mob.Stats.DamageTypeKey,
AoeRadius = ability.Definition.AoeRadius,
MaxRange = ability.Definition.Range > 0 ? ability.Definition.Range * 1.5f : 500f,
SpriteKey = !string.IsNullOrEmpty(ability.Definition.ProjectileSprite)
? ability.Definition.ProjectileSprite : "projectile_default",
CanHitPlayers = true,
CanHitMobs = false
};
Projectiles[proj.Id] = proj;
}
private void ProcessMobAoeAbility(MobInstance mob, IPlayerTarget target, MobAbilityState ability)
{
float radius = ability.Definition.AoeRadius > 0 ? ability.Definition.AoeRadius : 64f;
float centerX = target.X;
float centerY = target.Y;
foreach (var player in Players.Values)
{
if (!player.IsAlive || player.IsInvulnerable) continue;
float dist = GetDistance(centerX, centerY, player.X, player.Y);
if (dist > radius) continue;
int baseDamage = ability.Definition.BaseDamage;
string damageType = !string.IsNullOrEmpty(ability.Definition.DamageTypeKey)
? ability.Definition.DamageTypeKey : mob.Stats.DamageTypeKey;
var result = CombatCalculator.CalculateMobToPlayerDamage(
mob, player, damageType, baseDamage,
player.Resistances);
player.Health -= result.FinalDamage;
player.IsInCombat = true;
player.LastCombatTick = CurrentTick;
PendingEvents.Enqueue(new WorldCombatEvent
{
Type = WorldCombatEventType.Damage,
SourceMobId = mob.Id,
TargetPlayerId = player.CharacterId,
Damage = result.FinalDamage,
DamageTypeKey = damageType,
X = player.X,
Y = player.Y
});
if (player.Health <= 0)
{
player.Health = 0;
player.IsAlive = false;
PendingEvents.Enqueue(new WorldCombatEvent
{
Type = WorldCombatEventType.PlayerDeath,
TargetPlayerId = player.CharacterId,
X = player.X,
Y = player.Y
});
}
}
}
#endregion
#region Projectiles
private void UpdateProjectiles(float deltaTime)
{
var expired = new List<int>();
foreach (var proj in Projectiles.Values)
{
proj.X += proj.VelocityX * deltaTime;
proj.Y += proj.VelocityY * deltaTime;
proj.DistanceTraveled += proj.Speed * deltaTime;
// Check max range
if (proj.DistanceTraveled >= proj.MaxRange)
{
expired.Add(proj.Id);
continue;
}
// Check wall collision
if (!CanActorMoveTo(proj.X, proj.Y))
{
expired.Add(proj.Id);
continue;
}
// Check hit on players (mob projectiles)
if (proj.CanHitPlayers && proj.SourceType == ProjectileSource.Mob)
{
foreach (var player in Players.Values)
{
if (!player.IsAlive || player.IsInvulnerable) continue;
float dist = GetDistance(proj.X, proj.Y, player.X, player.Y);
if (dist <= 20f) // Hit radius
{
ApplyProjectileDamageToPlayer(proj, player);
expired.Add(proj.Id);
break;
}
}
}
// Check hit on mobs (player projectiles)
if (proj.CanHitMobs && proj.SourceType == ProjectileSource.Player)
{
foreach (var mob in Mobs.Values)
{
if (!mob.IsAlive) continue;
float dist = GetDistance(proj.X, proj.Y, mob.X, mob.Y);
if (dist <= 20f)
{
ApplyProjectileDamageToMob(proj, mob);
expired.Add(proj.Id);
break;
}
}
}
}
foreach (var id in expired)
Projectiles.TryRemove(id, out _);
}
private void ApplyProjectileDamageToPlayer(ProjectileInstance proj, WorldPlayerCombatState player)
{
var result = CombatCalculator.CalculateMobToPlayerDamage(
Mobs.TryGetValue(proj.SourceMobId, out var srcMob) ? srcMob : null!,
player, proj.DamageTypeKey, proj.Damage, player.Resistances);
player.Health -= result.FinalDamage;
player.IsInCombat = true;
player.LastCombatTick = CurrentTick;
PendingEvents.Enqueue(new WorldCombatEvent
{
Type = WorldCombatEventType.Damage,
SourceMobId = proj.SourceMobId,
TargetPlayerId = player.CharacterId,
Damage = result.FinalDamage,
DamageTypeKey = proj.DamageTypeKey,
X = player.X,
Y = player.Y
});
if (player.Health <= 0)
{
player.Health = 0;
player.IsAlive = false;
PendingEvents.Enqueue(new WorldCombatEvent
{
Type = WorldCombatEventType.PlayerDeath,
TargetPlayerId = player.CharacterId,
X = player.X,
Y = player.Y
});
}
}
private void ApplyProjectileDamageToMob(ProjectileInstance proj, MobInstance mob)
{
var player = GetPlayer(proj.SourcePlayerId);
if (player == null) return;
var result = CombatCalculator.CalculatePlayerToMobDamage(
player, mob, proj.DamageTypeKey, proj.Damage);
mob.Health -= result.FinalDamage;
PendingEvents.Enqueue(new WorldCombatEvent
{
Type = WorldCombatEventType.Damage,
SourcePlayerId = proj.SourcePlayerId,
TargetMobId = mob.Id,
Damage = result.FinalDamage,
DamageTypeKey = proj.DamageTypeKey,
X = mob.X,
Y = mob.Y
});
if (mob.Health <= 0)
{
mob.Health = 0;
mob.IsAlive = false;
mob.State = MobState.Dead;
mob.CurrentAnimation = mob.GetDirectionalAnimation("death");
MobSpawnTracker?.OnMobDied(mob.Id);
PendingEvents.Enqueue(new WorldCombatEvent
{
Type = WorldCombatEventType.MobDeath,
TargetMobId = mob.Id,
SourcePlayerId = proj.SourcePlayerId,
X = mob.X,
Y = mob.Y
});
}
}
#endregion
#region Hazard Zones
private void UpdateHazardZones(float deltaTime)
{
var expired = new List<int>();
foreach (var hz in HazardZones.Values)
{
hz.Duration -= deltaTime;
if (hz.Duration <= 0)
{
expired.Add(hz.Id);
continue;
}
hz.NextTickIn -= deltaTime;
if (hz.NextTickIn <= 0)
{
hz.NextTickIn = hz.TickInterval;
// Damage players in radius
foreach (var player in Players.Values)
{
if (!player.IsAlive || player.IsInvulnerable) continue;
float dist = GetDistance(hz.X, hz.Y, player.X, player.Y);
if (dist > hz.Radius) continue;
var mob = Mobs.TryGetValue(hz.SourceMobId, out var m) ? m : null;
var result = CombatCalculator.CalculateMobToPlayerDamage(
mob!, player, hz.DamageTypeKey, hz.DamagePerTick, player.Resistances);
player.Health -= result.FinalDamage;
player.IsInCombat = true;
player.LastCombatTick = CurrentTick;
PendingEvents.Enqueue(new WorldCombatEvent
{
Type = WorldCombatEventType.Damage,
SourceMobId = hz.SourceMobId,
TargetPlayerId = player.CharacterId,
Damage = result.FinalDamage,
DamageTypeKey = hz.DamageTypeKey,
X = player.X,
Y = player.Y
});
if (player.Health <= 0)
{
player.Health = 0;
player.IsAlive = false;
PendingEvents.Enqueue(new WorldCombatEvent
{
Type = WorldCombatEventType.PlayerDeath,
TargetPlayerId = player.CharacterId,
X = player.X,
Y = player.Y
});
}
}
}
}
foreach (var id in expired)
HazardZones.TryRemove(id, out _);
}
#endregion
#region NPCs
private void UpdateNpcs(float deltaTime)
{
foreach (var npc in Npcs.Values)
{
if (!npc.IsAlive || !npc.CanWander) continue;
npc.NextWanderIn -= deltaTime;
if (npc.NextWanderIn <= 0)
{
npc.NextWanderIn = npc.WanderIntervalSeconds;
// Pick random point within wander radius
var rng = new Random();
float angle = (float)(rng.NextDouble() * Math.PI * 2);
float dist = (float)(rng.NextDouble() * npc.WanderRadiusPx);
float targetX = npc.SpawnX + MathF.Cos(angle) * dist;
float targetY = npc.SpawnY + MathF.Sin(angle) * dist;
if (CanActorMoveTo(targetX, targetY))
{
// Simple linear move (NPCs don't need full pathfinding)
float moveSpeed = 30f * deltaTime;
float dx = targetX - npc.X;
float dy = targetY - npc.Y;
float moveDist = MathF.Sqrt(dx * dx + dy * dy);
if (moveDist > 1f)
{
npc.X += (dx / moveDist) * Math.Min(moveSpeed, moveDist);
npc.Y += (dy / moveDist) * Math.Min(moveSpeed, moveDist);
}
}
}
}
}
#endregion
#region ICombatEnvironment Implementation
public bool CanActorMoveTo(float x, float y)
{
if (_cachedRegion == null) return true; // Fallback if region not set
return _cache.IsPositionWalkable(_cachedRegion, ZoneZ, x, y, false);
}
public IEnumerable<IPlayerTarget> GetAlivePlayers()
=> Players.Values.Where(p => p.IsAlive);
public IPlayerTarget? GetPlayer(ulong characterId)
=> Players.TryGetValue(characterId, out var p) ? p : null;
public void RequestMobSummon(int mobDefinitionId, float x, float y, int tier)
{
_pendingSummons.Add((mobDefinitionId, x, y, tier));
}
#endregion
#region Helpers
private void ProcessPendingSummons()
{
// World zone doesn't support dynamic mob summoning yet (would need mob definitions)
// Clear to prevent memory leak
_pendingSummons.Clear();
}
public object SerializeMob(MobInstance mob)
{
return new
{
id = mob.Id,
definitionId = mob.DefinitionId,
name = mob.Name,
x = mob.X,
y = mob.Y,
health = mob.Health,
maxHealth = mob.MaxHealth,
isAlive = mob.IsAlive,
state = mob.State.ToString(),
animation = mob.CurrentAnimation,
facing = mob.FacingDirection,
spriteConfig = mob.SpriteConfigJson,
tintColor = mob.TintColor,
scale = mob.Scale
};
}
public object SerializeNpc(NpcInstance npc)
{
return new
{
id = npc.Id,
definitionId = npc.DefinitionId,
name = npc.Name,
x = npc.X,
y = npc.Y,
health = npc.Health,
maxHealth = npc.MaxHealth,
isAlive = npc.IsAlive,
canShop = npc.CanShop,
hasDialog = npc.HasDialog,
animation = npc.CurrentAnimation,
spriteConfig = npc.SpriteConfigJson,
tintColor = npc.TintColor,
scale = npc.Scale
};
}
private static float GetDistance(float x1, float y1, float x2, float y2)
{
float dx = x2 - x1;
float dy = y2 - y1;
return MathF.Sqrt(dx * dx + dy * dy);
}
/// <summary>
/// Clean up zone state when deactivating
/// </summary>
public void Deactivate()
{
IsActive = false;
Mobs.Clear();
Npcs.Clear();
Projectiles.Clear();
HazardZones.Clear();
Players.Clear();
while (PendingEvents.TryDequeue(out _)) { }
_initialized = false;
}
#endregion
}
#region Combat Events
public enum WorldCombatEventType
{
Damage,
MobDeath,
PlayerDeath,
MobSpawn,
ProjectileSpawn,
AbilityUsed,
PlayerAttack,
PvpDamage
}
public sealed class WorldCombatEvent
{
public WorldCombatEventType Type { get; set; }
// Source
public int SourceMobId { get; set; }
public ulong SourcePlayerId { get; set; }
// Target
public int TargetMobId { get; set; }
public ulong TargetPlayerId { get; set; }
// Data
public int Damage { get; set; }
public string DamageTypeKey { get; set; } = "physical";
public float X { get; set; }
public float Y { get; set; }
// For mob spawn events
public object? MobData { get; set; }
}
#endregion
+45
View File
@@ -121,6 +121,51 @@ public static class OpCodes
/// </summary>
public const int WORLD_CHUNK_DELTA = 712;
// ===== World Combat (720-739) =====
/// <summary>Server -> Client: Combat state update (mob states, damage events, deaths)</summary>
public const int WORLD_COMBAT_STATE = 720;
/// <summary>Client -> Server: Player attacks a mob, player, or object in the world</summary>
public const int WORLD_ATTACK = 721;
/// <summary>Client -> Server: Request loot from dead world mob</summary>
public const int WORLD_MOB_LOOT_REQUEST = 722;
/// <summary>Server -> Client: Loot contents from world mob</summary>
public const int WORLD_MOB_LOOT_RESULT = 723;
// ===== World NPC (740-749) =====
/// <summary>Client -> Server: Interact with world NPC</summary>
public const int WORLD_NPC_INTERACT = 740;
/// <summary>Server -> Client: NPC interaction state (dialog/shop)</summary>
public const int WORLD_NPC_INTERACT_STATE = 741;
/// <summary>Client -> Server: Select dialog option</summary>
public const int WORLD_NPC_DIALOG_SELECT = 742;
/// <summary>Server -> Client: Dialog result</summary>
public const int WORLD_NPC_DIALOG_RESULT = 743;
/// <summary>Client -> Server: NPC shop buy/sell</summary>
public const int WORLD_NPC_SHOP_ACTION = 744;
/// <summary>Server -> Client: Shop action result</summary>
public const int WORLD_NPC_SHOP_RESULT = 745;
// ===== World Object (750-759) =====
/// <summary>Client -> Server: Interact with world object</summary>
public const int WORLD_OBJECT_INTERACT = 750;
/// <summary>Server -> Client: Object interaction result</summary>
public const int WORLD_OBJECT_INTERACT_RESULT = 751;
/// <summary>Server -> Client: Object state change broadcast</summary>
public const int WORLD_OBJECT_STATE = 752;
// ===== Error Messages (900-999) =====
/// <summary>
@@ -207,7 +207,7 @@ public class IndexModel : AdminPageModel
}
await EnsureZonesAsync(region);
var zone = await _db.WorldZones.FirstAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY);
var zone = await _db.WorldZones.FirstAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY && z.ZoneZ == 0);
var chunks = await _db.WorldChunks
.Where(c => c.WorldZoneId == zone.Id)
@@ -901,8 +901,9 @@ public class IndexModel : AdminPageModel
private async Task EnsureZonesAsync(WorldRegion region)
{
// Only auto-create Z=0 (ground level) zones
var existing = await _db.WorldZones
.Where(z => z.RegionId == region.Id)
.Where(z => z.RegionId == region.Id && z.ZoneZ == 0)
.Select(z => new { z.ZoneX, z.ZoneY })
.ToListAsync();
@@ -956,7 +957,7 @@ public class IndexModel : AdminPageModel
await EnsureZonesAsync(region);
var zone = await _db.WorldZones
.FirstOrDefaultAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY && z.IsEnabled);
.FirstOrDefaultAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY && z.ZoneZ == 0 && z.IsEnabled);
if (zone == null)
return (false, "zone_not_found", region, null, null);
@@ -986,16 +987,17 @@ public class IndexModel : AdminPageModel
return x >= 0 && y >= 0 && x < width && y < height;
}
private void PublishDelta(int regionId, int zoneX, int zoneY, int chunkX, int chunkY, long fromVersion, long toVersion, object op)
private void PublishDelta(int regionId, int zoneX, int zoneY, int chunkX, int chunkY, long fromVersion, long toVersion, object op, int zoneZ = 0)
{
_deltaHub.Publish(
ChunkKey(regionId, zoneX, zoneY, chunkX, chunkY),
ChunkKey(regionId, zoneX, zoneY, chunkX, chunkY, zoneZ),
new
{
kind = "chunk_delta",
regionId,
zoneX,
zoneY,
zoneZ,
chunkX,
chunkY,
fromVersion,
@@ -1004,8 +1006,8 @@ public class IndexModel : AdminPageModel
});
}
private static string ChunkKey(int regionId, int zoneX, int zoneY, int chunkX, int chunkY)
=> $"{regionId}:{zoneX}:{zoneY}:{chunkX}:{chunkY}";
private static string ChunkKey(int regionId, int zoneX, int zoneY, int chunkX, int chunkY, int zoneZ = 0)
=> $"{regionId}:{zoneX}:{zoneY}:{zoneZ}:{chunkX}:{chunkY}";
private static string NormalizeCdnBaseUrl(string? baseUrl)
{
+1
View File
@@ -55,6 +55,7 @@ public class DungeonCharacter
public int? WorldRegionId { get; set; }
public int? WorldZoneX { get; set; }
public int? WorldZoneY { get; set; }
public int? WorldZoneZ { get; set; }
public int? WorldChunkX { get; set; }
public int? WorldChunkY { get; set; }
public float? WorldX { get; set; }
+3 -1
View File
@@ -39,10 +39,12 @@ public class WorldZone
public int ZoneX { get; set; }
public int ZoneY { get; set; }
public int ZoneZ { get; set; } = 0; // 0 = ground, positive = upper floors, negative = basements
[MaxLength(64)]
public string Name { get; set; } = "";
public bool IsPvpEnabled { get; set; } = false;
public bool IsEnabled { get; set; } = true;
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
@@ -166,7 +168,7 @@ public sealed class WorldZoneConfig : IEntityTypeConfiguration<WorldZone>
{
public void Configure(EntityTypeBuilder<WorldZone> e)
{
e.HasIndex(x => new { x.RegionId, x.ZoneX, x.ZoneY }).IsUnique();
e.HasIndex(x => new { x.RegionId, x.ZoneX, x.ZoneY, x.ZoneZ }).IsUnique();
e.HasOne(x => x.Region)
.WithMany()
.HasForeignKey(x => x.RegionId)