| 1 | import { Component } from "../ecs/components.js"; |
| 2 | import { itemDefinition } from "../../../shared/definitions/items.js"; |
| 3 | import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js"; |
| 4 | import { mobDefinition } from "../../../shared/definitions/mobs.js"; |
| 5 | import { |
| 6 | mobCanFightType, |
| 7 | mobCanFight, |
| 8 | mobMeleeAttackProfile, |
| 9 | mobSkillLevels, |
| 10 | mobIsAggressive, |
| 11 | mobAggroRangeTiles |
| 12 | } from "../../../shared/definitions/mobCombat.js"; |
| 13 | import { spellDefinition } from "../../../shared/definitions/spells.js"; |
| 14 | import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js"; |
| 15 | import { |
| 16 | effectiveHitSkillInDarkness, |
| 17 | aggroDistanceMultiplier |
| 18 | } from "../../../shared/combat/darkness.js"; |
| 19 | import { |
| 20 | bakedTileLight01, |
| 21 | entityLightAtTile, |
| 22 | tileCombatLight01, |
| 23 | tileIndexLocal |
| 24 | } from "../../../shared/lighting/combatLight.js"; |
| 25 | import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js"; |
| 26 | import { |
| 27 | effectiveSkillLevel, |
| 28 | equipmentBonusesFromSlots |
| 29 | } from "../../../shared/equipment/stats.js"; |
| 30 | import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js"; |
| 31 | import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js"; |
| 32 | import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js"; |
| 33 | import { chunkBoundsAround, findPath } from "../navigation/astar.js"; |
| 34 | import { findPathToNearestGoal } from "../../../shared/navigation/bfs.js"; |
| 35 | import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js"; |
| 36 | import { rayReaches } from "../../../shared/lighting/raycast.js"; |
| 37 | import { tileToChunk } from "../world/coordinates.js"; |
| 38 | import { stackQuantity } from "../../../shared/items/inventory.js"; |
| 39 | import { addGroundItem, publicGroundItem } from "../items/bags.js"; |
| 40 | import { resolveItemDualTint } from "../../../shared/render/tint.js"; |
| 41 | import { castMobAttackSpell } from "../spells/mobCast.js"; |
| 42 | import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js"; |
| 43 | |
| 44 | export function chebyshev (ax, ay, bx, by) |
| 45 | { |
| 46 | return Math.max(Math.abs(ax - bx), Math.abs(ay - by)); |
| 47 | } |
| 48 | |
| 49 | export function attackProfileOf (ecs, handle) |
| 50 | { |
| 51 | const creature = ecs.get(handle, Component.creature); |
| 52 | const level = creatureLevel(ecs, handle); |
| 53 | const equipment = ecs.get(handle, Component.equipment); |
| 54 | const weapon = equipment?.slots?.weapon; |
| 55 | if (weapon?.itemId != null) |
| 56 | { |
| 57 | const attack = itemDefinition(weapon.itemId)?.equipment?.attack; |
| 58 | if (attack) |
| 59 | { |
| 60 | const profile = { ...attack }; |
| 61 | if (creature) |
| 62 | { profile.mobAttackSkill = level; } |
| 63 | return profile; |
| 64 | } |
| 65 | } |
| 66 | if (creature) |
| 67 | { |
| 68 | const def = mobDefinition(creature.mobTypeId); |
| 69 | if (mobCanFightType(creature.mobTypeId)) |
| 70 | { return mobMeleeAttackProfile(def, level); } |
| 71 | } |
| 72 | return { ...UNARMED_ATTACK }; |
| 73 | } |
| 74 | |
| 75 | function creatureLevel (ecs, handle) |
| 76 | { |
| 77 | const creature = ecs.get(handle, Component.creature); |
| 78 | if (!creature) |
| 79 | { return 1; } |
| 80 | if (creature.level != null) |
| 81 | { return Math.max(1, creature.level | 0 || 1); } |
| 82 | const origin = ecs.get(handle, Component.spawnOrigin); |
| 83 | if (origin?.level != null) |
| 84 | { return Math.max(1, origin.level | 0 || 1); } |
| 85 | const def = mobDefinition(creature.mobTypeId); |
| 86 | return Math.max(1, def?.attackSkill | 0 || 1); |
| 87 | } |
| 88 | |
| 89 | export function weaponEquipmentKind (ecs, handle) |
| 90 | { |
| 91 | const equipment = ecs.get(handle, Component.equipment); |
| 92 | const weapon = equipment?.slots?.weapon; |
| 93 | if (!weapon?.itemId) |
| 94 | { return null; } |
| 95 | return itemDefinition(weapon.itemId)?.equipment?.kind ?? null; |
| 96 | } |
| 97 | |
| 98 | export function ensureMobCombat (ecs, entityId) |
| 99 | { |
| 100 | const handle = ecs.handleOf(entityId); |
| 101 | if (handle == null) |
| 102 | { return false; } |
| 103 | const creature = ecs.get(handle, Component.creature); |
| 104 | if (!creature || !mobCanFightType(creature.mobTypeId)) |
| 105 | { return false; } |
| 106 | const def = mobDefinition(creature.mobTypeId); |
| 107 | const level = creatureLevel(ecs, handle); |
| 108 | if (!ecs.get(handle, Component.combat)) |
| 109 | { ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); } |
| 110 | if (!ecs.get(handle, Component.skills)) |
| 111 | { ecs.add(handle, Component.skills, { levels: mobSkillLevels(def, level) }); } |
| 112 | return true; |
| 113 | } |
| 114 | |
| 115 | function attackerSkillLevel (skills, profile, skillId) |
| 116 | { |
| 117 | if (profile.mobAttackSkill != null) |
| 118 | { return profile.mobAttackSkill; } |
| 119 | return skillLevel(skills, skillId); |
| 120 | } |
| 121 | |
| 122 | function defenderSkillLevel (skills, skillId, equipment = null, settings = null) |
| 123 | { |
| 124 | const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots, settings) : {}; |
| 125 | return effectiveSkillLevel(skills, skillId, bonuses); |
| 126 | } |
| 127 | |
| 128 | function playerCombatLevels (ecs, handle, profile, settings = null) |
| 129 | { |
| 130 | const skills = ecs.get(handle, Component.skills); |
| 131 | const equipment = ecs.get(handle, Component.equipment); |
| 132 | const bonuses = equipmentBonusesFromSlots(equipment?.slots, settings); |
| 133 | const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now()); |
| 134 | bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0); |
| 135 | bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0); |
| 136 | |
| 137 | return { |
| 138 | hitLevel: skillLevel(skills, profile.hitSkillId ?? SkillId.unarmed), |
| 139 | damageLevel: effectiveSkillLevel(skills, profile.damageSkillId ?? SkillId.strength, bonuses), |
| 140 | agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses), |
| 141 | defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses) |
| 142 | }; |
| 143 | } |
| 144 | |
| 145 | export function isUntargetable (ecs, handle) |
| 146 | { |
| 147 | const creature = ecs.get(handle, Component.creature); |
| 148 | if (!creature) |
| 149 | { return false; } |
| 150 | return !!mobDefinition(creature.mobTypeId)?.untargetable; |
| 151 | } |
| 152 | |
| 153 | export function engageTarget (ecs, attackerId, targetId, now = Date.now()) |
| 154 | { |
| 155 | const handle = ecs.handleOf(attackerId); |
| 156 | if (handle == null) |
| 157 | { return false; } |
| 158 | let combat = ecs.get(handle, Component.combat); |
| 159 | if (!combat) |
| 160 | { combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); } |
| 161 | const targetChanged = combat.targetEntityId !== targetId; |
| 162 | combat.targetEntityId = targetId; |
| 163 | if (targetChanged) |
| 164 | { |
| 165 | // New engage (or switch): allow an immediate swing; keep cadence if already on this target. |
| 166 | combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now); |
| 167 | const path = ecs.get(handle, Component.path); |
| 168 | if (path) |
| 169 | { path.tiles = []; } |
| 170 | } |
| 171 | return true; |
| 172 | } |
| 173 | |
| 174 | export function clearEngage (ecs, entityId) |
| 175 | { |
| 176 | const handle = ecs.handleOf(entityId); |
| 177 | const combat = handle != null ? ecs.get(handle, Component.combat) : null; |
| 178 | if (combat) |
| 179 | { combat.targetEntityId = null; } |
| 180 | } |
| 181 | |
| 182 | export function hasCombatLineOfSight (world, fromX, fromY, toX, toY) |
| 183 | { |
| 184 | const isClear = world.isClearForRangedAttack |
| 185 | ? (x, y) => world.isClearForRangedAttack(x, y) |
| 186 | : (x, y) => world.isEnterable(x, y); |
| 187 | return rayReaches(fromX, fromY, toX, toY, isClear); |
| 188 | } |
| 189 | |
| 190 | /** Target-tile lighting 0–1 (baked + entity lights + time of day). */ |
| 191 | export function tileLightAt (world, tileX, tileY, now = Date.now()) |
| 192 | { |
| 193 | const data = world.chunkData?.(tileToChunk(tileX), tileToChunk(tileY)); |
| 194 | const index = tileIndexLocal(tileX, tileY); |
| 195 | const baked = bakedTileLight01(data?.light, index); |
| 196 | const entity = entityLightAtTile(world.ecs, Component, tileX, tileY, now); |
| 197 | const worldTime = world.worldTime?.(now); |
| 198 | return tileCombatLight01({ |
| 199 | bakedLight01: baked, |
| 200 | entityLight01: entity, |
| 201 | worldHour: worldTime?.hour ?? 12, |
| 202 | nightDarkness: world.settings?.nightDarkness ?? 0.72 |
| 203 | }); |
| 204 | } |
| 205 | |
| 206 | function arrowStackInOffhand (equipment) |
| 207 | { |
| 208 | const stack = equipment?.slots?.offhand; |
| 209 | if (!stack) |
| 210 | { return null; } |
| 211 | const def = itemDefinition(stack.itemId); |
| 212 | if (def?.equipment?.kind !== EquipmentKind.arrowAmmo) |
| 213 | { return null; } |
| 214 | return stack; |
| 215 | } |
| 216 | |
| 217 | function consumeArrow (ecs, handle) |
| 218 | { |
| 219 | const equipment = ecs.get(handle, Component.equipment); |
| 220 | const stack = arrowStackInOffhand(equipment); |
| 221 | if (!stack || stackQuantity(stack.quantity) <= 0) |
| 222 | { return false; } |
| 223 | if (stackQuantity(stack.quantity) <= 1) |
| 224 | { equipment.slots.offhand = null; } |
| 225 | else |
| 226 | { stack.quantity = stackQuantity(stack.quantity) - 1; } |
| 227 | return true; |
| 228 | } |
| 229 | |
| 230 | /** Fixed `quantity`, or inclusive `quantityMin`/`quantityMax` range (default 1). */ |
| 231 | function rollDropQuantity (drop) |
| 232 | { |
| 233 | if (drop.quantityMin != null || drop.quantityMax != null) |
| 234 | { |
| 235 | const min = Math.max(0, Math.floor(Number(drop.quantityMin ?? 1))); |
| 236 | const max = Math.max(min, Math.floor(Number(drop.quantityMax ?? min))); |
| 237 | return min + Math.floor(Math.random() * (max - min + 1)); |
| 238 | } |
| 239 | return Math.max(1, Math.floor(Number(drop.quantity ?? 1))); |
| 240 | } |
| 241 | |
| 242 | function spawnMobDrops (world, targetHandle, tileX, tileY, now, attackerId = null) |
| 243 | { |
| 244 | const creature = world.ecs.get(targetHandle, Component.creature); |
| 245 | if (!creature) |
| 246 | { return []; } |
| 247 | const def = mobDefinition(creature.mobTypeId); |
| 248 | const mobName = entityCombatDisplayName(world.ecs, targetHandle) |
| 249 | || def?.displayName |
| 250 | || "a creature"; |
| 251 | let killerName = "someone"; |
| 252 | if (attackerId != null) |
| 253 | { |
| 254 | const attackerHandle = world.ecs.handleOf(attackerId); |
| 255 | if (attackerHandle != null) |
| 256 | { killerName = entityCombatDisplayName(world.ecs, attackerHandle) || "someone"; } |
| 257 | } |
| 258 | const origin = lootOrigin(mobName, killerName); |
| 259 | const events = []; |
| 260 | for (const drop of def?.drops ?? []) |
| 261 | { |
| 262 | if (Math.random() > (drop.chance ?? 1)) |
| 263 | { continue; } |
| 264 | const quantity = rollDropQuantity(drop); |
| 265 | if (quantity <= 0) |
| 266 | { continue; } |
| 267 | const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1); |
| 268 | const stack = attachOrigins({ |
| 269 | itemId: drop.itemId, |
| 270 | quantity, |
| 271 | origins: [{ origin, quantity }] |
| 272 | }); |
| 273 | const item = { |
| 274 | groundItemId, |
| 275 | tileX, |
| 276 | tileY, |
| 277 | stack, |
| 278 | droppedAt: now, |
| 279 | expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000), |
| 280 | source: "mob-drop" |
| 281 | }; |
| 282 | addGroundItem(world, item); |
| 283 | events.push({ |
| 284 | type: "ground-item-appear", |
| 285 | ...publicGroundItem(item), |
| 286 | stack: item.stack, |
| 287 | droppedAt: item.droppedAt, |
| 288 | source: item.source, |
| 289 | expiresAt: item.expiresAt |
| 290 | }); |
| 291 | } |
| 292 | return events; |
| 293 | } |
| 294 | |
| 295 | function entityCombatDisplayName (ecs, handle) |
| 296 | { |
| 297 | const appearance = ecs.get(handle, Component.appearance); |
| 298 | const fromAppearance = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim(); |
| 299 | if (fromAppearance) |
| 300 | { return fromAppearance; } |
| 301 | const creature = ecs.get(handle, Component.creature); |
| 302 | if (creature?.mobTypeId) |
| 303 | { |
| 304 | const def = mobDefinition(creature.mobTypeId); |
| 305 | if (def?.displayName) |
| 306 | { return def.displayName; } |
| 307 | } |
| 308 | return null; |
| 309 | } |
| 310 | |
| 311 | function projectileDualTintFromAttacker (ecs, handle) |
| 312 | { |
| 313 | const equipment = ecs.get(handle, Component.equipment); |
| 314 | const stack = arrowStackInOffhand(equipment); |
| 315 | if (!stack) |
| 316 | { return null; } |
| 317 | return resolveItemDualTint(stack, itemDefinition(stack.itemId)); |
| 318 | } |
| 319 | |
| 320 | function publicDualTint (dualTint) |
| 321 | { |
| 322 | if (!dualTint) |
| 323 | { return null; } |
| 324 | return { |
| 325 | shaftTint: dualTint.shaft, |
| 326 | tipTint: dualTint.tip |
| 327 | }; |
| 328 | } |
| 329 | |
| 330 | function missProjectileTile (targetTileX, targetTileY, rng = Math.random) |
| 331 | { |
| 332 | const angle = rng() * Math.PI * 2; |
| 333 | const dist = rng(); |
| 334 | return { |
| 335 | tileX: Math.round(targetTileX + Math.cos(angle) * dist), |
| 336 | tileY: Math.round(targetTileY + Math.sin(angle) * dist) |
| 337 | }; |
| 338 | } |
| 339 | |
| 340 | /** |
| 341 | * Aggressive mobs auto-engage the nearest player character within aggro range |
| 342 | * when they have line of sight. Does nothing while already engaged. |
| 343 | */ |
| 344 | export function stepAggression (world, now = Date.now()) |
| 345 | { |
| 346 | for (const entity of world.ecs.query(Component.creature, Component.position)) |
| 347 | { |
| 348 | if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY)) |
| 349 | { continue; } |
| 350 | const def = mobDefinition(entity.creature.mobTypeId); |
| 351 | const origin = world.ecs.get(entity.handle, Component.spawnOrigin); |
| 352 | const aggressive = origin |
| 353 | ? !!origin.aggressive |
| 354 | : mobIsAggressive(def); |
| 355 | if (!aggressive || !mobCanFight(def)) |
| 356 | { continue; } |
| 357 | if (world.ecs.has(entity.handle, Component.dead)) |
| 358 | { continue; } |
| 359 | const health = world.ecs.get(entity.handle, Component.health); |
| 360 | if (health && health.current <= 0) |
| 361 | { continue; } |
| 362 | const combat = world.ecs.get(entity.handle, Component.combat); |
| 363 | if (combat?.targetEntityId != null) |
| 364 | { continue; } |
| 365 | |
| 366 | const range = mobAggroRangeTiles(def); |
| 367 | let bestId = null; |
| 368 | let bestDist = Infinity; |
| 369 | for (const player of world.ecs.query(Component.character, Component.position)) |
| 370 | { |
| 371 | if (world.ecs.has(player.handle, Component.dead)) |
| 372 | { continue; } |
| 373 | const playerHealth = world.ecs.get(player.handle, Component.health); |
| 374 | if (playerHealth && playerHealth.current <= 0) |
| 375 | { continue; } |
| 376 | const dist = chebyshev( |
| 377 | entity.position.tileX, |
| 378 | entity.position.tileY, |
| 379 | player.position.tileX, |
| 380 | player.position.tileY |
| 381 | ); |
| 382 | if (dist < 1 || dist > range) |
| 383 | { continue; } |
| 384 | let effectiveDist = dist; |
| 385 | if (dist > 1) |
| 386 | { |
| 387 | const light = tileLightAt(world, player.position.tileX, player.position.tileY); |
| 388 | effectiveDist = dist * aggroDistanceMultiplier(light); |
| 389 | } |
| 390 | if (effectiveDist > range) |
| 391 | { continue; } |
| 392 | if (!hasCombatLineOfSight( |
| 393 | world, |
| 394 | entity.position.tileX, |
| 395 | entity.position.tileY, |
| 396 | player.position.tileX, |
| 397 | player.position.tileY |
| 398 | )) |
| 399 | { continue; } |
| 400 | if (dist < bestDist) |
| 401 | { |
| 402 | bestDist = dist; |
| 403 | bestId = player.entityId; |
| 404 | } |
| 405 | } |
| 406 | if (bestId == null) |
| 407 | { continue; } |
| 408 | if (!ensureMobCombat(world.ecs, entity.entityId)) |
| 409 | { continue; } |
| 410 | engageTarget(world.ecs, entity.entityId, bestId, now); |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | /** Local entity handle or a nearby ghost snapshot for cross-worker combat. */ |
| 415 | export function resolveCombatTarget (world, targetId) |
| 416 | { |
| 417 | const handle = world.ecs.handleOf(targetId); |
| 418 | if (handle != null) |
| 419 | { |
| 420 | const pos = world.ecs.get(handle, Component.position); |
| 421 | if (!pos) |
| 422 | { return null; } |
| 423 | if (isUntargetable(world.ecs, handle)) |
| 424 | { return null; } |
| 425 | return { |
| 426 | local: true, |
| 427 | handle, |
| 428 | pos, |
| 429 | health: world.ecs.get(handle, Component.health) |
| 430 | }; |
| 431 | } |
| 432 | const ghost = world.ghosts?.get?.(targetId); |
| 433 | if (!ghost || ghost.untargetable) |
| 434 | { return null; } |
| 435 | const health = ghost.health != null |
| 436 | ? { current: ghost.health, max: ghost.maxHealth ?? ghost.health } |
| 437 | : null; |
| 438 | return { |
| 439 | local: false, |
| 440 | handle: null, |
| 441 | pos: { tileX: ghost.tileX, tileY: ghost.tileY }, |
| 442 | health |
| 443 | }; |
| 444 | } |
| 445 | |
| 446 | function attackerCombatLevels (ecs, attackerHandle, profile, settings = null) |
| 447 | { |
| 448 | const attackerCharacter = ecs.get(attackerHandle, Component.character); |
| 449 | if (attackerCharacter) |
| 450 | { return playerCombatLevels(ecs, attackerHandle, profile, settings); } |
| 451 | const skills = ecs.get(attackerHandle, Component.skills); |
| 452 | return { |
| 453 | hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId), |
| 454 | damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId), |
| 455 | agilityLevel: skillLevel(skills, SkillId.agility), |
| 456 | defenceLevel: skillLevel(skills, SkillId.defence) |
| 457 | }; |
| 458 | } |
| 459 | |
| 460 | export function stepCombat (world, now = Date.now()) |
| 461 | { |
| 462 | const events = []; |
| 463 | for (const entity of world.ecs.query(Component.combat, Component.position)) |
| 464 | { |
| 465 | if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY)) |
| 466 | { continue; } |
| 467 | const combat = entity.combat; |
| 468 | const targetId = combat.targetEntityId; |
| 469 | if (targetId == null) |
| 470 | { continue; } |
| 471 | const target = resolveCombatTarget(world, targetId); |
| 472 | if (!target) |
| 473 | { |
| 474 | combat.targetEntityId = null; |
| 475 | continue; |
| 476 | } |
| 477 | if (target.health && target.health.current <= 0) |
| 478 | { |
| 479 | combat.targetEntityId = null; |
| 480 | continue; |
| 481 | } |
| 482 | |
| 483 | const profile = attackProfileOf(world.ecs, entity.handle); |
| 484 | const targetPos = target.pos; |
| 485 | const isCreature = !!world.ecs.get(entity.handle, Component.creature) |
| 486 | && !world.ecs.get(entity.handle, Component.character); |
| 487 | const weaponKind = weaponEquipmentKind(world.ecs, entity.handle); |
| 488 | const isStaff = weaponKind === EquipmentKind.staff; |
| 489 | |
| 490 | if (profile.mode === "ranged") |
| 491 | { |
| 492 | const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY); |
| 493 | const maxRange = profile.rangeTiles | 0 || COMBAT_RANGE_TILES; |
| 494 | const equipment = world.ecs.get(entity.handle, Component.equipment); |
| 495 | const hasArrows = isCreature |
| 496 | || (arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0); |
| 497 | const inRange = dist >= 1 && dist <= maxRange |
| 498 | && hasCombatLineOfSight( |
| 499 | world, |
| 500 | entity.position.tileX, |
| 501 | entity.position.tileY, |
| 502 | targetPos.tileX, |
| 503 | targetPos.tileY |
| 504 | ); |
| 505 | if (!inRange || !hasArrows) |
| 506 | { |
| 507 | if (inRange && !hasArrows && now >= (combat.nextSwingAt || 0) |
| 508 | && world.ecs.get(entity.handle, Component.character)) |
| 509 | { |
| 510 | combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200); |
| 511 | events.push({ |
| 512 | type: "combat-no-arrows", |
| 513 | attackerId: entity.entityId, |
| 514 | sessionId: world.ecs.get(entity.handle, Component.networkIdentity)?.sessionId ?? null |
| 515 | }); |
| 516 | } |
| 517 | queueRangedApproach(world, entity.entityId, entity.handle, entity.position, targetPos, maxRange); |
| 518 | continue; |
| 519 | } |
| 520 | clearCombatApproachPath(world.ecs, entity.handle); |
| 521 | if (now < (combat.nextSwingAt || 0)) |
| 522 | { continue; } |
| 523 | combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200); |
| 524 | events.push(...resolveRangedShot(world, entity.entityId, targetId, profile, now, targetPos)); |
| 525 | continue; |
| 526 | } |
| 527 | |
| 528 | if (profile.mode !== "melee" && !isStaff) |
| 529 | { continue; } |
| 530 | |
| 531 | const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY); |
| 532 | const canSwing = !isStaff |
| 533 | && dist === 1 |
| 534 | && world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY); |
| 535 | const attackSpells = isCreature ? eligibleMobAttackSpells(world.ecs, entity.handle) : []; |
| 536 | const shouldCast = isCreature && attackSpells.length > 0 && (isStaff || !canSwing); |
| 537 | |
| 538 | if (shouldCast) |
| 539 | { |
| 540 | const inSpellRange = dist >= 1 && dist <= COMBAT_RANGE_TILES |
| 541 | && hasCombatLineOfSight( |
| 542 | world, |
| 543 | entity.position.tileX, |
| 544 | entity.position.tileY, |
| 545 | targetPos.tileX, |
| 546 | targetPos.tileY |
| 547 | ); |
| 548 | if (!inSpellRange) |
| 549 | { |
| 550 | queueStandInRangeApproach( |
| 551 | world, |
| 552 | entity.entityId, |
| 553 | entity.handle, |
| 554 | entity.position, |
| 555 | targetPos.tileX, |
| 556 | targetPos.tileY, |
| 557 | COMBAT_RANGE_TILES, |
| 558 | 1 |
| 559 | ); |
| 560 | continue; |
| 561 | } |
| 562 | clearCombatApproachPath(world.ecs, entity.handle); |
| 563 | if (now < (combat.nextSwingAt || 0)) |
| 564 | { continue; } |
| 565 | const picked = pickMobAttackSpell(attackSpells); |
| 566 | if (!picked) |
| 567 | { |
| 568 | combat.nextSwingAt = now + SPELL_COOLDOWN_MS; |
| 569 | continue; |
| 570 | } |
| 571 | combat.nextSwingAt = now + SPELL_COOLDOWN_MS; |
| 572 | events.push(...castMobAttackSpell(world, entity.entityId, targetId, picked.spellId, now)); |
| 573 | continue; |
| 574 | } |
| 575 | |
| 576 | if (!canSwing) |
| 577 | { |
| 578 | if (isStaff) |
| 579 | { |
| 580 | queueStandInRangeApproach( |
| 581 | world, |
| 582 | entity.entityId, |
| 583 | entity.handle, |
| 584 | entity.position, |
| 585 | targetPos.tileX, |
| 586 | targetPos.tileY, |
| 587 | COMBAT_RANGE_TILES, |
| 588 | 1 |
| 589 | ); |
| 590 | } |
| 591 | else |
| 592 | { queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos); } |
| 593 | continue; |
| 594 | } |
| 595 | clearCombatApproachPath(world.ecs, entity.handle); |
| 596 | const attackerHealth = world.ecs.get(entity.handle, Component.health); |
| 597 | if (attackerHealth && attackerHealth.current <= 0) |
| 598 | { continue; } |
| 599 | if ((combat.nextSwingAt || 0) > now) |
| 600 | { continue; } |
| 601 | |
| 602 | combat.nextSwingAt = now + (profile.cooldownMs || 800); |
| 603 | events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now)); |
| 604 | } |
| 605 | return events; |
| 606 | } |
| 607 | |
| 608 | function eligibleMobAttackSpells (ecs, handle) |
| 609 | { |
| 610 | const spells = ecs.get(handle, Component.spells); |
| 611 | if (!spells?.known?.length) |
| 612 | { return []; } |
| 613 | const level = creatureLevel(ecs, handle); |
| 614 | const chances = spells.castChances ?? {}; |
| 615 | const out = []; |
| 616 | for (const spellId of spells.known) |
| 617 | { |
| 618 | const def = spellDefinition(spellId); |
| 619 | if (!def || def.target !== "entity") |
| 620 | { continue; } |
| 621 | const minLevel = Math.max(1, def.minMagicLevel | 0 || 1); |
| 622 | if (level < minLevel) |
| 623 | { continue; } |
| 624 | const chance = Math.max(0, Math.min(100, Number(chances[spellId]) || 0)) | 0; |
| 625 | if (chance <= 0) |
| 626 | { continue; } |
| 627 | out.push({ spellId, chance }); |
| 628 | } |
| 629 | return out; |
| 630 | } |
| 631 | |
| 632 | function pickMobAttackSpell (spells) |
| 633 | { |
| 634 | if (!spells.length) |
| 635 | { return null; } |
| 636 | const pick = spells[Math.floor(Math.random() * spells.length)]; |
| 637 | if ((Math.random() * 100) >= pick.chance) |
| 638 | { return null; } |
| 639 | return pick; |
| 640 | } |
| 641 | |
| 642 | function clearCombatApproachPath (ecs, handle) |
| 643 | { |
| 644 | const path = ecs.get(handle, Component.path); |
| 645 | if (path?.tiles?.length) |
| 646 | { path.tiles = []; } |
| 647 | } |
| 648 | |
| 649 | function combatTileKey (tileX, tileY) |
| 650 | { |
| 651 | return `${tileX},${tileY}`; |
| 652 | } |
| 653 | |
| 654 | /** Tiles claimed by other combatants fighting the same target (position, next step, path goal). */ |
| 655 | function collectCombatAllyReservations (world, entityId, targetEntityId) |
| 656 | { |
| 657 | const reserved = new Set(); |
| 658 | if (targetEntityId == null) |
| 659 | { return reserved; } |
| 660 | for (const entity of world.ecs.query(Component.combat, Component.position)) |
| 661 | { |
| 662 | if (entity.entityId === entityId) |
| 663 | { continue; } |
| 664 | if (entity.combat.targetEntityId !== targetEntityId) |
| 665 | { continue; } |
| 666 | reserved.add(combatTileKey(entity.position.tileX, entity.position.tileY)); |
| 667 | const allyPath = world.ecs.get(entity.handle, Component.path); |
| 668 | if (!allyPath?.tiles?.length) |
| 669 | { continue; } |
| 670 | const next = allyPath.tiles[0]; |
| 671 | if (next) |
| 672 | { reserved.add(combatTileKey(next.x, next.y)); } |
| 673 | const dest = allyPath.tiles[allyPath.tiles.length - 1]; |
| 674 | if (dest) |
| 675 | { reserved.add(combatTileKey(dest.x, dest.y)); } |
| 676 | } |
| 677 | return reserved; |
| 678 | } |
| 679 | |
| 680 | function combatGoalPreference (entityId, tileX, tileY) |
| 681 | { |
| 682 | return ((tileX * 73856093) ^ (tileY * 19349663) ^ (entityId * 83492791)) >>> 0; |
| 683 | } |
| 684 | |
| 685 | export function queueMeleeApproach (world, entityId, handle, position, targetPos) |
| 686 | { |
| 687 | if (world.frozen?.has?.(entityId)) |
| 688 | { return; } |
| 689 | let path = world.ecs.get(handle, Component.path); |
| 690 | if (!path) |
| 691 | { path = world.ecs.add(handle, Component.path, { tiles: [] }); } |
| 692 | |
| 693 | const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) |
| 694 | ?? true; |
| 695 | if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) === 1 && aloneHere) |
| 696 | { |
| 697 | path.tiles = []; |
| 698 | return; |
| 699 | } |
| 700 | |
| 701 | const combat = world.ecs.get(handle, Component.combat); |
| 702 | const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null); |
| 703 | const goal = bestAdjacentGoal(world, entityId, position, targetPos, reserved); |
| 704 | if (!goal) |
| 705 | { |
| 706 | path.tiles = []; |
| 707 | return; |
| 708 | } |
| 709 | |
| 710 | if (goal.x === position.tileX && goal.y === position.tileY) |
| 711 | { |
| 712 | path.tiles = []; |
| 713 | return; |
| 714 | } |
| 715 | |
| 716 | if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved)) |
| 717 | { return; } |
| 718 | |
| 719 | const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); |
| 720 | const preferVertical = !!world.ecs.get(handle, Component.character); |
| 721 | const tiles = findPath( |
| 722 | position.tileX, |
| 723 | position.tileY, |
| 724 | goal.x, |
| 725 | goal.y, |
| 726 | (x, y) => |
| 727 | { |
| 728 | if (x === goal.x && y === goal.y) |
| 729 | { |
| 730 | return world.isClearStanding?.(entityId, x, y) |
| 731 | ?? world.walkableFor(entityId, x, y); |
| 732 | } |
| 733 | return world.walkableFor(entityId, x, y); |
| 734 | }, |
| 735 | bounds.minX, |
| 736 | bounds.minY, |
| 737 | bounds.maxX, |
| 738 | bounds.maxY, |
| 739 | { preferVertical } |
| 740 | ); |
| 741 | if (!tiles.length) |
| 742 | { |
| 743 | path.tiles = []; |
| 744 | return; |
| 745 | } |
| 746 | path.tiles = tiles; |
| 747 | const movement = world.ecs.get(handle, Component.movement); |
| 748 | if (movement) |
| 749 | { movement.walkCarry = 0; } |
| 750 | } |
| 751 | |
| 752 | /** |
| 753 | * Path toward the nearest reachable tile from which `targetTile` is in Chebyshev range with LOS. |
| 754 | * Goal is chosen by BFS flood from the actor (shortest walk), not min Chebyshev (which biases top-left). |
| 755 | * @param {number} minStandDist Minimum stand-off from target (0 = may stand on target tile). |
| 756 | */ |
| 757 | export function queueStandInRangeApproach ( |
| 758 | world, |
| 759 | entityId, |
| 760 | handle, |
| 761 | position, |
| 762 | targetTileX, |
| 763 | targetTileY, |
| 764 | maxRange, |
| 765 | minStandDist = 1 |
| 766 | ) |
| 767 | { |
| 768 | if (world.frozen?.has?.(entityId)) |
| 769 | { return; } |
| 770 | let path = world.ecs.get(handle, Component.path); |
| 771 | if (!path) |
| 772 | { path = world.ecs.add(handle, Component.path, { tiles: [] }); } |
| 773 | |
| 774 | const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY); |
| 775 | const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true; |
| 776 | if ( |
| 777 | distToTarget <= maxRange |
| 778 | && distToTarget >= minStandDist |
| 779 | && aloneHere |
| 780 | && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY) |
| 781 | ) |
| 782 | { |
| 783 | path.tiles = []; |
| 784 | return; |
| 785 | } |
| 786 | |
| 787 | const combat = world.ecs.get(handle, Component.combat); |
| 788 | const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null); |
| 789 | const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); |
| 790 | const isWalkable = (x, y) => world.walkableFor(entityId, x, y); |
| 791 | const isGoal = (x, y) => |
| 792 | { |
| 793 | const standOff = chebyshev(x, y, targetTileX, targetTileY); |
| 794 | if (standOff < minStandDist || standOff > maxRange) |
| 795 | { return false; } |
| 796 | if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y))) |
| 797 | { return false; } |
| 798 | const key = combatTileKey(x, y); |
| 799 | if (reserved.has(key) && !(x === position.tileX && y === position.tileY)) |
| 800 | { return false; } |
| 801 | return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY); |
| 802 | }; |
| 803 | |
| 804 | const tiles = findPathToNearestGoal( |
| 805 | position.tileX, |
| 806 | position.tileY, |
| 807 | isGoal, |
| 808 | isWalkable, |
| 809 | bounds.minX, |
| 810 | bounds.minY, |
| 811 | bounds.maxX, |
| 812 | bounds.maxY |
| 813 | ); |
| 814 | if (!tiles.length) |
| 815 | { |
| 816 | path.tiles = []; |
| 817 | return; |
| 818 | } |
| 819 | const bestGoal = tiles[tiles.length - 1]; |
| 820 | if (path.tiles?.length && !standInRangePathStale( |
| 821 | world, |
| 822 | entityId, |
| 823 | path, |
| 824 | bestGoal, |
| 825 | targetTileX, |
| 826 | targetTileY, |
| 827 | maxRange, |
| 828 | minStandDist, |
| 829 | reserved, |
| 830 | position |
| 831 | )) |
| 832 | { return; } |
| 833 | path.tiles = tiles; |
| 834 | const movement = world.ecs.get(handle, Component.movement); |
| 835 | if (movement) |
| 836 | { movement.walkCarry = 0; } |
| 837 | } |
| 838 | |
| 839 | function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange) |
| 840 | { |
| 841 | queueStandInRangeApproach( |
| 842 | world, |
| 843 | entityId, |
| 844 | handle, |
| 845 | position, |
| 846 | targetPos.tileX, |
| 847 | targetPos.tileY, |
| 848 | maxRange, |
| 849 | 1 |
| 850 | ); |
| 851 | } |
| 852 | |
| 853 | export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos) |
| 854 | { |
| 855 | const events = []; |
| 856 | const attackerHandle = world.ecs.handleOf(attackerId); |
| 857 | if (attackerHandle == null) |
| 858 | { return events; } |
| 859 | const from = world.ecs.get(attackerHandle, Component.position); |
| 860 | if (!from || !targetPos) |
| 861 | { return events; } |
| 862 | const isCreature = !!world.ecs.get(attackerHandle, Component.creature) |
| 863 | && !world.ecs.get(attackerHandle, Component.character); |
| 864 | if (!isCreature && !consumeArrow(world.ecs, attackerHandle)) |
| 865 | { return events; } |
| 866 | |
| 867 | const snapshot = { tileX: targetPos.tileX, tileY: targetPos.tileY }; |
| 868 | const target = resolveCombatTarget(world, targetId); |
| 869 | if (!target) |
| 870 | { return events; } |
| 871 | |
| 872 | if (!target.local) |
| 873 | { |
| 874 | events.push({ |
| 875 | type: "remote-ranged-resolve", |
| 876 | attackerId, |
| 877 | targetId, |
| 878 | profile, |
| 879 | attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings), |
| 880 | attackerIsPlayer: !!world.ecs.get(attackerHandle, Component.character), |
| 881 | now, |
| 882 | tileX: snapshot.tileX, |
| 883 | tileY: snapshot.tileY, |
| 884 | fromTileX: from.tileX, |
| 885 | fromTileY: from.tileY, |
| 886 | ...(publicDualTint(projectileDualTintFromAttacker(world.ecs, attackerHandle)) ?? {}) |
| 887 | }); |
| 888 | return events; |
| 889 | } |
| 890 | |
| 891 | const hitEvents = applyLocalMeleeHit( |
| 892 | world, |
| 893 | attackerId, |
| 894 | targetId, |
| 895 | attackerHandle, |
| 896 | target.handle, |
| 897 | profile, |
| 898 | now, |
| 899 | snapshot |
| 900 | ); |
| 901 | const outcome = hitEvents.find((e) => |
| 902 | e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block"); |
| 903 | let endX = snapshot.tileX; |
| 904 | let endY = snapshot.tileY; |
| 905 | if (outcome?.type === "combat-miss") |
| 906 | { |
| 907 | const miss = missProjectileTile(snapshot.tileX, snapshot.tileY); |
| 908 | endX = miss.tileX; |
| 909 | endY = miss.tileY; |
| 910 | } |
| 911 | else |
| 912 | { |
| 913 | const currentPos = world.ecs.get(target.handle, Component.position); |
| 914 | if (currentPos) |
| 915 | { |
| 916 | endX = currentPos.tileX; |
| 917 | endY = currentPos.tileY; |
| 918 | } |
| 919 | } |
| 920 | events.push({ |
| 921 | type: "combat-projectile", |
| 922 | attackerId, |
| 923 | targetId, |
| 924 | fromTileX: from.tileX, |
| 925 | fromTileY: from.tileY, |
| 926 | tileX: endX, |
| 927 | tileY: endY, |
| 928 | durationMs: RANGED_PROJECTILE_MS, |
| 929 | trackTarget: outcome?.type !== "combat-miss", |
| 930 | ...(publicDualTint(projectileDualTintFromAttacker(world.ecs, attackerHandle)) ?? {}) |
| 931 | }); |
| 932 | return events.concat(hitEvents); |
| 933 | } |
| 934 | |
| 935 | function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist, reserved, position) |
| 936 | { |
| 937 | const dest = path.tiles[path.tiles.length - 1]; |
| 938 | if (dest.x !== goal.x || dest.y !== goal.y) |
| 939 | { return true; } |
| 940 | const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY); |
| 941 | if (standOff < minStandDist || standOff > maxRange) |
| 942 | { return true; } |
| 943 | if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY)) |
| 944 | { return true; } |
| 945 | if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true)) |
| 946 | { return true; } |
| 947 | const destKey = combatTileKey(dest.x, dest.y); |
| 948 | if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY)) |
| 949 | { return true; } |
| 950 | const next = path.tiles[0]; |
| 951 | if (!next) |
| 952 | { return true; } |
| 953 | if (!world.walkableFor(entityId, next.x, next.y)) |
| 954 | { return true; } |
| 955 | return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true); |
| 956 | } |
| 957 | |
| 958 | function meleePathStale (world, entityId, position, targetPos, path, goal, reserved) |
| 959 | { |
| 960 | const dest = path.tiles[path.tiles.length - 1]; |
| 961 | if (dest.x !== goal.x || dest.y !== goal.y) |
| 962 | { return true; } |
| 963 | if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1) |
| 964 | { return true; } |
| 965 | if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true)) |
| 966 | { return true; } |
| 967 | const destKey = combatTileKey(dest.x, dest.y); |
| 968 | if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY)) |
| 969 | { return true; } |
| 970 | const next = path.tiles[0]; |
| 971 | if (!next) |
| 972 | { return true; } |
| 973 | if (!world.walkableFor(entityId, next.x, next.y)) |
| 974 | { return true; } |
| 975 | return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true); |
| 976 | } |
| 977 | |
| 978 | function bestAdjacentGoal (world, entityId, position, targetPos, reserved = null) |
| 979 | { |
| 980 | const dirs = [ |
| 981 | { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 }, |
| 982 | { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 } |
| 983 | ]; |
| 984 | let best = null; |
| 985 | let bestDist = Infinity; |
| 986 | let bestPref = Infinity; |
| 987 | for (const dir of dirs) |
| 988 | { |
| 989 | const x = targetPos.tileX + dir.x; |
| 990 | const y = targetPos.tileY + dir.y; |
| 991 | const isHere = x === position.tileX && y === position.tileY; |
| 992 | const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true; |
| 993 | const key = combatTileKey(x, y); |
| 994 | if (reserved?.has(key) && !(isHere && aloneHere)) |
| 995 | { continue; } |
| 996 | const clear = world.isClearStanding?.(entityId, x, y) |
| 997 | ?? world.walkableFor(entityId, x, y); |
| 998 | if (!clear && !isHere) |
| 999 | { continue; } |
| 1000 | if (isHere && !aloneHere) |
| 1001 | { continue; } |
| 1002 | const dist = chebyshev(position.tileX, position.tileY, x, y); |
| 1003 | const pref = combatGoalPreference(entityId, x, y); |
| 1004 | if (dist < bestDist || (dist === bestDist && pref < bestPref)) |
| 1005 | { |
| 1006 | bestDist = dist; |
| 1007 | bestPref = pref; |
| 1008 | best = { x, y }; |
| 1009 | } |
| 1010 | } |
| 1011 | return best; |
| 1012 | } |
| 1013 | |
| 1014 | export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now()) |
| 1015 | { |
| 1016 | const events = []; |
| 1017 | const attackerHandle = world.ecs.handleOf(attackerId); |
| 1018 | if (attackerHandle == null) |
| 1019 | { return events; } |
| 1020 | const target = resolveCombatTarget(world, targetId); |
| 1021 | if (!target) |
| 1022 | { return events; } |
| 1023 | const from = world.ecs.get(attackerHandle, Component.position); |
| 1024 | const to = target.pos; |
| 1025 | if (!from || !to) |
| 1026 | { return events; } |
| 1027 | if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1) |
| 1028 | { return events; } |
| 1029 | if (world.isClearStanding && !world.isClearStanding(attackerId, from.tileX, from.tileY)) |
| 1030 | { return events; } |
| 1031 | |
| 1032 | events.push({ |
| 1033 | type: "combat-swing", |
| 1034 | attackerId, |
| 1035 | targetId, |
| 1036 | tileX: to.tileX, |
| 1037 | tileY: to.tileY, |
| 1038 | fromTileX: from.tileX, |
| 1039 | fromTileY: from.tileY |
| 1040 | }); |
| 1041 | |
| 1042 | if (!target.local) |
| 1043 | { |
| 1044 | const attackerCharacter = world.ecs.get(attackerHandle, Component.character); |
| 1045 | events.push({ |
| 1046 | type: "remote-melee-resolve", |
| 1047 | attackerId, |
| 1048 | targetId, |
| 1049 | profile, |
| 1050 | attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings), |
| 1051 | attackerIsPlayer: !!attackerCharacter, |
| 1052 | now, |
| 1053 | tileX: to.tileX, |
| 1054 | tileY: to.tileY |
| 1055 | }); |
| 1056 | return events; |
| 1057 | } |
| 1058 | |
| 1059 | return events.concat(applyLocalMeleeHit( |
| 1060 | world, |
| 1061 | attackerId, |
| 1062 | targetId, |
| 1063 | attackerHandle, |
| 1064 | target.handle, |
| 1065 | profile, |
| 1066 | now, |
| 1067 | to |
| 1068 | )); |
| 1069 | } |
| 1070 | |
| 1071 | /** Authoritative ranged hit when the defender lives on this worker. */ |
| 1072 | export function applyRemoteRangedShot (world, payload) |
| 1073 | { |
| 1074 | const targetHandle = world.ecs.handleOf(payload.targetId); |
| 1075 | if (targetHandle == null) |
| 1076 | { return { events: [], forwards: [] }; } |
| 1077 | const snapshot = { |
| 1078 | tileX: payload.tileX, |
| 1079 | tileY: payload.tileY |
| 1080 | }; |
| 1081 | |
| 1082 | const hitEvents = applyLocalMeleeHit( |
| 1083 | world, |
| 1084 | payload.attackerId, |
| 1085 | payload.targetId, |
| 1086 | null, |
| 1087 | targetHandle, |
| 1088 | payload.profile, |
| 1089 | payload.now ?? Date.now(), |
| 1090 | snapshot, |
| 1091 | payload.attackerLevels, |
| 1092 | payload.attackerIsPlayer |
| 1093 | ); |
| 1094 | |
| 1095 | const outcome = hitEvents.find((e) => |
| 1096 | e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block"); |
| 1097 | let endX = snapshot.tileX; |
| 1098 | let endY = snapshot.tileY; |
| 1099 | if (outcome?.type === "combat-miss") |
| 1100 | { |
| 1101 | const miss = missProjectileTile(snapshot.tileX, snapshot.tileY); |
| 1102 | endX = miss.tileX; |
| 1103 | endY = miss.tileY; |
| 1104 | } |
| 1105 | else |
| 1106 | { |
| 1107 | const currentPos = world.ecs.get(targetHandle, Component.position); |
| 1108 | if (currentPos) |
| 1109 | { |
| 1110 | endX = currentPos.tileX; |
| 1111 | endY = currentPos.tileY; |
| 1112 | } |
| 1113 | } |
| 1114 | |
| 1115 | const events = [{ |
| 1116 | type: "combat-projectile", |
| 1117 | attackerId: payload.attackerId, |
| 1118 | targetId: payload.targetId, |
| 1119 | fromTileX: payload.fromTileX, |
| 1120 | fromTileY: payload.fromTileY, |
| 1121 | tileX: endX, |
| 1122 | tileY: endY, |
| 1123 | durationMs: RANGED_PROJECTILE_MS, |
| 1124 | trackTarget: outcome?.type !== "combat-miss", |
| 1125 | shaftTint: payload.shaftTint ?? null, |
| 1126 | tipTint: payload.tipTint ?? null |
| 1127 | }, ...hitEvents]; |
| 1128 | |
| 1129 | const forwards = []; |
| 1130 | const hitEvent = hitEvents.find((event) => event.type === "combat-hit"); |
| 1131 | if (hitEvent && payload.attackerIsPlayer) |
| 1132 | { |
| 1133 | forwards.push({ |
| 1134 | type: "forward-combat-xp", |
| 1135 | entityId: payload.attackerId, |
| 1136 | profile: payload.profile, |
| 1137 | damage: hitEvent.damage |
| 1138 | }); |
| 1139 | } |
| 1140 | return { events, forwards }; |
| 1141 | } |
| 1142 | |
| 1143 | /** Authoritative hit resolution when the defender lives on this worker. */ |
| 1144 | export function applyRemoteMeleeSwing (world, payload) |
| 1145 | { |
| 1146 | const targetHandle = world.ecs.handleOf(payload.targetId); |
| 1147 | if (targetHandle == null) |
| 1148 | { return { events: [], forwards: [] }; } |
| 1149 | const to = world.ecs.get(targetHandle, Component.position); |
| 1150 | if (!to) |
| 1151 | { return { events: [], forwards: [] }; } |
| 1152 | |
| 1153 | const events = applyLocalMeleeHit( |
| 1154 | world, |
| 1155 | payload.attackerId, |
| 1156 | payload.targetId, |
| 1157 | null, |
| 1158 | targetHandle, |
| 1159 | payload.profile, |
| 1160 | payload.now ?? Date.now(), |
| 1161 | to, |
| 1162 | payload.attackerLevels, |
| 1163 | payload.attackerIsPlayer |
| 1164 | ); |
| 1165 | |
| 1166 | const forwards = []; |
| 1167 | const hitEvent = events.find((event) => event.type === "combat-hit"); |
| 1168 | if (hitEvent && payload.attackerIsPlayer) |
| 1169 | { |
| 1170 | forwards.push({ |
| 1171 | type: "forward-combat-xp", |
| 1172 | entityId: payload.attackerId, |
| 1173 | profile: payload.profile, |
| 1174 | damage: hitEvent.damage |
| 1175 | }); |
| 1176 | } |
| 1177 | return { events, forwards }; |
| 1178 | } |
| 1179 | |
| 1180 | function applyLocalMeleeHit ( |
| 1181 | world, |
| 1182 | attackerId, |
| 1183 | targetId, |
| 1184 | attackerHandle, |
| 1185 | targetHandle, |
| 1186 | profile, |
| 1187 | now, |
| 1188 | to, |
| 1189 | attackerLevelsOverride = null, |
| 1190 | attackerIsPlayerOverride = null |
| 1191 | ) |
| 1192 | { |
| 1193 | const events = []; |
| 1194 | if (targetHandle == null) |
| 1195 | { return events; } |
| 1196 | |
| 1197 | const attackerIsPlayer = attackerIsPlayerOverride != null |
| 1198 | ? !!attackerIsPlayerOverride |
| 1199 | : (attackerHandle != null ? !!world.ecs.get(attackerHandle, Component.character) : null); |
| 1200 | |
| 1201 | // Retaliate on the first resolved swing (hit or miss), not on Attack-click engage. |
| 1202 | if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId)) |
| 1203 | { engageTarget(world.ecs, targetId, attackerId, now); } |
| 1204 | if (attackerIsPlayer === false) |
| 1205 | { |
| 1206 | const targetCharacter = world.ecs.get(targetHandle, Component.character); |
| 1207 | if (targetCharacter) |
| 1208 | { |
| 1209 | engageTarget(world.ecs, targetId, attackerId, now); |
| 1210 | const follow = world.ecs.get(targetHandle, Component.follow); |
| 1211 | if (follow) |
| 1212 | { |
| 1213 | follow.targetEntityId = null; |
| 1214 | follow.trail = []; |
| 1215 | } |
| 1216 | if (world.ecs.has(targetHandle, Component.gather)) |
| 1217 | { world.ecs.remove(targetHandle, Component.gather); } |
| 1218 | } |
| 1219 | } |
| 1220 | |
| 1221 | const defenderSkills = world.ecs.get(targetHandle, Component.skills); |
| 1222 | const defenderEquipment = world.ecs.get(targetHandle, Component.equipment); |
| 1223 | const attackerLevels = attackerLevelsOverride |
| 1224 | ?? (attackerHandle != null |
| 1225 | ? attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings) |
| 1226 | : null); |
| 1227 | if (!attackerLevels) |
| 1228 | { return events; } |
| 1229 | |
| 1230 | const agilityLevel = defenderSkillLevel( |
| 1231 | defenderSkills, |
| 1232 | SkillId.agility, |
| 1233 | defenderEquipment, |
| 1234 | world.settings |
| 1235 | ); |
| 1236 | const defenceLevel = defenderSkillLevel( |
| 1237 | defenderSkills, |
| 1238 | SkillId.defence, |
| 1239 | defenderEquipment, |
| 1240 | world.settings |
| 1241 | ); |
| 1242 | |
| 1243 | const resolved = resolvePhysicalAttack({ |
| 1244 | hitSkillLevel: effectiveHitSkillInDarkness( |
| 1245 | attackerLevels.hitLevel, |
| 1246 | tileLightAt(world, to.tileX, to.tileY) |
| 1247 | ), |
| 1248 | agilitySkillLevel: agilityLevel, |
| 1249 | damageSkillLevel: attackerLevels.damageLevel, |
| 1250 | defenceSkillLevel: defenceLevel |
| 1251 | }); |
| 1252 | |
| 1253 | if (resolved.outcome === "miss") |
| 1254 | { |
| 1255 | events.push({ |
| 1256 | type: "combat-miss", |
| 1257 | attackerId, |
| 1258 | targetId, |
| 1259 | tileX: to.tileX, |
| 1260 | tileY: to.tileY |
| 1261 | }); |
| 1262 | const dodgeXp = awardCombatAvoidanceXp( |
| 1263 | world.ecs, |
| 1264 | targetHandle, |
| 1265 | SkillId.agility, |
| 1266 | resolved.damageRoll |
| 1267 | ); |
| 1268 | if (dodgeXp) |
| 1269 | { |
| 1270 | events.push({ |
| 1271 | type: "skills-updated", |
| 1272 | entityId: targetId, |
| 1273 | characterId: dodgeXp.characterId, |
| 1274 | skills: dodgeXp.view, |
| 1275 | stored: dodgeXp.stored, |
| 1276 | levelUps: dodgeXp.levelUps ?? [] |
| 1277 | }); |
| 1278 | } |
| 1279 | return events; |
| 1280 | } |
| 1281 | |
| 1282 | if (resolved.outcome === "block") |
| 1283 | { |
| 1284 | events.push({ |
| 1285 | type: "combat-block", |
| 1286 | attackerId, |
| 1287 | targetId, |
| 1288 | tileX: to.tileX, |
| 1289 | tileY: to.tileY |
| 1290 | }); |
| 1291 | const blockXp = awardCombatAvoidanceXp( |
| 1292 | world.ecs, |
| 1293 | targetHandle, |
| 1294 | SkillId.defence, |
| 1295 | resolved.damageRoll |
| 1296 | ); |
| 1297 | if (blockXp) |
| 1298 | { |
| 1299 | events.push({ |
| 1300 | type: "skills-updated", |
| 1301 | entityId: targetId, |
| 1302 | characterId: blockXp.characterId, |
| 1303 | skills: blockXp.view, |
| 1304 | stored: blockXp.stored, |
| 1305 | levelUps: blockXp.levelUps ?? [] |
| 1306 | }); |
| 1307 | } |
| 1308 | return events; |
| 1309 | } |
| 1310 | |
| 1311 | const damage = resolved.damage; |
| 1312 | const targetCharacter = world.ecs.get(targetHandle, Component.character); |
| 1313 | if (targetCharacter) |
| 1314 | { syncPlayerHealth(world.ecs, targetHandle); } |
| 1315 | const health = world.ecs.get(targetHandle, Component.health); |
| 1316 | if (health) |
| 1317 | { |
| 1318 | health.current = Math.max(0, (health.current | 0) - damage); |
| 1319 | } |
| 1320 | events.push({ |
| 1321 | type: "combat-hit", |
| 1322 | attackerId, |
| 1323 | targetId, |
| 1324 | damage, |
| 1325 | tileX: to.tileX, |
| 1326 | tileY: to.tileY, |
| 1327 | health: health?.current ?? 0, |
| 1328 | maxHealth: health?.max ?? 0 |
| 1329 | }); |
| 1330 | |
| 1331 | const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage); |
| 1332 | if (healthXp) |
| 1333 | { |
| 1334 | events.push({ |
| 1335 | type: "skills-updated", |
| 1336 | entityId: targetId, |
| 1337 | characterId: healthXp.characterId, |
| 1338 | skills: healthXp.view, |
| 1339 | stored: healthXp.stored, |
| 1340 | levelUps: healthXp.levelUps ?? [] |
| 1341 | }); |
| 1342 | if (health) |
| 1343 | { |
| 1344 | const hitEvent = events[events.length - 2]; |
| 1345 | if (hitEvent?.type === "combat-hit") |
| 1346 | { |
| 1347 | hitEvent.health = health.current; |
| 1348 | hitEvent.maxHealth = health.max; |
| 1349 | } |
| 1350 | } |
| 1351 | } |
| 1352 | |
| 1353 | if (attackerHandle != null) |
| 1354 | { |
| 1355 | const attackerCharacter = world.ecs.get(attackerHandle, Component.character); |
| 1356 | if (attackerCharacter) |
| 1357 | { |
| 1358 | const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile, damage); |
| 1359 | if (xpAward) |
| 1360 | { |
| 1361 | events.push({ |
| 1362 | type: "skills-updated", |
| 1363 | entityId: attackerId, |
| 1364 | characterId: attackerCharacter.characterId, |
| 1365 | skills: xpAward.view, |
| 1366 | stored: xpAward.stored, |
| 1367 | levelUps: xpAward.levelUps ?? [] |
| 1368 | }); |
| 1369 | } |
| 1370 | } |
| 1371 | } |
| 1372 | |
| 1373 | if (health && health.current <= 0) |
| 1374 | { |
| 1375 | clearEngage(world.ecs, attackerId); |
| 1376 | clearEngage(world.ecs, targetId); |
| 1377 | for (const entity of world.ecs.query(Component.combat)) |
| 1378 | { |
| 1379 | if (entity.combat.targetEntityId === targetId) |
| 1380 | { entity.combat.targetEntityId = null; } |
| 1381 | } |
| 1382 | if (targetCharacter && !world.ecs.has(targetHandle, Component.dead)) |
| 1383 | { |
| 1384 | const path = world.ecs.get(targetHandle, Component.path); |
| 1385 | if (path) |
| 1386 | { path.tiles = []; } |
| 1387 | const follow = world.ecs.get(targetHandle, Component.follow); |
| 1388 | if (follow) |
| 1389 | { |
| 1390 | follow.targetEntityId = null; |
| 1391 | follow.trail = []; |
| 1392 | } |
| 1393 | world.ecs.add(targetHandle, Component.dead, {}); |
| 1394 | const identity = world.ecs.get(targetHandle, Component.networkIdentity); |
| 1395 | events.push({ |
| 1396 | type: "player-died", |
| 1397 | entityId: targetId, |
| 1398 | attackerId, |
| 1399 | characterId: targetCharacter.characterId, |
| 1400 | sessionId: identity?.sessionId ?? null, |
| 1401 | tileX: to.tileX, |
| 1402 | tileY: to.tileY, |
| 1403 | health: 0, |
| 1404 | maxHealth: health.max |
| 1405 | }); |
| 1406 | } |
| 1407 | const creature = world.ecs.get(targetHandle, Component.creature); |
| 1408 | if (creature && !world.ecs.get(targetHandle, Component.character)) |
| 1409 | { |
| 1410 | events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); |
| 1411 | } |
| 1412 | } |
| 1413 | return events; |
| 1414 | } |
| 1415 | |
| 1416 | /** |
| 1417 | * Drops, despawn, and `mob-killed` for bounty / town-guard reaction. |
| 1418 | * Shared by melee and spell kill paths. |
| 1419 | */ |
| 1420 | export function finalizeMobKill (world, attackerId, targetId, targetHandle, tileX, tileY, now) |
| 1421 | { |
| 1422 | const events = []; |
| 1423 | const handle = targetHandle ?? world.ecs.handleOf(targetId); |
| 1424 | if (handle == null) |
| 1425 | { return events; } |
| 1426 | const creature = world.ecs.get(handle, Component.creature); |
| 1427 | const origin = world.ecs.get(handle, Component.spawnOrigin); |
| 1428 | const appearance = world.ecs.get(handle, Component.appearance); |
| 1429 | events.push(...spawnMobDrops(world, handle, tileX, tileY, now, attackerId)); |
| 1430 | events.push({ |
| 1431 | type: "mob-killed", |
| 1432 | entityId: targetId, |
| 1433 | attackerId, |
| 1434 | mobTypeId: creature?.mobTypeId ?? null, |
| 1435 | level: creature?.level ?? origin?.level ?? 1, |
| 1436 | bounty: Math.max(0, origin?.bounty | 0 || 0), |
| 1437 | spawnerId: origin?.spawnerId ?? null, |
| 1438 | originTileX: origin?.originTileX ?? tileX, |
| 1439 | originTileY: origin?.originTileY ?? tileY, |
| 1440 | wanderRangeTiles: origin?.wanderRangeTiles ?? 0, |
| 1441 | townGuard: !!origin?.townGuard, |
| 1442 | displayName: appearance?.firstName ?? null, |
| 1443 | tileX, |
| 1444 | tileY |
| 1445 | }); |
| 1446 | const view = world.destroyEntity?.(targetId) ?? null; |
| 1447 | if (view) |
| 1448 | { |
| 1449 | events.push({ |
| 1450 | type: "entity-despawn", |
| 1451 | entityId: targetId, |
| 1452 | tileX: view.tileX, |
| 1453 | tileY: view.tileY |
| 1454 | }); |
| 1455 | } |
| 1456 | return events; |
| 1457 | } |
| 1458 | |
| 1459 | /** Apply HP loss and shared death/loot side-effects (used by spell impacts). */ |
| 1460 | export function applyDamageAndKill (world, attackerId, targetId, damage, now = Date.now()) |
| 1461 | { |
| 1462 | const events = []; |
| 1463 | const targetHandle = world.ecs.handleOf(targetId); |
| 1464 | if (targetHandle == null) |
| 1465 | { return events; } |
| 1466 | const to = world.ecs.get(targetHandle, Component.position); |
| 1467 | if (!to) |
| 1468 | { return events; } |
| 1469 | const health = world.ecs.get(targetHandle, Component.health); |
| 1470 | if (health) |
| 1471 | { health.current = Math.max(0, (health.current | 0) - damage); } |
| 1472 | events.push({ |
| 1473 | type: "combat-hit", |
| 1474 | attackerId, |
| 1475 | targetId, |
| 1476 | damage, |
| 1477 | tileX: to.tileX, |
| 1478 | tileY: to.tileY, |
| 1479 | health: health?.current ?? 0, |
| 1480 | maxHealth: health?.max ?? 0 |
| 1481 | }); |
| 1482 | |
| 1483 | const attackerHandle = world.ecs.handleOf(attackerId); |
| 1484 | if (attackerHandle != null && ensureMobCombat(world.ecs, targetId)) |
| 1485 | { |
| 1486 | const targetCombat = world.ecs.get(targetHandle, Component.combat); |
| 1487 | if (targetCombat && targetCombat.targetEntityId == null) |
| 1488 | { engageTarget(world.ecs, targetId, attackerId, now); } |
| 1489 | } |
| 1490 | if (attackerHandle != null && world.ecs.get(targetHandle, Component.character)) |
| 1491 | { |
| 1492 | const attackerCreature = world.ecs.get(attackerHandle, Component.creature); |
| 1493 | if (attackerCreature) |
| 1494 | { |
| 1495 | engageTarget(world.ecs, targetId, attackerId, now); |
| 1496 | } |
| 1497 | } |
| 1498 | |
| 1499 | const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage); |
| 1500 | if (healthXp) |
| 1501 | { |
| 1502 | events.push({ |
| 1503 | type: "skills-updated", |
| 1504 | entityId: targetId, |
| 1505 | characterId: healthXp.characterId, |
| 1506 | skills: healthXp.view, |
| 1507 | stored: healthXp.stored, |
| 1508 | levelUps: healthXp.levelUps ?? [] |
| 1509 | }); |
| 1510 | } |
| 1511 | |
| 1512 | if (health && health.current <= 0) |
| 1513 | { |
| 1514 | clearEngage(world.ecs, attackerId); |
| 1515 | clearEngage(world.ecs, targetId); |
| 1516 | for (const entity of world.ecs.query(Component.combat)) |
| 1517 | { |
| 1518 | if (entity.combat.targetEntityId === targetId) |
| 1519 | { entity.combat.targetEntityId = null; } |
| 1520 | } |
| 1521 | const targetCharacter = world.ecs.get(targetHandle, Component.character); |
| 1522 | if (targetCharacter && !world.ecs.has(targetHandle, Component.dead)) |
| 1523 | { |
| 1524 | const path = world.ecs.get(targetHandle, Component.path); |
| 1525 | if (path) |
| 1526 | { path.tiles = []; } |
| 1527 | world.ecs.add(targetHandle, Component.dead, {}); |
| 1528 | const identity = world.ecs.get(targetHandle, Component.networkIdentity); |
| 1529 | events.push({ |
| 1530 | type: "player-died", |
| 1531 | entityId: targetId, |
| 1532 | attackerId, |
| 1533 | characterId: targetCharacter.characterId, |
| 1534 | sessionId: identity?.sessionId ?? null, |
| 1535 | tileX: to.tileX, |
| 1536 | tileY: to.tileY, |
| 1537 | health: 0, |
| 1538 | maxHealth: health.max |
| 1539 | }); |
| 1540 | } |
| 1541 | const creature = world.ecs.get(targetHandle, Component.creature); |
| 1542 | if (creature && !targetCharacter) |
| 1543 | { events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); } |
| 1544 | } |
| 1545 | return events; |
| 1546 | } |