| 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, isTownGuardMob } from "../../../shared/definitions/mobs.js"; |
| 5 | import |
| 6 | { |
| 7 | mobCanFightType, |
| 8 | mobCanFight, |
| 9 | mobMeleeAttackProfile, |
| 10 | mobSkillLevels, |
| 11 | mobIsAggressive, |
| 12 | mobAggroRangeTiles, |
| 13 | mobIsBoss |
| 14 | } from "../../../shared/definitions/mobCombat.js"; |
| 15 | import { |
| 16 | combatLevelFromSkills, |
| 17 | mobAggressionLevel, |
| 18 | playerOutlevelsMobAggression |
| 19 | } from "../../../shared/combat/combatLevel.js"; |
| 20 | import { chunkPeaceAggressionImmunity } from "../../../shared/navigation/chunkPresence.js"; |
| 21 | import { skullAttractsTownGuards } from "../../../shared/combat/skull.js"; |
| 22 | import { OVERWORLD_ID } from "../../../shared/world/dimensions.js"; |
| 23 | import { spellDefinition, spellMinMagicLevel } from "../../../shared/definitions/spells.js"; |
| 24 | import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js"; |
| 25 | import { mobDamageAffinities } from "../../../shared/combat/magic.js"; |
| 26 | import { AttackType } from "../../../shared/definitions/attackTypes.js"; |
| 27 | import |
| 28 | { |
| 29 | isMagicStaffEquipped, |
| 30 | firstFavoriteAttackSpellId |
| 31 | } from "../../../shared/combat/maxHit.js"; |
| 32 | import { canCastSpell } from "../../../shared/spells/state.js"; |
| 33 | import |
| 34 | { |
| 35 | effectiveHitSkillInDarkness, |
| 36 | aggroDistanceMultiplier |
| 37 | } from "../../../shared/combat/darkness.js"; |
| 38 | import |
| 39 | { |
| 40 | entityLightAtTile, |
| 41 | tileCombatLight01, |
| 42 | tileIndexLocal |
| 43 | } from "../../../shared/lighting/combatLight.js"; |
| 44 | import { blockLightSourcesNearTile } from "../../../shared/lighting/blockLights.js"; |
| 45 | import { dynamicDarknessAtTile, dynamicLightAtTile, rayReaches } from "../../../shared/lighting/raycast.js"; |
| 46 | import { LightOcclusion } from "../../../shared/definitions/tiles.js"; |
| 47 | import { tileLightOcclusionAt } from "../../../shared/lighting/chunkOcclusion.js"; |
| 48 | import { spellLightsForDynamicLighting } from "../spells/lights.js"; |
| 49 | import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js"; |
| 50 | import |
| 51 | { |
| 52 | effectiveSkillLevel, |
| 53 | equipmentBonusesFromSlots |
| 54 | } from "../../../shared/equipment/stats.js"; |
| 55 | import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js"; |
| 56 | import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js"; |
| 57 | import |
| 58 | { |
| 59 | markHealthDamaged, |
| 60 | PASSIVE_HP_REGEN_DELAY_MS, |
| 61 | PASSIVE_HP_REGEN_PER_SECOND |
| 62 | } from "../../../shared/combat/passiveRegen.js"; |
| 63 | import { publicEntityView } from "../ecs/serialize.js"; |
| 64 | import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js"; |
| 65 | import { chunkBoundsAround, findPath } from "../navigation/astar.js"; |
| 66 | import { tileToChunk } from "../world/coordinates.js"; |
| 67 | import { findPathToNearestGoal } from "../../../shared/navigation/bfs.js"; |
| 68 | import { CHUNK_SIZE, GAIT, VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js"; |
| 69 | import { stackQuantity, insertStack } from "../../../shared/items/inventory.js"; |
| 70 | import { addGroundItem, publicGroundItem, bagView } from "../items/bags.js"; |
| 71 | import { resolveItemDualTint } from "../../../shared/render/tint.js"; |
| 72 | import { essenceItemIdForElement } from "../../../shared/definitions/essenceItems.js"; |
| 73 | import { castMobAttackSpell } from "../spells/mobCast.js"; |
| 74 | import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js"; |
| 75 | import { scheduleSpawnerRespawn } from "../simulation/spawners.js"; |
| 76 | import |
| 77 | { |
| 78 | passiveHpRegenMultiplier, |
| 79 | attackerToHitRng, |
| 80 | enemyToHitRngAgainst, |
| 81 | hitSkillBonus, |
| 82 | jewelryDamageAffinities, |
| 83 | mergeAffinities, |
| 84 | damageReflectFraction, |
| 85 | autoLootOnKill, |
| 86 | ignoresNonBossAggro, |
| 87 | JADEITE_FAIRY_RESPAWN_MS |
| 88 | } from "../../../shared/equipment/jewelryEffects.js"; |
| 89 | |
| 90 | export function chebyshev (ax, ay, bx, by) |
| 91 | { |
| 92 | return Math.max(Math.abs(ax - bx), Math.abs(ay - by)); |
| 93 | } |
| 94 | |
| 95 | /** Creatures run while closing; they walk the last two tiles (and when standing to attack). */ |
| 96 | export const COMBAT_CHASE_RUN_TILES = 2; |
| 97 | |
| 98 | function creatureCanRun (world, handle) |
| 99 | { |
| 100 | const stamina = world.ecs.get(handle, Component.stamina); |
| 101 | if (!stamina) |
| 102 | { return true; } |
| 103 | return Number(stamina.current) > 0; |
| 104 | } |
| 105 | |
| 106 | function isCombatCreature (world, handle) |
| 107 | { |
| 108 | return !!world.ecs.get(handle, Component.creature) |
| 109 | && !world.ecs.get(handle, Component.character); |
| 110 | } |
| 111 | |
| 112 | function syncCreatureChaseGait (world, handle, dist, chasing) |
| 113 | { |
| 114 | if (!isCombatCreature(world, handle)) |
| 115 | { return; } |
| 116 | const movement = world.ecs.get(handle, Component.movement); |
| 117 | if (!movement) |
| 118 | { return; } |
| 119 | if (chasing && dist > COMBAT_CHASE_RUN_TILES && creatureCanRun(world, handle)) |
| 120 | { movement.gait = GAIT.run; } |
| 121 | else |
| 122 | { movement.gait = GAIT.walk; } |
| 123 | } |
| 124 | |
| 125 | function dropCombatTarget (world, entity) |
| 126 | { |
| 127 | entity.combat.targetEntityId = null; |
| 128 | syncCreatureChaseGait(world, entity.handle, 0, false); |
| 129 | } |
| 130 | |
| 131 | /** |
| 132 | * Stop everyone who was attacking / auto-casting at `targetEntityId` |
| 133 | * (melee engage, spell repeat, pending cast, approach path). |
| 134 | */ |
| 135 | export function clearAttackersTargeting (ecs, targetEntityId) |
| 136 | { |
| 137 | const targetId = targetEntityId | 0; |
| 138 | if (!targetId) |
| 139 | { return; } |
| 140 | for (const entity of ecs.query(Component.combat)) |
| 141 | { |
| 142 | if (entity.combat.targetEntityId !== targetId) |
| 143 | { continue; } |
| 144 | entity.combat.targetEntityId = null; |
| 145 | entity.combat.seekCover = false; |
| 146 | entity.combat.fleeFrom = null; |
| 147 | clearCombatApproachPath(ecs, entity.handle); |
| 148 | } |
| 149 | for (const entity of ecs.query(Component.spellcasting)) |
| 150 | { |
| 151 | const casting = entity.spellcasting; |
| 152 | if (!casting) |
| 153 | { continue; } |
| 154 | const pendingTarget = casting.pendingCast?.targetEntityId; |
| 155 | const hitting = casting.repeatTargetEntityId === targetId |
| 156 | || (pendingTarget != null && (pendingTarget | 0) === targetId); |
| 157 | if (!hitting) |
| 158 | { continue; } |
| 159 | casting.repeatSpellId = null; |
| 160 | casting.repeatTargetEntityId = null; |
| 161 | casting.repeatTileX = null; |
| 162 | casting.repeatTileY = null; |
| 163 | casting.pendingCast = null; |
| 164 | clearCombatApproachPath(ecs, entity.handle); |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | export function attackProfileOf (ecs, handle) |
| 169 | { |
| 170 | const creature = ecs.get(handle, Component.creature); |
| 171 | const level = creatureLevel(ecs, handle); |
| 172 | const equipment = ecs.get(handle, Component.equipment); |
| 173 | const weapon = equipment?.slots?.weapon; |
| 174 | if (weapon?.itemId != null) |
| 175 | { |
| 176 | const attack = itemDefinition(weapon.itemId)?.equipment?.attack; |
| 177 | if (attack) |
| 178 | { |
| 179 | const profile = { ...attack }; |
| 180 | if (creature) |
| 181 | { profile.mobAttackSkill = level; } |
| 182 | return profile; |
| 183 | } |
| 184 | } |
| 185 | if (creature) |
| 186 | { |
| 187 | const def = mobDefinition(creature.mobTypeId); |
| 188 | if (mobCanFightType(creature.mobTypeId)) |
| 189 | { return mobMeleeAttackProfile(def, level); } |
| 190 | } |
| 191 | return { ...UNARMED_ATTACK }; |
| 192 | } |
| 193 | |
| 194 | function creatureLevel (ecs, handle) |
| 195 | { |
| 196 | const creature = ecs.get(handle, Component.creature); |
| 197 | if (!creature) |
| 198 | { return 1; } |
| 199 | if (creature.level != null) |
| 200 | { return Math.max(1, creature.level | 0 || 1); } |
| 201 | const origin = ecs.get(handle, Component.spawnOrigin); |
| 202 | if (origin?.level != null) |
| 203 | { return Math.max(1, origin.level | 0 || 1); } |
| 204 | const def = mobDefinition(creature.mobTypeId); |
| 205 | return Math.max(1, def?.attackSkill | 0 || 1); |
| 206 | } |
| 207 | |
| 208 | export function weaponEquipmentKind (ecs, handle) |
| 209 | { |
| 210 | const equipment = ecs.get(handle, Component.equipment); |
| 211 | const weapon = equipment?.slots?.weapon; |
| 212 | if (!weapon?.itemId) |
| 213 | { return null; } |
| 214 | return itemDefinition(weapon.itemId)?.equipment?.kind ?? null; |
| 215 | } |
| 216 | |
| 217 | export function ensureMobCombat (ecs, entityId) |
| 218 | { |
| 219 | const handle = ecs.handleOf(entityId); |
| 220 | if (handle == null) |
| 221 | { return false; } |
| 222 | const creature = ecs.get(handle, Component.creature); |
| 223 | if (!creature || !mobCanFightType(creature.mobTypeId)) |
| 224 | { return false; } |
| 225 | const def = mobDefinition(creature.mobTypeId); |
| 226 | const level = creatureLevel(ecs, handle); |
| 227 | if (!ecs.get(handle, Component.combat)) |
| 228 | { ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0, seekCover: false, fleeFrom: null }); } |
| 229 | if (!ecs.get(handle, Component.skills)) |
| 230 | { ecs.add(handle, Component.skills, { levels: mobSkillLevels(def, level) }); } |
| 231 | return true; |
| 232 | } |
| 233 | |
| 234 | function attackerSkillLevel (skills, profile, skillId) |
| 235 | { |
| 236 | if (profile.mobAttackSkill != null) |
| 237 | { return profile.mobAttackSkill; } |
| 238 | return skillLevel(skills, skillId); |
| 239 | } |
| 240 | |
| 241 | function defenderSkillLevel (skills, skillId, equipment = null, settings = null) |
| 242 | { |
| 243 | const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots, settings) : {}; |
| 244 | return effectiveSkillLevel(skills, skillId, bonuses); |
| 245 | } |
| 246 | |
| 247 | function playerCombatLevels (ecs, handle, profile, settings = null) |
| 248 | { |
| 249 | const skills = ecs.get(handle, Component.skills); |
| 250 | const equipment = ecs.get(handle, Component.equipment); |
| 251 | const bonuses = equipmentBonusesFromSlots(equipment?.slots, settings); |
| 252 | const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now()); |
| 253 | bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0); |
| 254 | bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0); |
| 255 | |
| 256 | return { |
| 257 | hitLevel: effectiveSkillLevel(skills, profile.hitSkillId ?? SkillId.unarmed, bonuses) |
| 258 | + hitSkillBonus(equipment), |
| 259 | damageLevel: effectiveSkillLevel(skills, profile.damageSkillId ?? SkillId.strength, bonuses), |
| 260 | agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses), |
| 261 | defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses) |
| 262 | }; |
| 263 | } |
| 264 | |
| 265 | export function isUntargetable (ecs, handle) |
| 266 | { |
| 267 | if (ecs.has(handle, Component.dead)) |
| 268 | { return true; } |
| 269 | const creature = ecs.get(handle, Component.creature); |
| 270 | if (!creature) |
| 271 | { return false; } |
| 272 | return !!mobDefinition(creature.mobTypeId)?.untargetable; |
| 273 | } |
| 274 | |
| 275 | /** Stop active combat / cast / path activity when a player dies. |
| 276 | * Auto-cast preference is kept so respawn + re-cast can resume repeating. */ |
| 277 | export function silenceDeadPlayer (ecs, handle) |
| 278 | { |
| 279 | if (handle == null) |
| 280 | { return; } |
| 281 | const entityId = ecs.entityIdOf(handle); |
| 282 | if (entityId != null) |
| 283 | { clearEngage(ecs, entityId); } |
| 284 | const path = ecs.get(handle, Component.path); |
| 285 | if (path) |
| 286 | { path.tiles = []; } |
| 287 | const follow = ecs.get(handle, Component.follow); |
| 288 | if (follow) |
| 289 | { |
| 290 | follow.targetEntityId = null; |
| 291 | follow.trail = []; |
| 292 | } |
| 293 | const casting = ecs.get(handle, Component.spellcasting); |
| 294 | if (casting) |
| 295 | { |
| 296 | casting.armedSpellId = null; |
| 297 | casting.repeatSpellId = null; |
| 298 | casting.repeatTargetEntityId = null; |
| 299 | casting.repeatTileX = null; |
| 300 | casting.repeatTileY = null; |
| 301 | casting.pendingCast = null; |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | /** |
| 306 | * Player is mid click-order (walk / harvest) — do not auto-retaliate or |
| 307 | * cancel that order when a mob swings. |
| 308 | */ |
| 309 | export function playerBusyWithClickOrder (ecs, handle) |
| 310 | { |
| 311 | if (handle == null) |
| 312 | { return false; } |
| 313 | if (ecs.has(handle, Component.gather)) |
| 314 | { return true; } |
| 315 | const path = ecs.get(handle, Component.path); |
| 316 | return !!(path?.tiles?.length); |
| 317 | } |
| 318 | |
| 319 | /** |
| 320 | * Staff with a favorited attack spell → entity auto-cast at the attacker; |
| 321 | * otherwise melee engage. Returns true when a response was started. |
| 322 | */ |
| 323 | /** |
| 324 | * Staff + favorite entity attack spell: arm auto-cast at the target instead of melee engage. |
| 325 | * Used by click-Attack and auto-retaliate so casters hold spell range. |
| 326 | */ |
| 327 | export function tryArmStaffSpellAttack (ecs, playerId, targetEntityId) |
| 328 | { |
| 329 | const handle = ecs.handleOf(playerId); |
| 330 | if (handle == null) |
| 331 | { return false; } |
| 332 | const equipment = ecs.get(handle, Component.equipment); |
| 333 | const spells = ecs.get(handle, Component.spells); |
| 334 | const skills = ecs.get(handle, Component.skills); |
| 335 | let casting = ecs.get(handle, Component.spellcasting); |
| 336 | if (!casting && spells) |
| 337 | { |
| 338 | casting = ecs.add(handle, Component.spellcasting, { |
| 339 | armedSpellId: null, |
| 340 | repeatSpellId: null, |
| 341 | repeatTargetEntityId: null, |
| 342 | repeatTileX: null, |
| 343 | repeatTileY: null, |
| 344 | nextCastAt: 0, |
| 345 | pendingCast: null |
| 346 | }); |
| 347 | } |
| 348 | if (!(isMagicStaffEquipped(equipment?.slots) && casting && spells && skills)) |
| 349 | { return false; } |
| 350 | const spellId = firstFavoriteAttackSpellId(spells); |
| 351 | const def = spellId ? spellDefinition(spellId) : null; |
| 352 | if ( |
| 353 | !( |
| 354 | spellId |
| 355 | && def?.target === "entity" |
| 356 | && def.autoRepeat |
| 357 | && canCastSpell(skills, spells, spellId).ok |
| 358 | ) |
| 359 | ) |
| 360 | { return false; } |
| 361 | casting.repeatSpellId = spellId; |
| 362 | casting.repeatTargetEntityId = targetEntityId | 0; |
| 363 | casting.repeatTileX = null; |
| 364 | casting.repeatTileY = null; |
| 365 | casting.pendingCast = null; |
| 366 | const combat = ecs.get(handle, Component.combat); |
| 367 | if (combat) |
| 368 | { combat.targetEntityId = null; } |
| 369 | const path = ecs.get(handle, Component.path); |
| 370 | if (path) |
| 371 | { path.tiles = []; } |
| 372 | return true; |
| 373 | } |
| 374 | |
| 375 | export function maybePlayerRetaliate (world, playerId, attackerId, now = Date.now()) |
| 376 | { |
| 377 | const ecs = world.ecs; |
| 378 | const handle = ecs.handleOf(playerId); |
| 379 | if (handle == null || ecs.has(handle, Component.dead)) |
| 380 | { return false; } |
| 381 | if (playerBusyWithClickOrder(ecs, handle)) |
| 382 | { return false; } |
| 383 | if (isSpellCombatBusy(ecs, handle)) |
| 384 | { return false; } |
| 385 | |
| 386 | const follow = ecs.get(handle, Component.follow); |
| 387 | if (follow) |
| 388 | { |
| 389 | follow.targetEntityId = null; |
| 390 | follow.trail = []; |
| 391 | } |
| 392 | if (ecs.has(handle, Component.gather)) |
| 393 | { ecs.remove(handle, Component.gather); } |
| 394 | |
| 395 | if (tryArmStaffSpellAttack(ecs, playerId, attackerId)) |
| 396 | { return true; } |
| 397 | return engageTarget(ecs, playerId, attackerId, now); |
| 398 | } |
| 399 | |
| 400 | export function engageTarget (ecs, attackerId, targetId, now = Date.now()) |
| 401 | { |
| 402 | const handle = ecs.handleOf(attackerId); |
| 403 | if (handle == null) |
| 404 | { return false; } |
| 405 | if (ecs.has(handle, Component.dead)) |
| 406 | { return false; } |
| 407 | const targetHandle = ecs.handleOf(targetId); |
| 408 | if (targetHandle != null && ecs.has(targetHandle, Component.dead)) |
| 409 | { return false; } |
| 410 | // Spell auto-cast / pending cast is already the active combat form. |
| 411 | if (isSpellCombatBusy(ecs, handle)) |
| 412 | { return false; } |
| 413 | let combat = ecs.get(handle, Component.combat); |
| 414 | if (!combat) |
| 415 | { combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0, seekCover: false, fleeFrom: null }); } |
| 416 | const targetChanged = combat.targetEntityId !== targetId; |
| 417 | combat.targetEntityId = targetId; |
| 418 | if (targetChanged) |
| 419 | { |
| 420 | // New engage (or switch): allow an immediate swing; keep cadence if already on this target. |
| 421 | combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now); |
| 422 | const path = ecs.get(handle, Component.path); |
| 423 | if (path) |
| 424 | { path.tiles = []; } |
| 425 | } |
| 426 | return true; |
| 427 | } |
| 428 | |
| 429 | /** Melee mobs shot by player ranged/spells prefer cover while closing. */ |
| 430 | export function markSeekCover (ecs, entityId) |
| 431 | { |
| 432 | const handle = ecs.handleOf(entityId); |
| 433 | const combat = handle != null ? ecs.get(handle, Component.combat) : null; |
| 434 | if (combat) |
| 435 | { combat.seekCover = true; } |
| 436 | } |
| 437 | |
| 438 | /** |
| 439 | * Flee-on-hit mobs (fairies) path away from the hit source until far enough, |
| 440 | * then stop fleeing until the next successful hit. |
| 441 | */ |
| 442 | export function markFleeOnHit (world, targetId, attackerId) |
| 443 | { |
| 444 | const ecs = world.ecs; |
| 445 | const targetHandle = ecs.handleOf(targetId); |
| 446 | if (targetHandle == null) |
| 447 | { return; } |
| 448 | const creature = ecs.get(targetHandle, Component.creature); |
| 449 | if (!creature || ecs.get(targetHandle, Component.character)) |
| 450 | { return; } |
| 451 | // Companion summons (jadeite fairy, shade) stay in the fight. |
| 452 | if (ecs.get(targetHandle, Component.summon)) |
| 453 | { return; } |
| 454 | const fleeDist = mobDefinition(creature.mobTypeId)?.fleeOnHitTiles | 0; |
| 455 | if (fleeDist <= 0) |
| 456 | { return; } |
| 457 | if (!ensureMobCombat(ecs, targetId)) |
| 458 | { return; } |
| 459 | const combat = ecs.get(targetHandle, Component.combat); |
| 460 | const targetPos = ecs.get(targetHandle, Component.position); |
| 461 | const attackerHandle = ecs.handleOf(attackerId); |
| 462 | const attackerPos = attackerHandle != null ? ecs.get(attackerHandle, Component.position) : null; |
| 463 | if (!combat || !targetPos || !attackerPos) |
| 464 | { return; } |
| 465 | if (chebyshev(targetPos.tileX, targetPos.tileY, attackerPos.tileX, attackerPos.tileY) >= fleeDist) |
| 466 | { |
| 467 | combat.fleeFrom = null; |
| 468 | return; |
| 469 | } |
| 470 | combat.fleeFrom = { |
| 471 | tileX: attackerPos.tileX, |
| 472 | tileY: attackerPos.tileY, |
| 473 | minDist: fleeDist |
| 474 | }; |
| 475 | const path = ecs.get(targetHandle, Component.path); |
| 476 | if (path) |
| 477 | { path.tiles = []; } |
| 478 | } |
| 479 | |
| 480 | /** Pending cast or entity-spell auto-repeat — physical combat must not run. */ |
| 481 | export function isSpellCombatBusy (ecs, handle) |
| 482 | { |
| 483 | const casting = ecs.get(handle, Component.spellcasting); |
| 484 | if (!casting) |
| 485 | { return false; } |
| 486 | if (casting.pendingCast) |
| 487 | { return true; } |
| 488 | if (!casting.repeatSpellId) |
| 489 | { return false; } |
| 490 | const def = spellDefinition(casting.repeatSpellId); |
| 491 | return def?.target === "entity"; |
| 492 | } |
| 493 | |
| 494 | function clearSpellCombatState (ecs, handle) |
| 495 | { |
| 496 | const casting = ecs.get(handle, Component.spellcasting); |
| 497 | if (!casting) |
| 498 | { return; } |
| 499 | casting.repeatSpellId = null; |
| 500 | casting.repeatTargetEntityId = null; |
| 501 | casting.repeatTileX = null; |
| 502 | casting.repeatTileY = null; |
| 503 | casting.pendingCast = null; |
| 504 | } |
| 505 | |
| 506 | export function clearEngage (ecs, entityId) |
| 507 | { |
| 508 | const handle = ecs.handleOf(entityId); |
| 509 | const combat = handle != null ? ecs.get(handle, Component.combat) : null; |
| 510 | if (combat) |
| 511 | { |
| 512 | combat.targetEntityId = null; |
| 513 | combat.seekCover = false; |
| 514 | combat.fleeFrom = null; |
| 515 | } |
| 516 | } |
| 517 | |
| 518 | export function hasCombatLineOfSight (world, fromX, fromY, toX, toY) |
| 519 | { |
| 520 | const isClear = world.isClearForRangedAttack |
| 521 | ? (x, y) => world.isClearForRangedAttack(x, y) |
| 522 | : (x, y) => world.isEnterable(x, y); |
| 523 | return rayReaches(fromX, fromY, toX, toY, isClear); |
| 524 | } |
| 525 | |
| 526 | function lightOcclusionAtWorld (world, x, y) |
| 527 | { |
| 528 | const data = world.chunkData?.(tileToChunk(x), tileToChunk(y)); |
| 529 | if (!data) |
| 530 | { return LightOcclusion.clear; } |
| 531 | const index = tileIndexLocal(x, y); |
| 532 | if (Array.isArray(data.occlusion) && data.occlusion.length > index) |
| 533 | { return data.occlusion[index] | 0; } |
| 534 | const localX = ((x % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE; |
| 535 | const localY = ((y % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE; |
| 536 | return tileLightOcclusionAt(data.grounds, data.blocks, localX, localY); |
| 537 | } |
| 538 | |
| 539 | /** |
| 540 | * Target-tile lighting 0–1 for combat. |
| 541 | * Block lights (torches, …) use live occlusion so passage-open doors let light through; |
| 542 | * entity/spell lights layer on top (same compositing as client inner 3×3). |
| 543 | */ |
| 544 | export function tileLightAt (world, tileX, tileY, now = Date.now()) |
| 545 | { |
| 546 | const occlusionAt = (x, y) => lightOcclusionAtWorld(world, x, y); |
| 547 | const blockSources = blockLightSourcesNearTile( |
| 548 | (chunkX, chunkY) => world.chunkData?.(chunkX, chunkY), |
| 549 | tileX, |
| 550 | tileY |
| 551 | ); |
| 552 | const blockLit = dynamicLightAtTile(tileX, tileY, blockSources, occlusionAt); |
| 553 | const entity = entityLightAtTile(world.ecs, Component, tileX, tileY, now); |
| 554 | const { lights, darks } = spellLightsForDynamicLighting(world.spellLights, now); |
| 555 | const spellLight = dynamicLightAtTile(tileX, tileY, lights, occlusionAt); |
| 556 | const spellDark = dynamicDarknessAtTile(tileX, tileY, darks, occlusionAt); |
| 557 | const worldTime = world.worldTime?.(now); |
| 558 | return tileCombatLight01({ |
| 559 | bakedLight01: blockLit, |
| 560 | entityLight01: entity, |
| 561 | spellLight01: spellLight, |
| 562 | spellDark01: spellDark, |
| 563 | worldHour: worldTime?.hour ?? 12, |
| 564 | nightDarkness: world.settings?.nightDarkness ?? 0.72 |
| 565 | }); |
| 566 | } |
| 567 | |
| 568 | function arrowStackInOffhand (equipment) |
| 569 | { |
| 570 | const stack = equipment?.slots?.offhand; |
| 571 | if (!stack) |
| 572 | { return null; } |
| 573 | const def = itemDefinition(stack.itemId); |
| 574 | if (def?.equipment?.kind !== EquipmentKind.arrowAmmo) |
| 575 | { return null; } |
| 576 | return stack; |
| 577 | } |
| 578 | |
| 579 | /** Physical attack type, or tipped-arrow element for ranged shots. */ |
| 580 | function resolveAttackDamageType (ecs, attackerHandle, profile) |
| 581 | { |
| 582 | if (attackerHandle != null && profile?.mode === "ranged") |
| 583 | { |
| 584 | const stack = arrowStackInOffhand(ecs.get(attackerHandle, Component.equipment)); |
| 585 | if (stack?.instance?.kind === "tipped-arrow" && stack.instance.element) |
| 586 | { return stack.instance.element; } |
| 587 | } |
| 588 | return profile?.attackType ?? AttackType.blunt; |
| 589 | } |
| 590 | |
| 591 | function consumeArrow (ecs, handle) |
| 592 | { |
| 593 | const equipment = ecs.get(handle, Component.equipment); |
| 594 | const stack = arrowStackInOffhand(equipment); |
| 595 | if (!stack || stackQuantity(stack.quantity) <= 0) |
| 596 | { return false; } |
| 597 | if (stackQuantity(stack.quantity) <= 1) |
| 598 | { equipment.slots.offhand = null; } |
| 599 | else |
| 600 | { stack.quantity = stackQuantity(stack.quantity) - 1; } |
| 601 | return true; |
| 602 | } |
| 603 | |
| 604 | /** Fixed `quantity`, or inclusive `quantityMin`/`quantityMax` range (default 1). */ |
| 605 | function rollDropQuantity (drop) |
| 606 | { |
| 607 | if (drop.quantityMin != null || drop.quantityMax != null) |
| 608 | { |
| 609 | const min = Math.max(0, Math.floor(Number(drop.quantityMin ?? 1))); |
| 610 | const max = Math.max(min, Math.floor(Number(drop.quantityMax ?? min))); |
| 611 | return min + Math.floor(Math.random() * (max - min + 1)); |
| 612 | } |
| 613 | return Math.max(1, Math.floor(Number(drop.quantity ?? 1))); |
| 614 | } |
| 615 | |
| 616 | function spawnMobDrops (world, targetHandle, tileX, tileY, now, attackerId = null) |
| 617 | { |
| 618 | const creature = world.ecs.get(targetHandle, Component.creature); |
| 619 | if (!creature) |
| 620 | { return []; } |
| 621 | // Summons (e.g. Shade spell) never drop loot — only wild / spawner mobs. |
| 622 | if (world.ecs.get(targetHandle, Component.summon)) |
| 623 | { return []; } |
| 624 | const def = mobDefinition(creature.mobTypeId); |
| 625 | const mobName = entityCombatDisplayName(world.ecs, targetHandle) |
| 626 | || def?.displayName |
| 627 | || "a creature"; |
| 628 | let killerName = "someone"; |
| 629 | if (attackerId != null) |
| 630 | { |
| 631 | const attackerHandle = world.ecs.handleOf(attackerId); |
| 632 | if (attackerHandle != null) |
| 633 | { killerName = entityCombatDisplayName(world.ecs, attackerHandle) || "someone"; } |
| 634 | } |
| 635 | const origin = lootOrigin(mobName, killerName); |
| 636 | const events = []; |
| 637 | const spawnOrigin = world.ecs.get(targetHandle, Component.spawnOrigin); |
| 638 | const dropTable = [ |
| 639 | ...(def?.drops ?? []), |
| 640 | ...(Array.isArray(spawnOrigin?.drops) ? spawnOrigin.drops : []) |
| 641 | ]; |
| 642 | if (creature.element && (def?.essenceDropChance ?? 0) > 0) |
| 643 | { |
| 644 | const essenceId = essenceItemIdForElement(creature.element); |
| 645 | if (essenceId) |
| 646 | { dropTable.push({ itemId: essenceId, chance: def.essenceDropChance }); } |
| 647 | } |
| 648 | for (const drop of dropTable) |
| 649 | { |
| 650 | if (Math.random() > (drop.chance ?? 1)) |
| 651 | { continue; } |
| 652 | const quantity = rollDropQuantity(drop); |
| 653 | if (quantity <= 0) |
| 654 | { continue; } |
| 655 | const stack = attachOrigins({ |
| 656 | itemId: drop.itemId, |
| 657 | quantity, |
| 658 | origins: [{ origin, quantity }] |
| 659 | }); |
| 660 | if (tryAutoLootToKiller(world, attackerId, stack, events)) |
| 661 | { continue; } |
| 662 | const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1); |
| 663 | const item = { |
| 664 | groundItemId, |
| 665 | tileX, |
| 666 | tileY, |
| 667 | stack, |
| 668 | droppedAt: now, |
| 669 | expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000), |
| 670 | source: "mob-drop" |
| 671 | }; |
| 672 | addGroundItem(world, item); |
| 673 | events.push({ |
| 674 | type: "ground-item-appear", |
| 675 | ...publicGroundItem(item), |
| 676 | stack: item.stack, |
| 677 | droppedAt: item.droppedAt, |
| 678 | source: item.source, |
| 679 | expiresAt: item.expiresAt |
| 680 | }); |
| 681 | } |
| 682 | return events; |
| 683 | } |
| 684 | |
| 685 | function tryAutoLootToKiller (world, attackerId, stack, events) |
| 686 | { |
| 687 | if (attackerId == null) |
| 688 | { return false; } |
| 689 | const attackerHandle = world.ecs.handleOf(attackerId); |
| 690 | if (attackerHandle == null) |
| 691 | { return false; } |
| 692 | const equipment = world.ecs.get(attackerHandle, Component.equipment); |
| 693 | if (!autoLootOnKill(equipment)) |
| 694 | { return false; } |
| 695 | const inventory = world.ecs.get(attackerHandle, Component.inventory); |
| 696 | const character = world.ecs.get(attackerHandle, Component.character); |
| 697 | const def = itemDefinition(stack.itemId); |
| 698 | if (!inventory || !character || !def) |
| 699 | { return false; } |
| 700 | const inserted = insertStack(inventory.slots, stack, def); |
| 701 | if (!inserted.ok || (inserted.remainder | 0) > 0) |
| 702 | { return false; } |
| 703 | inventory.slots = inserted.slots; |
| 704 | events.push({ |
| 705 | type: "inventory", |
| 706 | characterId: character.characterId, |
| 707 | ...bagView(world.ecs, attackerHandle) |
| 708 | }); |
| 709 | return true; |
| 710 | } |
| 711 | |
| 712 | function entityCombatDisplayName (ecs, handle) |
| 713 | { |
| 714 | const appearance = ecs.get(handle, Component.appearance); |
| 715 | const fromAppearance = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim(); |
| 716 | if (fromAppearance) |
| 717 | { return fromAppearance; } |
| 718 | const creature = ecs.get(handle, Component.creature); |
| 719 | if (creature?.mobTypeId) |
| 720 | { |
| 721 | const def = mobDefinition(creature.mobTypeId); |
| 722 | if (def?.displayName) |
| 723 | { return def.displayName; } |
| 724 | } |
| 725 | return null; |
| 726 | } |
| 727 | |
| 728 | function projectileDualTintFromAttacker (ecs, handle) |
| 729 | { |
| 730 | const equipment = ecs.get(handle, Component.equipment); |
| 731 | const stack = arrowStackInOffhand(equipment); |
| 732 | if (!stack) |
| 733 | { return null; } |
| 734 | return resolveItemDualTint(stack, itemDefinition(stack.itemId)); |
| 735 | } |
| 736 | |
| 737 | function projectileSpriteFromAttacker (ecs, handle) |
| 738 | { |
| 739 | const equipment = ecs.get(handle, Component.equipment); |
| 740 | const stack = arrowStackInOffhand(equipment); |
| 741 | if (stack?.instance?.kind === "tipped-arrow") |
| 742 | { return "fx:projectile:arrow-tipped"; } |
| 743 | return "fx:projectile:arrow"; |
| 744 | } |
| 745 | |
| 746 | function publicDualTint (dualTint) |
| 747 | { |
| 748 | if (!dualTint) |
| 749 | { return null; } |
| 750 | return { |
| 751 | shaftTint: dualTint.shaft, |
| 752 | tipTint: dualTint.tip, |
| 753 | ...(dualTint.coat ? { coatTint: dualTint.coat } : {}) |
| 754 | }; |
| 755 | } |
| 756 | |
| 757 | function missProjectileTile (targetTileX, targetTileY, rng = Math.random) |
| 758 | { |
| 759 | const angle = rng() * Math.PI * 2; |
| 760 | const dist = rng(); |
| 761 | return { |
| 762 | tileX: Math.round(targetTileX + Math.cos(angle) * dist), |
| 763 | tileY: Math.round(targetTileY + Math.sin(angle) * dist) |
| 764 | }; |
| 765 | } |
| 766 | |
| 767 | /** |
| 768 | * Aggressive mobs auto-engage the nearest player or town guard within aggro range |
| 769 | * when they have line of sight. Town guards auto-engage aggressive creatures and |
| 770 | * players whose skull tint has started lerping toward red. |
| 771 | * Does nothing while already engaged. |
| 772 | */ |
| 773 | export function stepAggression (world, now = Date.now()) |
| 774 | { |
| 775 | for (const entity of world.ecs.query(Component.creature, Component.position)) |
| 776 | { |
| 777 | if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY)) |
| 778 | { continue; } |
| 779 | const def = mobDefinition(entity.creature.mobTypeId); |
| 780 | if (world.ecs.get(entity.handle, Component.summon)) |
| 781 | { continue; } |
| 782 | const origin = world.ecs.get(entity.handle, Component.spawnOrigin); |
| 783 | const townGuard = !!origin?.townGuard || isTownGuardMob(entity.creature.mobTypeId); |
| 784 | const aggressive = origin |
| 785 | ? !!origin.aggressive |
| 786 | : mobIsAggressive(def); |
| 787 | if ((!aggressive && !townGuard) || !mobCanFight(def)) |
| 788 | { continue; } |
| 789 | if (world.ecs.has(entity.handle, Component.dead)) |
| 790 | { continue; } |
| 791 | const health = world.ecs.get(entity.handle, Component.health); |
| 792 | if (health && health.current <= 0) |
| 793 | { continue; } |
| 794 | const combat = world.ecs.get(entity.handle, Component.combat); |
| 795 | if (combat?.targetEntityId != null) |
| 796 | { continue; } |
| 797 | |
| 798 | const range = mobAggroRangeTiles(def); |
| 799 | const bestId = townGuard |
| 800 | ? pickAggressionTargetForTownGuard(world, entity, range) |
| 801 | : pickAggressionTargetPlayerOrGuard(world, entity, range, now); |
| 802 | if (bestId == null) |
| 803 | { continue; } |
| 804 | if (!ensureMobCombat(world.ecs, entity.entityId)) |
| 805 | { continue; } |
| 806 | engageTarget(world.ecs, entity.entityId, bestId, now); |
| 807 | } |
| 808 | } |
| 809 | |
| 810 | function creatureIsAggressiveHostile (world, handle, creature) |
| 811 | { |
| 812 | if (!creature || world.ecs.get(handle, Component.character)) |
| 813 | { return false; } |
| 814 | if (world.ecs.get(handle, Component.summon)) |
| 815 | { return false; } |
| 816 | const origin = world.ecs.get(handle, Component.spawnOrigin); |
| 817 | if (origin?.townGuard || isTownGuardMob(creature.mobTypeId)) |
| 818 | { return false; } |
| 819 | if (origin) |
| 820 | { return !!origin.aggressive; } |
| 821 | return mobIsAggressive(mobDefinition(creature.mobTypeId)); |
| 822 | } |
| 823 | |
| 824 | function entityIsTownGuard (world, handle, creature) |
| 825 | { |
| 826 | if (!creature || world.ecs.get(handle, Component.character)) |
| 827 | { return false; } |
| 828 | const origin = world.ecs.get(handle, Component.spawnOrigin); |
| 829 | return !!origin?.townGuard || isTownGuardMob(creature.mobTypeId); |
| 830 | } |
| 831 | |
| 832 | /** Nearest living player or town guard in range with LOS. */ |
| 833 | function pickAggressionTargetPlayerOrGuard (world, entity, range, now = Date.now()) |
| 834 | { |
| 835 | let bestId = null; |
| 836 | let bestDist = Infinity; |
| 837 | for (const player of world.ecs.query(Component.character, Component.position)) |
| 838 | { |
| 839 | if (playerIgnoresAggressiveMob(world, entity, player.handle, now)) |
| 840 | { continue; } |
| 841 | const dist = considerAggressionCandidate(world, entity, player.handle, player.entityId, player.position, range); |
| 842 | if (dist != null && dist < bestDist) |
| 843 | { |
| 844 | bestDist = dist; |
| 845 | bestId = player.entityId; |
| 846 | } |
| 847 | } |
| 848 | for (const other of world.ecs.query(Component.creature, Component.position)) |
| 849 | { |
| 850 | if (other.entityId === entity.entityId) |
| 851 | { continue; } |
| 852 | if (!entityIsTownGuard(world, other.handle, other.creature)) |
| 853 | { continue; } |
| 854 | const dist = considerAggressionCandidate(world, entity, other.handle, other.entityId, other.position, range); |
| 855 | if (dist != null && dist < bestDist) |
| 856 | { |
| 857 | bestDist = dist; |
| 858 | bestId = other.entityId; |
| 859 | } |
| 860 | } |
| 861 | return bestId; |
| 862 | } |
| 863 | |
| 864 | /** Non-boss aggressive mobs skip players who outlevel them or have chunk peace. */ |
| 865 | function playerIgnoresAggressiveMob (world, mobEntity, playerHandle, now) |
| 866 | { |
| 867 | const def = mobDefinition(mobEntity.creature.mobTypeId); |
| 868 | if (mobIsBoss(def)) |
| 869 | { return false; } |
| 870 | const playerEquipment = world.ecs.get(playerHandle, Component.equipment); |
| 871 | if (ignoresNonBossAggro(playerEquipment)) |
| 872 | { return true; } |
| 873 | const skills = world.ecs.get(playerHandle, Component.skills); |
| 874 | if (!skills) |
| 875 | { return false; } |
| 876 | const playerLevel = combatLevelFromSkills(skills); |
| 877 | const origin = world.ecs.get(mobEntity.handle, Component.spawnOrigin); |
| 878 | const mobLevel = mobAggressionLevel(mobEntity.creature, origin, def); |
| 879 | if (playerOutlevelsMobAggression(playerLevel, mobLevel)) |
| 880 | { return true; } |
| 881 | const presence = world.ecs.get(playerHandle, Component.chunkPresence); |
| 882 | const pos = world.ecs.get(playerHandle, Component.position); |
| 883 | if (!presence || !pos) |
| 884 | { return false; } |
| 885 | return chunkPeaceAggressionImmunity( |
| 886 | presence, |
| 887 | pos.tileX, |
| 888 | pos.tileY, |
| 889 | pos.dimensionId ?? OVERWORLD_ID, |
| 890 | now, |
| 891 | tileToChunk |
| 892 | ); |
| 893 | } |
| 894 | |
| 895 | /** |
| 896 | * Nearest aggressive hostile creature or red-lerping skulled player in range |
| 897 | * with LOS (for town guards). |
| 898 | */ |
| 899 | function pickAggressionTargetForTownGuard (world, entity, range) |
| 900 | { |
| 901 | let bestId = null; |
| 902 | let bestDist = Infinity; |
| 903 | for (const other of world.ecs.query(Component.creature, Component.position)) |
| 904 | { |
| 905 | if (other.entityId === entity.entityId) |
| 906 | { continue; } |
| 907 | if (!creatureIsAggressiveHostile(world, other.handle, other.creature)) |
| 908 | { continue; } |
| 909 | if (!mobCanFight(mobDefinition(other.creature.mobTypeId))) |
| 910 | { continue; } |
| 911 | const dist = considerAggressionCandidate(world, entity, other.handle, other.entityId, other.position, range); |
| 912 | if (dist != null && dist < bestDist) |
| 913 | { |
| 914 | bestDist = dist; |
| 915 | bestId = other.entityId; |
| 916 | } |
| 917 | } |
| 918 | for (const player of world.ecs.query(Component.character, Component.position)) |
| 919 | { |
| 920 | if (!skullAttractsTownGuards(player.character?.skullValue, world.settings)) |
| 921 | { continue; } |
| 922 | const dist = considerAggressionCandidate(world, entity, player.handle, player.entityId, player.position, range); |
| 923 | if (dist != null && dist < bestDist) |
| 924 | { |
| 925 | bestDist = dist; |
| 926 | bestId = player.entityId; |
| 927 | } |
| 928 | } |
| 929 | return bestId; |
| 930 | } |
| 931 | |
| 932 | /** |
| 933 | * @returns {number|null} Chebyshev distance if a valid aggro candidate, else null. |
| 934 | */ |
| 935 | function considerAggressionCandidate (world, attacker, targetHandle, targetEntityId, targetPos, range) |
| 936 | { |
| 937 | if (world.ecs.has(targetHandle, Component.dead)) |
| 938 | { return null; } |
| 939 | const health = world.ecs.get(targetHandle, Component.health); |
| 940 | if (health && health.current <= 0) |
| 941 | { return null; } |
| 942 | const dist = chebyshev( |
| 943 | attacker.position.tileX, |
| 944 | attacker.position.tileY, |
| 945 | targetPos.tileX, |
| 946 | targetPos.tileY |
| 947 | ); |
| 948 | if (dist < 1 || dist > range) |
| 949 | { return null; } |
| 950 | let effectiveDist = dist; |
| 951 | if (dist > 1) |
| 952 | { |
| 953 | const light = tileLightAt(world, targetPos.tileX, targetPos.tileY); |
| 954 | effectiveDist = dist * aggroDistanceMultiplier(light); |
| 955 | } |
| 956 | if (effectiveDist > range) |
| 957 | { return null; } |
| 958 | if (!hasCombatLineOfSight( |
| 959 | world, |
| 960 | attacker.position.tileX, |
| 961 | attacker.position.tileY, |
| 962 | targetPos.tileX, |
| 963 | targetPos.tileY |
| 964 | )) |
| 965 | { return null; } |
| 966 | return dist; |
| 967 | } |
| 968 | |
| 969 | /** Local entity handle or a nearby ghost snapshot for cross-worker combat. */ |
| 970 | export function resolveCombatTarget (world, targetId) |
| 971 | { |
| 972 | const handle = world.ecs.handleOf(targetId); |
| 973 | if (handle != null) |
| 974 | { |
| 975 | const pos = world.ecs.get(handle, Component.position); |
| 976 | if (!pos) |
| 977 | { return null; } |
| 978 | if (isUntargetable(world.ecs, handle)) |
| 979 | { return null; } |
| 980 | return { |
| 981 | local: true, |
| 982 | handle, |
| 983 | pos, |
| 984 | health: world.ecs.get(handle, Component.health) |
| 985 | }; |
| 986 | } |
| 987 | const ghost = world.ghosts?.get?.(targetId); |
| 988 | if (!ghost || ghost.untargetable) |
| 989 | { return null; } |
| 990 | const health = ghost.health != null |
| 991 | ? { current: ghost.health, max: ghost.maxHealth ?? ghost.health } |
| 992 | : null; |
| 993 | return { |
| 994 | local: false, |
| 995 | handle: null, |
| 996 | pos: { tileX: ghost.tileX, tileY: ghost.tileY }, |
| 997 | health |
| 998 | }; |
| 999 | } |
| 1000 | |
| 1001 | function attackerCombatLevels (ecs, attackerHandle, profile, settings = null) |
| 1002 | { |
| 1003 | const attackerCharacter = ecs.get(attackerHandle, Component.character); |
| 1004 | if (attackerCharacter) |
| 1005 | { return playerCombatLevels(ecs, attackerHandle, profile, settings); } |
| 1006 | const skills = ecs.get(attackerHandle, Component.skills); |
| 1007 | const equipment = ecs.get(attackerHandle, Component.equipment); |
| 1008 | const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots, settings) : {}; |
| 1009 | const hitSkillId = profile.hitSkillId ?? SkillId.unarmed; |
| 1010 | const damageSkillId = profile.damageSkillId ?? SkillId.strength; |
| 1011 | const baseHit = attackerSkillLevel(skills, profile, hitSkillId); |
| 1012 | const baseDamage = attackerSkillLevel(skills, profile, damageSkillId); |
| 1013 | return { |
| 1014 | hitLevel: Math.max(1, baseHit + (bonuses[hitSkillId] ?? 0)), |
| 1015 | damageLevel: Math.max(1, baseDamage + (bonuses[damageSkillId] ?? 0)), |
| 1016 | agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses), |
| 1017 | defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses) |
| 1018 | }; |
| 1019 | } |
| 1020 | |
| 1021 | export function stepPassiveHealthRegen (world, now = Date.now(), dt = 1 / 20) |
| 1022 | { |
| 1023 | const events = []; |
| 1024 | for (const entity of world.ecs.query(Component.health, Component.position)) |
| 1025 | { |
| 1026 | const { handle, entityId, health, position, character } = entity; |
| 1027 | if (world.ecs.has(handle, Component.dead)) |
| 1028 | { continue; } |
| 1029 | if (!world.chunkIsSimulating?.(position.tileX, position.tileY)) |
| 1030 | { continue; } |
| 1031 | if ((health.current | 0) >= (health.max | 0)) |
| 1032 | { continue; } |
| 1033 | const lastDamageAt = health.lastDamageAt ?? 0; |
| 1034 | if (now - lastDamageAt < PASSIVE_HP_REGEN_DELAY_MS) |
| 1035 | { continue; } |
| 1036 | const beforeInt = health.current | 0; |
| 1037 | const equipment = world.ecs.get(handle, Component.equipment); |
| 1038 | const regenMult = passiveHpRegenMultiplier(equipment); |
| 1039 | health.current = Math.min( |
| 1040 | health.max | 0, |
| 1041 | (Number(health.current) || 0) + PASSIVE_HP_REGEN_PER_SECOND * regenMult * dt |
| 1042 | ); |
| 1043 | if ((health.current | 0) === beforeInt) |
| 1044 | { continue; } |
| 1045 | if (character) |
| 1046 | { syncPlayerHealth(world.ecs, handle); } |
| 1047 | const view = publicEntityView(world.ecs, entityId); |
| 1048 | if (!view) |
| 1049 | { continue; } |
| 1050 | events.push({ |
| 1051 | type: "entity-health", |
| 1052 | entityId, |
| 1053 | ...(character ? { characterId: character.characterId } : {}), |
| 1054 | health: view.health, |
| 1055 | maxHealth: view.maxHealth, |
| 1056 | tileX: view.tileX, |
| 1057 | tileY: view.tileY |
| 1058 | }); |
| 1059 | } |
| 1060 | return events; |
| 1061 | } |
| 1062 | |
| 1063 | export function stepCombat (world, now = Date.now()) |
| 1064 | { |
| 1065 | const events = []; |
| 1066 | for (const entity of world.ecs.query(Component.combat, Component.position)) |
| 1067 | { |
| 1068 | if (world.ecs.has(entity.handle, Component.dead)) |
| 1069 | { |
| 1070 | dropCombatTarget(world, entity); |
| 1071 | continue; |
| 1072 | } |
| 1073 | if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY)) |
| 1074 | { continue; } |
| 1075 | const combat = entity.combat; |
| 1076 | const targetId = combat.targetEntityId; |
| 1077 | if (targetId == null) |
| 1078 | { continue; } |
| 1079 | const target = resolveCombatTarget(world, targetId); |
| 1080 | if (!target) |
| 1081 | { |
| 1082 | dropCombatTarget(world, entity); |
| 1083 | continue; |
| 1084 | } |
| 1085 | if (target.health && target.health.current <= 0) |
| 1086 | { |
| 1087 | dropCombatTarget(world, entity); |
| 1088 | continue; |
| 1089 | } |
| 1090 | |
| 1091 | // One combat form at a time: spell cast / auto-cast wins over melee & archery. |
| 1092 | if (isSpellCombatBusy(world.ecs, entity.handle)) |
| 1093 | { continue; } |
| 1094 | |
| 1095 | if (combat.fleeFrom) |
| 1096 | { |
| 1097 | const flee = combat.fleeFrom; |
| 1098 | const minDist = Math.max(1, flee.minDist | 0 || 2); |
| 1099 | const fleeDist = chebyshev( |
| 1100 | entity.position.tileX, |
| 1101 | entity.position.tileY, |
| 1102 | flee.tileX, |
| 1103 | flee.tileY |
| 1104 | ); |
| 1105 | if (fleeDist >= minDist) |
| 1106 | { |
| 1107 | combat.fleeFrom = null; |
| 1108 | clearCombatApproachPath(world.ecs, entity.handle); |
| 1109 | } |
| 1110 | else |
| 1111 | { |
| 1112 | queueFleeFromHitSource(world, entity.entityId, entity.handle, entity.position, flee, minDist); |
| 1113 | continue; |
| 1114 | } |
| 1115 | } |
| 1116 | |
| 1117 | const profile = attackProfileOf(world.ecs, entity.handle); |
| 1118 | const targetPos = target.pos; |
| 1119 | const isCreature = isCombatCreature(world, entity.handle); |
| 1120 | const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY); |
| 1121 | |
| 1122 | if (profile.mode === "ranged") |
| 1123 | { |
| 1124 | const maxRange = profile.rangeTiles | 0 || COMBAT_RANGE_TILES; |
| 1125 | const equipment = world.ecs.get(entity.handle, Component.equipment); |
| 1126 | const hasArrows = isCreature |
| 1127 | || (arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0); |
| 1128 | const inRange = dist >= 1 && dist <= maxRange |
| 1129 | && hasCombatLineOfSight( |
| 1130 | world, |
| 1131 | entity.position.tileX, |
| 1132 | entity.position.tileY, |
| 1133 | targetPos.tileX, |
| 1134 | targetPos.tileY |
| 1135 | ); |
| 1136 | if (!inRange || !hasArrows) |
| 1137 | { |
| 1138 | if (inRange && !hasArrows && now >= (combat.nextSwingAt || 0) |
| 1139 | && world.ecs.get(entity.handle, Component.character)) |
| 1140 | { |
| 1141 | combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200); |
| 1142 | events.push({ |
| 1143 | type: "combat-no-arrows", |
| 1144 | attackerId: entity.entityId, |
| 1145 | sessionId: world.ecs.get(entity.handle, Component.networkIdentity)?.sessionId ?? null |
| 1146 | }); |
| 1147 | } |
| 1148 | syncCreatureChaseGait(world, entity.handle, dist, true); |
| 1149 | queueRangedApproach(world, entity.entityId, entity.handle, entity.position, targetPos, maxRange); |
| 1150 | continue; |
| 1151 | } |
| 1152 | syncCreatureChaseGait(world, entity.handle, dist, false); |
| 1153 | clearCombatApproachPath(world.ecs, entity.handle); |
| 1154 | if (now < (combat.nextSwingAt || 0)) |
| 1155 | { continue; } |
| 1156 | combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200); |
| 1157 | clearSpellCombatState(world.ecs, entity.handle); |
| 1158 | events.push(...resolveRangedShot(world, entity.entityId, targetId, profile, now, targetPos)); |
| 1159 | continue; |
| 1160 | } |
| 1161 | |
| 1162 | if (profile.mode !== "melee") |
| 1163 | { continue; } |
| 1164 | |
| 1165 | const canSwing = dist === 1 |
| 1166 | && world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY); |
| 1167 | const attackSpells = isCreature ? eligibleMobAttackSpells(world.ecs, entity.handle) : []; |
| 1168 | const preferSpell = isCreature |
| 1169 | && !!mobDefinition(world.ecs.get(entity.handle, Component.creature)?.mobTypeId)?.preferSpellAttack; |
| 1170 | const shouldCast = isCreature && attackSpells.length > 0 && (!canSwing || preferSpell); |
| 1171 | |
| 1172 | if (shouldCast) |
| 1173 | { |
| 1174 | const inSpellRange = dist >= 1 && dist <= COMBAT_RANGE_TILES |
| 1175 | && hasCombatLineOfSight( |
| 1176 | world, |
| 1177 | entity.position.tileX, |
| 1178 | entity.position.tileY, |
| 1179 | targetPos.tileX, |
| 1180 | targetPos.tileY |
| 1181 | ); |
| 1182 | if (!inSpellRange) |
| 1183 | { |
| 1184 | syncCreatureChaseGait(world, entity.handle, dist, true); |
| 1185 | queueStandInRangeApproach( |
| 1186 | world, |
| 1187 | entity.entityId, |
| 1188 | entity.handle, |
| 1189 | entity.position, |
| 1190 | targetPos.tileX, |
| 1191 | targetPos.tileY, |
| 1192 | COMBAT_RANGE_TILES, |
| 1193 | 1 |
| 1194 | ); |
| 1195 | continue; |
| 1196 | } |
| 1197 | syncCreatureChaseGait(world, entity.handle, dist, false); |
| 1198 | clearCombatApproachPath(world.ecs, entity.handle); |
| 1199 | if (now < (combat.nextSwingAt || 0)) |
| 1200 | { continue; } |
| 1201 | const picked = pickMobAttackSpell(attackSpells); |
| 1202 | if (!picked) |
| 1203 | { |
| 1204 | combat.nextSwingAt = now + SPELL_COOLDOWN_MS; |
| 1205 | continue; |
| 1206 | } |
| 1207 | combat.nextSwingAt = now + SPELL_COOLDOWN_MS; |
| 1208 | events.push(...castMobAttackSpell(world, entity.entityId, targetId, picked.spellId, now)); |
| 1209 | continue; |
| 1210 | } |
| 1211 | |
| 1212 | if (!canSwing) |
| 1213 | { |
| 1214 | syncCreatureChaseGait(world, entity.handle, dist, true); |
| 1215 | queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos); |
| 1216 | continue; |
| 1217 | } |
| 1218 | syncCreatureChaseGait(world, entity.handle, dist, false); |
| 1219 | clearCombatApproachPath(world.ecs, entity.handle); |
| 1220 | const attackerHealth = world.ecs.get(entity.handle, Component.health); |
| 1221 | if (attackerHealth && attackerHealth.current <= 0) |
| 1222 | { continue; } |
| 1223 | if ((combat.nextSwingAt || 0) > now) |
| 1224 | { continue; } |
| 1225 | |
| 1226 | combat.nextSwingAt = now + (profile.cooldownMs || 800); |
| 1227 | clearSpellCombatState(world.ecs, entity.handle); |
| 1228 | events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now)); |
| 1229 | } |
| 1230 | return events; |
| 1231 | } |
| 1232 | |
| 1233 | function eligibleMobAttackSpells (ecs, handle) |
| 1234 | { |
| 1235 | const spells = ecs.get(handle, Component.spells); |
| 1236 | if (!spells?.known?.length) |
| 1237 | { return []; } |
| 1238 | const level = creatureLevel(ecs, handle); |
| 1239 | const chances = spells.castChances ?? {}; |
| 1240 | const out = []; |
| 1241 | for (const spellId of spells.known) |
| 1242 | { |
| 1243 | const def = spellDefinition(spellId); |
| 1244 | if (!def || def.target !== "entity") |
| 1245 | { continue; } |
| 1246 | const minLevel = spellMinMagicLevel(def); |
| 1247 | if (level < minLevel) |
| 1248 | { continue; } |
| 1249 | const chance = Math.max(0, Math.min(100, Number(chances[spellId]) || 0)) | 0; |
| 1250 | if (chance <= 0) |
| 1251 | { continue; } |
| 1252 | out.push({ spellId, chance }); |
| 1253 | } |
| 1254 | return out; |
| 1255 | } |
| 1256 | |
| 1257 | function pickMobAttackSpell (spells) |
| 1258 | { |
| 1259 | if (!spells.length) |
| 1260 | { return null; } |
| 1261 | const pick = spells[Math.floor(Math.random() * spells.length)]; |
| 1262 | if ((Math.random() * 100) >= pick.chance) |
| 1263 | { return null; } |
| 1264 | return pick; |
| 1265 | } |
| 1266 | |
| 1267 | function clearCombatApproachPath (ecs, handle) |
| 1268 | { |
| 1269 | const path = ecs.get(handle, Component.path); |
| 1270 | if (path?.tiles?.length) |
| 1271 | { path.tiles = []; } |
| 1272 | } |
| 1273 | |
| 1274 | function combatTileKey (tileX, tileY) |
| 1275 | { |
| 1276 | return `${tileX},${tileY}`; |
| 1277 | } |
| 1278 | |
| 1279 | /** Tiles claimed by other combatants fighting the same target (position, next step, path goal). */ |
| 1280 | function collectCombatAllyReservations (world, entityId, targetEntityId) |
| 1281 | { |
| 1282 | const reserved = new Set(); |
| 1283 | if (targetEntityId == null) |
| 1284 | { return reserved; } |
| 1285 | for (const entity of world.ecs.query(Component.combat, Component.position)) |
| 1286 | { |
| 1287 | if (entity.entityId === entityId) |
| 1288 | { continue; } |
| 1289 | if (entity.combat.targetEntityId !== targetEntityId) |
| 1290 | { continue; } |
| 1291 | reserved.add(combatTileKey(entity.position.tileX, entity.position.tileY)); |
| 1292 | const allyPath = world.ecs.get(entity.handle, Component.path); |
| 1293 | if (!allyPath?.tiles?.length) |
| 1294 | { continue; } |
| 1295 | const next = allyPath.tiles[0]; |
| 1296 | if (next) |
| 1297 | { reserved.add(combatTileKey(next.x, next.y)); } |
| 1298 | const dest = allyPath.tiles[allyPath.tiles.length - 1]; |
| 1299 | if (dest) |
| 1300 | { reserved.add(combatTileKey(dest.x, dest.y)); } |
| 1301 | } |
| 1302 | return reserved; |
| 1303 | } |
| 1304 | |
| 1305 | function combatGoalPreference (entityId, tileX, tileY) |
| 1306 | { |
| 1307 | return ((tileX * 73856093) ^ (tileY * 19349663) ^ (entityId * 83492791)) >>> 0; |
| 1308 | } |
| 1309 | |
| 1310 | /** Cost multiplier for tiles the threat can currently shoot. */ |
| 1311 | const COVER_EXPOSED_STEP_COST = 5; |
| 1312 | |
| 1313 | function mobHasRangedRetaliation (world, handle) |
| 1314 | { |
| 1315 | const profile = attackProfileOf(world.ecs, handle); |
| 1316 | if (profile?.mode === "ranged") |
| 1317 | { return true; } |
| 1318 | return eligibleMobAttackSpells(world.ecs, handle).length > 0; |
| 1319 | } |
| 1320 | |
| 1321 | /** Melee-only creatures closing after a player ranged/spell hit. */ |
| 1322 | function shouldSeekCoverApproach (world, handle) |
| 1323 | { |
| 1324 | if (world.ecs.get(handle, Component.character)) |
| 1325 | { return false; } |
| 1326 | if (!world.ecs.get(handle, Component.creature)) |
| 1327 | { return false; } |
| 1328 | const combat = world.ecs.get(handle, Component.combat); |
| 1329 | if (!combat?.seekCover) |
| 1330 | { return false; } |
| 1331 | return !mobHasRangedRetaliation(world, handle); |
| 1332 | } |
| 1333 | |
| 1334 | function coverStepCost (world, threatPos, goalX, goalY, x, y) |
| 1335 | { |
| 1336 | // Final adjacent step is always in LOS — don't punish the last lunge. |
| 1337 | if (x === goalX && y === goalY) |
| 1338 | { return 1; } |
| 1339 | if (hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, x, y)) |
| 1340 | { return COVER_EXPOSED_STEP_COST; } |
| 1341 | return 1; |
| 1342 | } |
| 1343 | |
| 1344 | function pathCoverScore (world, threatPos, tiles) |
| 1345 | { |
| 1346 | let score = 0; |
| 1347 | for (const step of tiles) |
| 1348 | { |
| 1349 | score += hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, step.x, step.y) |
| 1350 | ? COVER_EXPOSED_STEP_COST |
| 1351 | : 1; |
| 1352 | } |
| 1353 | return score; |
| 1354 | } |
| 1355 | |
| 1356 | function listAdjacentMeleeGoals (world, entityId, position, targetPos, reserved) |
| 1357 | { |
| 1358 | const dirs = [ |
| 1359 | { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 }, |
| 1360 | { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 } |
| 1361 | ]; |
| 1362 | const goals = []; |
| 1363 | for (const dir of dirs) |
| 1364 | { |
| 1365 | const x = targetPos.tileX + dir.x; |
| 1366 | const y = targetPos.tileY + dir.y; |
| 1367 | const isHere = x === position.tileX && y === position.tileY; |
| 1368 | const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true; |
| 1369 | const key = combatTileKey(x, y); |
| 1370 | if (reserved?.has(key) && !(isHere && aloneHere)) |
| 1371 | { continue; } |
| 1372 | const clear = world.isClearStanding?.(entityId, x, y) |
| 1373 | ?? world.walkableFor(entityId, x, y); |
| 1374 | if (!clear && !isHere) |
| 1375 | { continue; } |
| 1376 | if (isHere && !aloneHere) |
| 1377 | { continue; } |
| 1378 | goals.push({ x, y }); |
| 1379 | } |
| 1380 | return goals; |
| 1381 | } |
| 1382 | |
| 1383 | function findCoverMeleeApproachPath (world, entityId, handle, position, targetPos, reserved) |
| 1384 | { |
| 1385 | const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); |
| 1386 | const preferVertical = !!world.ecs.get(handle, Component.character); |
| 1387 | const isWalkable = (x, y, goal) => |
| 1388 | { |
| 1389 | if (x === goal.x && y === goal.y) |
| 1390 | { |
| 1391 | return world.isClearStanding?.(entityId, x, y) |
| 1392 | ?? world.walkableFor(entityId, x, y); |
| 1393 | } |
| 1394 | return world.walkableFor(entityId, x, y); |
| 1395 | }; |
| 1396 | let bestTiles = null; |
| 1397 | let bestScore = Infinity; |
| 1398 | let bestPref = Infinity; |
| 1399 | for (const goal of listAdjacentMeleeGoals(world, entityId, position, targetPos, reserved)) |
| 1400 | { |
| 1401 | if (goal.x === position.tileX && goal.y === position.tileY) |
| 1402 | { return []; } |
| 1403 | const tiles = findPath( |
| 1404 | position.tileX, |
| 1405 | position.tileY, |
| 1406 | goal.x, |
| 1407 | goal.y, |
| 1408 | (x, y) => isWalkable(x, y, goal), |
| 1409 | bounds.minX, |
| 1410 | bounds.minY, |
| 1411 | bounds.maxX, |
| 1412 | bounds.maxY, |
| 1413 | { |
| 1414 | preferVertical, |
| 1415 | stepCost: (x, y) => coverStepCost(world, targetPos, goal.x, goal.y, x, y) |
| 1416 | } |
| 1417 | ); |
| 1418 | if (!tiles.length) |
| 1419 | { continue; } |
| 1420 | const score = pathCoverScore(world, targetPos, tiles); |
| 1421 | const pref = combatGoalPreference(entityId, goal.x, goal.y); |
| 1422 | if (score < bestScore || (score === bestScore && pref < bestPref)) |
| 1423 | { |
| 1424 | bestScore = score; |
| 1425 | bestPref = pref; |
| 1426 | bestTiles = tiles; |
| 1427 | } |
| 1428 | } |
| 1429 | return bestTiles; |
| 1430 | } |
| 1431 | |
| 1432 | /** Duck behind the nearest tile the threat cannot shoot when melee approach is impossible. */ |
| 1433 | function queueFleeToCover (world, entityId, handle, position, threatPos) |
| 1434 | { |
| 1435 | let path = world.ecs.get(handle, Component.path); |
| 1436 | if (!path) |
| 1437 | { path = world.ecs.add(handle, Component.path, { tiles: [] }); } |
| 1438 | const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); |
| 1439 | const isWalkable = (x, y) => world.walkableFor(entityId, x, y); |
| 1440 | const isGoal = (x, y) => |
| 1441 | { |
| 1442 | if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y))) |
| 1443 | { return false; } |
| 1444 | if (chebyshev(x, y, threatPos.tileX, threatPos.tileY) < 1) |
| 1445 | { return false; } |
| 1446 | return !hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, x, y); |
| 1447 | }; |
| 1448 | if (isGoal(position.tileX, position.tileY)) |
| 1449 | { |
| 1450 | path.tiles = []; |
| 1451 | return; |
| 1452 | } |
| 1453 | const tiles = findPathToNearestGoal( |
| 1454 | position.tileX, |
| 1455 | position.tileY, |
| 1456 | isGoal, |
| 1457 | isWalkable, |
| 1458 | bounds.minX, |
| 1459 | bounds.minY, |
| 1460 | bounds.maxX, |
| 1461 | bounds.maxY |
| 1462 | ); |
| 1463 | if (!tiles.length) |
| 1464 | { |
| 1465 | path.tiles = []; |
| 1466 | return; |
| 1467 | } |
| 1468 | path.tiles = tiles; |
| 1469 | const movement = world.ecs.get(handle, Component.movement); |
| 1470 | if (movement) |
| 1471 | { movement.walkCarry = 0; } |
| 1472 | } |
| 1473 | |
| 1474 | /** Path to the nearest standable tile at least `minDist` from the hit source. */ |
| 1475 | function queueFleeFromHitSource (world, entityId, handle, position, source, minDist) |
| 1476 | { |
| 1477 | if (world.frozen?.has?.(entityId)) |
| 1478 | { return; } |
| 1479 | let path = world.ecs.get(handle, Component.path); |
| 1480 | if (!path) |
| 1481 | { path = world.ecs.add(handle, Component.path, { tiles: [] }); } |
| 1482 | const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true; |
| 1483 | if ( |
| 1484 | aloneHere |
| 1485 | && chebyshev(position.tileX, position.tileY, source.tileX, source.tileY) >= minDist |
| 1486 | ) |
| 1487 | { |
| 1488 | path.tiles = []; |
| 1489 | return; |
| 1490 | } |
| 1491 | const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); |
| 1492 | const isWalkable = (x, y) => world.walkableFor(entityId, x, y); |
| 1493 | const isGoal = (x, y) => |
| 1494 | { |
| 1495 | if (chebyshev(x, y, source.tileX, source.tileY) < minDist) |
| 1496 | { return false; } |
| 1497 | return world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y); |
| 1498 | }; |
| 1499 | if (isGoal(position.tileX, position.tileY) && aloneHere) |
| 1500 | { |
| 1501 | path.tiles = []; |
| 1502 | return; |
| 1503 | } |
| 1504 | const dest = path.tiles?.length ? path.tiles[path.tiles.length - 1] : null; |
| 1505 | if ( |
| 1506 | dest |
| 1507 | && isGoal(dest.x, dest.y) |
| 1508 | && path.tiles.every((step) => isWalkable(step.x, step.y)) |
| 1509 | ) |
| 1510 | { return; } |
| 1511 | const tiles = findPathToNearestGoal( |
| 1512 | position.tileX, |
| 1513 | position.tileY, |
| 1514 | isGoal, |
| 1515 | isWalkable, |
| 1516 | bounds.minX, |
| 1517 | bounds.minY, |
| 1518 | bounds.maxX, |
| 1519 | bounds.maxY |
| 1520 | ); |
| 1521 | if (!tiles.length) |
| 1522 | { |
| 1523 | path.tiles = []; |
| 1524 | return; |
| 1525 | } |
| 1526 | path.tiles = tiles; |
| 1527 | const movement = world.ecs.get(handle, Component.movement); |
| 1528 | if (movement) |
| 1529 | { movement.walkCarry = 0; } |
| 1530 | } |
| 1531 | |
| 1532 | export function queueMeleeApproach (world, entityId, handle, position, targetPos) |
| 1533 | { |
| 1534 | if (world.frozen?.has?.(entityId)) |
| 1535 | { return; } |
| 1536 | let path = world.ecs.get(handle, Component.path); |
| 1537 | if (!path) |
| 1538 | { path = world.ecs.add(handle, Component.path, { tiles: [] }); } |
| 1539 | |
| 1540 | const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) |
| 1541 | ?? true; |
| 1542 | if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) === 1 && aloneHere) |
| 1543 | { |
| 1544 | path.tiles = []; |
| 1545 | return; |
| 1546 | } |
| 1547 | |
| 1548 | const combat = world.ecs.get(handle, Component.combat); |
| 1549 | const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null); |
| 1550 | const seekCover = shouldSeekCoverApproach(world, handle); |
| 1551 | |
| 1552 | if (seekCover) |
| 1553 | { |
| 1554 | const coverTiles = findCoverMeleeApproachPath( |
| 1555 | world, |
| 1556 | entityId, |
| 1557 | handle, |
| 1558 | position, |
| 1559 | targetPos, |
| 1560 | reserved |
| 1561 | ); |
| 1562 | if (coverTiles) |
| 1563 | { |
| 1564 | if (!coverTiles.length) |
| 1565 | { |
| 1566 | path.tiles = []; |
| 1567 | return; |
| 1568 | } |
| 1569 | const goal = coverTiles[coverTiles.length - 1]; |
| 1570 | if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved)) |
| 1571 | { return; } |
| 1572 | path.tiles = coverTiles; |
| 1573 | const movement = world.ecs.get(handle, Component.movement); |
| 1574 | if (movement) |
| 1575 | { movement.walkCarry = 0; } |
| 1576 | return; |
| 1577 | } |
| 1578 | queueFleeToCover(world, entityId, handle, position, targetPos); |
| 1579 | return; |
| 1580 | } |
| 1581 | |
| 1582 | const goal = bestAdjacentGoal(world, entityId, position, targetPos, reserved); |
| 1583 | if (!goal) |
| 1584 | { |
| 1585 | path.tiles = []; |
| 1586 | return; |
| 1587 | } |
| 1588 | |
| 1589 | if (goal.x === position.tileX && goal.y === position.tileY) |
| 1590 | { |
| 1591 | path.tiles = []; |
| 1592 | return; |
| 1593 | } |
| 1594 | |
| 1595 | if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved)) |
| 1596 | { return; } |
| 1597 | |
| 1598 | const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); |
| 1599 | const preferVertical = !!world.ecs.get(handle, Component.character); |
| 1600 | const tiles = findPath( |
| 1601 | position.tileX, |
| 1602 | position.tileY, |
| 1603 | goal.x, |
| 1604 | goal.y, |
| 1605 | (x, y) => |
| 1606 | { |
| 1607 | if (x === goal.x && y === goal.y) |
| 1608 | { |
| 1609 | return world.isClearStanding?.(entityId, x, y) |
| 1610 | ?? world.walkableFor(entityId, x, y); |
| 1611 | } |
| 1612 | return world.walkableFor(entityId, x, y); |
| 1613 | }, |
| 1614 | bounds.minX, |
| 1615 | bounds.minY, |
| 1616 | bounds.maxX, |
| 1617 | bounds.maxY, |
| 1618 | { preferVertical } |
| 1619 | ); |
| 1620 | if (!tiles.length) |
| 1621 | { |
| 1622 | path.tiles = []; |
| 1623 | return; |
| 1624 | } |
| 1625 | path.tiles = tiles; |
| 1626 | const movement = world.ecs.get(handle, Component.movement); |
| 1627 | if (movement) |
| 1628 | { movement.walkCarry = 0; } |
| 1629 | } |
| 1630 | |
| 1631 | /** |
| 1632 | * Path toward the nearest reachable tile from which `targetTile` is in Chebyshev range with LOS. |
| 1633 | * Goal is chosen by BFS flood from the actor (shortest walk), not min Chebyshev (which biases top-left). |
| 1634 | * @param {number} minStandDist Minimum stand-off from target (0 = may stand on target tile). |
| 1635 | */ |
| 1636 | export function queueStandInRangeApproach ( |
| 1637 | world, |
| 1638 | entityId, |
| 1639 | handle, |
| 1640 | position, |
| 1641 | targetTileX, |
| 1642 | targetTileY, |
| 1643 | maxRange, |
| 1644 | minStandDist = 1 |
| 1645 | ) |
| 1646 | { |
| 1647 | if (world.frozen?.has?.(entityId)) |
| 1648 | { return; } |
| 1649 | let path = world.ecs.get(handle, Component.path); |
| 1650 | if (!path) |
| 1651 | { path = world.ecs.add(handle, Component.path, { tiles: [] }); } |
| 1652 | |
| 1653 | const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY); |
| 1654 | const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true; |
| 1655 | if ( |
| 1656 | distToTarget <= maxRange |
| 1657 | && distToTarget >= minStandDist |
| 1658 | && aloneHere |
| 1659 | && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY) |
| 1660 | ) |
| 1661 | { |
| 1662 | path.tiles = []; |
| 1663 | return; |
| 1664 | } |
| 1665 | |
| 1666 | const combat = world.ecs.get(handle, Component.combat); |
| 1667 | const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null); |
| 1668 | const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); |
| 1669 | const isWalkable = (x, y) => world.walkableFor(entityId, x, y); |
| 1670 | const isGoal = (x, y) => |
| 1671 | { |
| 1672 | const standOff = chebyshev(x, y, targetTileX, targetTileY); |
| 1673 | if (standOff < minStandDist || standOff > maxRange) |
| 1674 | { return false; } |
| 1675 | if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y))) |
| 1676 | { return false; } |
| 1677 | const key = combatTileKey(x, y); |
| 1678 | if (reserved.has(key) && !(x === position.tileX && y === position.tileY)) |
| 1679 | { return false; } |
| 1680 | return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY); |
| 1681 | }; |
| 1682 | |
| 1683 | const tiles = findPathToNearestGoal( |
| 1684 | position.tileX, |
| 1685 | position.tileY, |
| 1686 | isGoal, |
| 1687 | isWalkable, |
| 1688 | bounds.minX, |
| 1689 | bounds.minY, |
| 1690 | bounds.maxX, |
| 1691 | bounds.maxY |
| 1692 | ); |
| 1693 | if (!tiles.length) |
| 1694 | { |
| 1695 | path.tiles = []; |
| 1696 | return; |
| 1697 | } |
| 1698 | const bestGoal = tiles[tiles.length - 1]; |
| 1699 | if (path.tiles?.length && !standInRangePathStale( |
| 1700 | world, |
| 1701 | entityId, |
| 1702 | path, |
| 1703 | bestGoal, |
| 1704 | targetTileX, |
| 1705 | targetTileY, |
| 1706 | maxRange, |
| 1707 | minStandDist, |
| 1708 | reserved, |
| 1709 | position |
| 1710 | )) |
| 1711 | { return; } |
| 1712 | path.tiles = tiles; |
| 1713 | const movement = world.ecs.get(handle, Component.movement); |
| 1714 | if (movement) |
| 1715 | { movement.walkCarry = 0; } |
| 1716 | } |
| 1717 | |
| 1718 | function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange) |
| 1719 | { |
| 1720 | queueStandInRangeApproach( |
| 1721 | world, |
| 1722 | entityId, |
| 1723 | handle, |
| 1724 | position, |
| 1725 | targetPos.tileX, |
| 1726 | targetPos.tileY, |
| 1727 | maxRange, |
| 1728 | 1 |
| 1729 | ); |
| 1730 | } |
| 1731 | |
| 1732 | export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos) |
| 1733 | { |
| 1734 | const events = []; |
| 1735 | const attackerHandle = world.ecs.handleOf(attackerId); |
| 1736 | if (attackerHandle == null) |
| 1737 | { return events; } |
| 1738 | const from = world.ecs.get(attackerHandle, Component.position); |
| 1739 | if (!from || !targetPos) |
| 1740 | { return events; } |
| 1741 | const isCreature = !!world.ecs.get(attackerHandle, Component.creature) |
| 1742 | && !world.ecs.get(attackerHandle, Component.character); |
| 1743 | const arrowTint = projectileDualTintFromAttacker(world.ecs, attackerHandle); |
| 1744 | const arrowSprite = projectileSpriteFromAttacker(world.ecs, attackerHandle); |
| 1745 | const tipElement = (() => |
| 1746 | { |
| 1747 | const stack = arrowStackInOffhand(world.ecs.get(attackerHandle, Component.equipment)); |
| 1748 | return stack?.instance?.kind === "tipped-arrow" ? stack.instance.element : null; |
| 1749 | })(); |
| 1750 | if (!isCreature && !consumeArrow(world.ecs, attackerHandle)) |
| 1751 | { return events; } |
| 1752 | |
| 1753 | const shotProfile = tipElement |
| 1754 | ? { ...profile, attackType: tipElement } |
| 1755 | : profile; |
| 1756 | |
| 1757 | const snapshot = { tileX: targetPos.tileX, tileY: targetPos.tileY }; |
| 1758 | const target = resolveCombatTarget(world, targetId); |
| 1759 | if (!target) |
| 1760 | { return events; } |
| 1761 | |
| 1762 | if (!target.local) |
| 1763 | { |
| 1764 | events.push({ |
| 1765 | type: "remote-ranged-resolve", |
| 1766 | attackerId, |
| 1767 | targetId, |
| 1768 | profile: shotProfile, |
| 1769 | attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, shotProfile, world.settings), |
| 1770 | attackerIsPlayer: !!world.ecs.get(attackerHandle, Component.character), |
| 1771 | now, |
| 1772 | tileX: snapshot.tileX, |
| 1773 | tileY: snapshot.tileY, |
| 1774 | fromTileX: from.tileX, |
| 1775 | fromTileY: from.tileY, |
| 1776 | sprite: arrowSprite, |
| 1777 | ...(publicDualTint(arrowTint) ?? {}) |
| 1778 | }); |
| 1779 | return events; |
| 1780 | } |
| 1781 | |
| 1782 | const hitEvents = applyLocalMeleeHit( |
| 1783 | world, |
| 1784 | attackerId, |
| 1785 | targetId, |
| 1786 | attackerHandle, |
| 1787 | target.handle, |
| 1788 | shotProfile, |
| 1789 | now, |
| 1790 | snapshot |
| 1791 | ); |
| 1792 | const outcome = hitEvents.find((e) => |
| 1793 | e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block"); |
| 1794 | let endX = snapshot.tileX; |
| 1795 | let endY = snapshot.tileY; |
| 1796 | if (outcome?.type === "combat-miss") |
| 1797 | { |
| 1798 | const miss = missProjectileTile(snapshot.tileX, snapshot.tileY); |
| 1799 | endX = miss.tileX; |
| 1800 | endY = miss.tileY; |
| 1801 | } |
| 1802 | else |
| 1803 | { |
| 1804 | const currentPos = world.ecs.get(target.handle, Component.position); |
| 1805 | if (currentPos) |
| 1806 | { |
| 1807 | endX = currentPos.tileX; |
| 1808 | endY = currentPos.tileY; |
| 1809 | } |
| 1810 | } |
| 1811 | events.push({ |
| 1812 | type: "combat-projectile", |
| 1813 | attackerId, |
| 1814 | targetId, |
| 1815 | fromTileX: from.tileX, |
| 1816 | fromTileY: from.tileY, |
| 1817 | tileX: endX, |
| 1818 | tileY: endY, |
| 1819 | durationMs: RANGED_PROJECTILE_MS, |
| 1820 | trackTarget: outcome?.type !== "combat-miss", |
| 1821 | sprite: arrowSprite, |
| 1822 | ...(publicDualTint(arrowTint) ?? {}) |
| 1823 | }); |
| 1824 | return events.concat(hitEvents); |
| 1825 | } |
| 1826 | |
| 1827 | function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist, reserved, position) |
| 1828 | { |
| 1829 | const dest = path.tiles[path.tiles.length - 1]; |
| 1830 | if (dest.x !== goal.x || dest.y !== goal.y) |
| 1831 | { return true; } |
| 1832 | const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY); |
| 1833 | if (standOff < minStandDist || standOff > maxRange) |
| 1834 | { return true; } |
| 1835 | if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY)) |
| 1836 | { return true; } |
| 1837 | if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true)) |
| 1838 | { return true; } |
| 1839 | const destKey = combatTileKey(dest.x, dest.y); |
| 1840 | if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY)) |
| 1841 | { return true; } |
| 1842 | const next = path.tiles[0]; |
| 1843 | if (!next) |
| 1844 | { return true; } |
| 1845 | if (!world.walkableFor(entityId, next.x, next.y)) |
| 1846 | { return true; } |
| 1847 | return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true); |
| 1848 | } |
| 1849 | |
| 1850 | function meleePathStale (world, entityId, position, targetPos, path, goal, reserved) |
| 1851 | { |
| 1852 | const dest = path.tiles[path.tiles.length - 1]; |
| 1853 | if (dest.x !== goal.x || dest.y !== goal.y) |
| 1854 | { return true; } |
| 1855 | if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1) |
| 1856 | { return true; } |
| 1857 | if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true)) |
| 1858 | { return true; } |
| 1859 | const destKey = combatTileKey(dest.x, dest.y); |
| 1860 | if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY)) |
| 1861 | { return true; } |
| 1862 | const next = path.tiles[0]; |
| 1863 | if (!next) |
| 1864 | { return true; } |
| 1865 | if (!world.walkableFor(entityId, next.x, next.y)) |
| 1866 | { return true; } |
| 1867 | return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true); |
| 1868 | } |
| 1869 | |
| 1870 | function bestAdjacentGoal (world, entityId, position, targetPos, reserved = null) |
| 1871 | { |
| 1872 | const dirs = [ |
| 1873 | { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 }, |
| 1874 | { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 } |
| 1875 | ]; |
| 1876 | let best = null; |
| 1877 | let bestDist = Infinity; |
| 1878 | let bestPref = Infinity; |
| 1879 | for (const dir of dirs) |
| 1880 | { |
| 1881 | const x = targetPos.tileX + dir.x; |
| 1882 | const y = targetPos.tileY + dir.y; |
| 1883 | const isHere = x === position.tileX && y === position.tileY; |
| 1884 | const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true; |
| 1885 | const key = combatTileKey(x, y); |
| 1886 | if (reserved?.has(key) && !(isHere && aloneHere)) |
| 1887 | { continue; } |
| 1888 | const clear = world.isClearStanding?.(entityId, x, y) |
| 1889 | ?? world.walkableFor(entityId, x, y); |
| 1890 | if (!clear && !isHere) |
| 1891 | { continue; } |
| 1892 | if (isHere && !aloneHere) |
| 1893 | { continue; } |
| 1894 | const dist = chebyshev(position.tileX, position.tileY, x, y); |
| 1895 | const pref = combatGoalPreference(entityId, x, y); |
| 1896 | if (dist < bestDist || (dist === bestDist && pref < bestPref)) |
| 1897 | { |
| 1898 | bestDist = dist; |
| 1899 | bestPref = pref; |
| 1900 | best = { x, y }; |
| 1901 | } |
| 1902 | } |
| 1903 | return best; |
| 1904 | } |
| 1905 | |
| 1906 | export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now()) |
| 1907 | { |
| 1908 | const events = []; |
| 1909 | const attackerHandle = world.ecs.handleOf(attackerId); |
| 1910 | if (attackerHandle == null) |
| 1911 | { return events; } |
| 1912 | const target = resolveCombatTarget(world, targetId); |
| 1913 | if (!target) |
| 1914 | { return events; } |
| 1915 | const from = world.ecs.get(attackerHandle, Component.position); |
| 1916 | const to = target.pos; |
| 1917 | if (!from || !to) |
| 1918 | { return events; } |
| 1919 | if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1) |
| 1920 | { return events; } |
| 1921 | if (world.isClearStanding && !world.isClearStanding(attackerId, from.tileX, from.tileY)) |
| 1922 | { return events; } |
| 1923 | |
| 1924 | events.push({ |
| 1925 | type: "combat-swing", |
| 1926 | attackerId, |
| 1927 | targetId, |
| 1928 | tileX: to.tileX, |
| 1929 | tileY: to.tileY, |
| 1930 | fromTileX: from.tileX, |
| 1931 | fromTileY: from.tileY |
| 1932 | }); |
| 1933 | |
| 1934 | if (!target.local) |
| 1935 | { |
| 1936 | const attackerCharacter = world.ecs.get(attackerHandle, Component.character); |
| 1937 | events.push({ |
| 1938 | type: "remote-melee-resolve", |
| 1939 | attackerId, |
| 1940 | targetId, |
| 1941 | profile, |
| 1942 | attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings), |
| 1943 | attackerIsPlayer: !!attackerCharacter, |
| 1944 | now, |
| 1945 | tileX: to.tileX, |
| 1946 | tileY: to.tileY |
| 1947 | }); |
| 1948 | return events; |
| 1949 | } |
| 1950 | |
| 1951 | return events.concat(applyLocalMeleeHit( |
| 1952 | world, |
| 1953 | attackerId, |
| 1954 | targetId, |
| 1955 | attackerHandle, |
| 1956 | target.handle, |
| 1957 | profile, |
| 1958 | now, |
| 1959 | to |
| 1960 | )); |
| 1961 | } |
| 1962 | |
| 1963 | /** Authoritative ranged hit when the defender lives on this worker. */ |
| 1964 | export function applyRemoteRangedShot (world, payload) |
| 1965 | { |
| 1966 | const targetHandle = world.ecs.handleOf(payload.targetId); |
| 1967 | if (targetHandle == null) |
| 1968 | { return { events: [], forwards: [] }; } |
| 1969 | const snapshot = { |
| 1970 | tileX: payload.tileX, |
| 1971 | tileY: payload.tileY |
| 1972 | }; |
| 1973 | |
| 1974 | const hitEvents = applyLocalMeleeHit( |
| 1975 | world, |
| 1976 | payload.attackerId, |
| 1977 | payload.targetId, |
| 1978 | null, |
| 1979 | targetHandle, |
| 1980 | payload.profile, |
| 1981 | payload.now ?? Date.now(), |
| 1982 | snapshot, |
| 1983 | payload.attackerLevels, |
| 1984 | payload.attackerIsPlayer |
| 1985 | ); |
| 1986 | |
| 1987 | const outcome = hitEvents.find((e) => |
| 1988 | e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block"); |
| 1989 | let endX = snapshot.tileX; |
| 1990 | let endY = snapshot.tileY; |
| 1991 | if (outcome?.type === "combat-miss") |
| 1992 | { |
| 1993 | const miss = missProjectileTile(snapshot.tileX, snapshot.tileY); |
| 1994 | endX = miss.tileX; |
| 1995 | endY = miss.tileY; |
| 1996 | } |
| 1997 | else |
| 1998 | { |
| 1999 | const currentPos = world.ecs.get(targetHandle, Component.position); |
| 2000 | if (currentPos) |
| 2001 | { |
| 2002 | endX = currentPos.tileX; |
| 2003 | endY = currentPos.tileY; |
| 2004 | } |
| 2005 | } |
| 2006 | |
| 2007 | const events = [{ |
| 2008 | type: "combat-projectile", |
| 2009 | attackerId: payload.attackerId, |
| 2010 | targetId: payload.targetId, |
| 2011 | fromTileX: payload.fromTileX, |
| 2012 | fromTileY: payload.fromTileY, |
| 2013 | tileX: endX, |
| 2014 | tileY: endY, |
| 2015 | durationMs: RANGED_PROJECTILE_MS, |
| 2016 | trackTarget: outcome?.type !== "combat-miss", |
| 2017 | sprite: payload.sprite ?? "fx:projectile:arrow", |
| 2018 | shaftTint: payload.shaftTint ?? null, |
| 2019 | tipTint: payload.tipTint ?? null, |
| 2020 | coatTint: payload.coatTint ?? null |
| 2021 | }, ...hitEvents]; |
| 2022 | |
| 2023 | const forwards = []; |
| 2024 | const hitEvent = hitEvents.find((event) => event.type === "combat-hit"); |
| 2025 | if (hitEvent && payload.attackerIsPlayer) |
| 2026 | { |
| 2027 | forwards.push({ |
| 2028 | type: "forward-combat-xp", |
| 2029 | entityId: payload.attackerId, |
| 2030 | profile: payload.profile, |
| 2031 | damage: hitEvent.damage |
| 2032 | }); |
| 2033 | } |
| 2034 | return { events, forwards }; |
| 2035 | } |
| 2036 | |
| 2037 | /** Authoritative hit resolution when the defender lives on this worker. */ |
| 2038 | export function applyRemoteMeleeSwing (world, payload) |
| 2039 | { |
| 2040 | const targetHandle = world.ecs.handleOf(payload.targetId); |
| 2041 | if (targetHandle == null) |
| 2042 | { return { events: [], forwards: [] }; } |
| 2043 | const to = world.ecs.get(targetHandle, Component.position); |
| 2044 | if (!to) |
| 2045 | { return { events: [], forwards: [] }; } |
| 2046 | |
| 2047 | const events = applyLocalMeleeHit( |
| 2048 | world, |
| 2049 | payload.attackerId, |
| 2050 | payload.targetId, |
| 2051 | null, |
| 2052 | targetHandle, |
| 2053 | payload.profile, |
| 2054 | payload.now ?? Date.now(), |
| 2055 | to, |
| 2056 | payload.attackerLevels, |
| 2057 | payload.attackerIsPlayer |
| 2058 | ); |
| 2059 | |
| 2060 | const forwards = []; |
| 2061 | const hitEvent = events.find((event) => event.type === "combat-hit"); |
| 2062 | if (hitEvent && payload.attackerIsPlayer) |
| 2063 | { |
| 2064 | forwards.push({ |
| 2065 | type: "forward-combat-xp", |
| 2066 | entityId: payload.attackerId, |
| 2067 | profile: payload.profile, |
| 2068 | damage: hitEvent.damage |
| 2069 | }); |
| 2070 | } |
| 2071 | return { events, forwards }; |
| 2072 | } |
| 2073 | |
| 2074 | function applyLocalMeleeHit ( |
| 2075 | world, |
| 2076 | attackerId, |
| 2077 | targetId, |
| 2078 | attackerHandle, |
| 2079 | targetHandle, |
| 2080 | profile, |
| 2081 | now, |
| 2082 | to, |
| 2083 | attackerLevelsOverride = null, |
| 2084 | attackerIsPlayerOverride = null |
| 2085 | ) |
| 2086 | { |
| 2087 | const events = []; |
| 2088 | if (targetHandle == null) |
| 2089 | { return events; } |
| 2090 | |
| 2091 | const attackerIsPlayer = attackerIsPlayerOverride != null |
| 2092 | ? !!attackerIsPlayerOverride |
| 2093 | : (attackerHandle != null ? !!world.ecs.get(attackerHandle, Component.character) : null); |
| 2094 | |
| 2095 | // Retaliate on the first resolved swing (hit or miss), not on Attack-click engage. |
| 2096 | if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId)) |
| 2097 | { |
| 2098 | engageTarget(world.ecs, targetId, attackerId, now); |
| 2099 | if (profile?.mode === "ranged") |
| 2100 | { markSeekCover(world.ecs, targetId); } |
| 2101 | } |
| 2102 | if (attackerIsPlayer === false) |
| 2103 | { |
| 2104 | const targetCharacter = world.ecs.get(targetHandle, Component.character); |
| 2105 | if (targetCharacter) |
| 2106 | { maybePlayerRetaliate(world, targetId, attackerId, now); } |
| 2107 | } |
| 2108 | |
| 2109 | const defenderSkills = world.ecs.get(targetHandle, Component.skills); |
| 2110 | const defenderEquipment = world.ecs.get(targetHandle, Component.equipment); |
| 2111 | const attackerLevels = attackerLevelsOverride |
| 2112 | ?? (attackerHandle != null |
| 2113 | ? attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings) |
| 2114 | : null); |
| 2115 | if (!attackerLevels) |
| 2116 | { return events; } |
| 2117 | |
| 2118 | const agilityLevel = defenderSkillLevel( |
| 2119 | defenderSkills, |
| 2120 | SkillId.agility, |
| 2121 | defenderEquipment, |
| 2122 | world.settings |
| 2123 | ); |
| 2124 | const defenceLevel = defenderSkillLevel( |
| 2125 | defenderSkills, |
| 2126 | SkillId.defence, |
| 2127 | defenderEquipment, |
| 2128 | world.settings |
| 2129 | ); |
| 2130 | |
| 2131 | const attackType = resolveAttackDamageType(world.ecs, attackerHandle, profile); |
| 2132 | const targetCreature = world.ecs.get(targetHandle, Component.creature); |
| 2133 | const mobAffinities = targetCreature |
| 2134 | ? mobDamageAffinities(mobDefinition(targetCreature.mobTypeId)) |
| 2135 | : {}; |
| 2136 | const targetAffinities = mergeAffinities(mobAffinities, jewelryDamageAffinities(defenderEquipment)); |
| 2137 | const attackerEquipment = attackerHandle != null |
| 2138 | ? world.ecs.get(attackerHandle, Component.equipment) |
| 2139 | : null; |
| 2140 | let hitRng = Math.random; |
| 2141 | hitRng = attackerToHitRng(attackerEquipment, hitRng); |
| 2142 | hitRng = enemyToHitRngAgainst(defenderEquipment, hitRng); |
| 2143 | const resolved = resolvePhysicalAttack({ |
| 2144 | hitSkillLevel: effectiveHitSkillInDarkness( |
| 2145 | attackerLevels.hitLevel, |
| 2146 | tileLightAt(world, to.tileX, to.tileY) |
| 2147 | ), |
| 2148 | agilitySkillLevel: agilityLevel, |
| 2149 | damageSkillLevel: attackerLevels.damageLevel, |
| 2150 | defenceSkillLevel: defenceLevel, |
| 2151 | attackType, |
| 2152 | targetAffinities, |
| 2153 | rng: hitRng |
| 2154 | }); |
| 2155 | |
| 2156 | if (resolved.outcome === "miss") |
| 2157 | { |
| 2158 | events.push({ |
| 2159 | type: "combat-miss", |
| 2160 | attackerId, |
| 2161 | targetId, |
| 2162 | tileX: to.tileX, |
| 2163 | tileY: to.tileY |
| 2164 | }); |
| 2165 | const dodgeXp = awardCombatAvoidanceXp( |
| 2166 | world.ecs, |
| 2167 | targetHandle, |
| 2168 | SkillId.agility, |
| 2169 | resolved.damageRoll |
| 2170 | ); |
| 2171 | if (dodgeXp) |
| 2172 | { |
| 2173 | events.push({ |
| 2174 | type: "skills-updated", |
| 2175 | entityId: targetId, |
| 2176 | characterId: dodgeXp.characterId, |
| 2177 | skills: dodgeXp.skills, |
| 2178 | combatLevel: dodgeXp.combatLevel, |
| 2179 | stored: dodgeXp.stored, |
| 2180 | levelUps: dodgeXp.levelUps ?? [] |
| 2181 | }); |
| 2182 | } |
| 2183 | return events; |
| 2184 | } |
| 2185 | |
| 2186 | if (resolved.outcome === "block") |
| 2187 | { |
| 2188 | events.push({ |
| 2189 | type: "combat-block", |
| 2190 | attackerId, |
| 2191 | targetId, |
| 2192 | tileX: to.tileX, |
| 2193 | tileY: to.tileY |
| 2194 | }); |
| 2195 | const blockXp = awardCombatAvoidanceXp( |
| 2196 | world.ecs, |
| 2197 | targetHandle, |
| 2198 | SkillId.defence, |
| 2199 | resolved.damageRoll |
| 2200 | ); |
| 2201 | if (blockXp) |
| 2202 | { |
| 2203 | events.push({ |
| 2204 | type: "skills-updated", |
| 2205 | entityId: targetId, |
| 2206 | characterId: blockXp.characterId, |
| 2207 | skills: blockXp.skills, |
| 2208 | combatLevel: blockXp.combatLevel, |
| 2209 | stored: blockXp.stored, |
| 2210 | levelUps: blockXp.levelUps ?? [] |
| 2211 | }); |
| 2212 | } |
| 2213 | return events; |
| 2214 | } |
| 2215 | |
| 2216 | const damage = resolved.damage; |
| 2217 | const targetCharacter = world.ecs.get(targetHandle, Component.character); |
| 2218 | if (targetCharacter) |
| 2219 | { syncPlayerHealth(world.ecs, targetHandle); } |
| 2220 | const health = world.ecs.get(targetHandle, Component.health); |
| 2221 | if (health) |
| 2222 | { |
| 2223 | health.current = Math.max(0, (health.current | 0) - damage); |
| 2224 | markHealthDamaged(health, now); |
| 2225 | } |
| 2226 | events.push({ |
| 2227 | type: "combat-hit", |
| 2228 | attackerId, |
| 2229 | targetId, |
| 2230 | damage, |
| 2231 | tileX: to.tileX, |
| 2232 | tileY: to.tileY, |
| 2233 | health: health?.current ?? 0, |
| 2234 | maxHealth: health?.max ?? 0 |
| 2235 | }); |
| 2236 | |
| 2237 | const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage); |
| 2238 | if (healthXp) |
| 2239 | { |
| 2240 | events.push({ |
| 2241 | type: "skills-updated", |
| 2242 | entityId: targetId, |
| 2243 | characterId: healthXp.characterId, |
| 2244 | skills: healthXp.skills, |
| 2245 | combatLevel: healthXp.combatLevel, |
| 2246 | stored: healthXp.stored, |
| 2247 | levelUps: healthXp.levelUps ?? [] |
| 2248 | }); |
| 2249 | if (health) |
| 2250 | { |
| 2251 | const hitEvent = events[events.length - 2]; |
| 2252 | if (hitEvent?.type === "combat-hit") |
| 2253 | { |
| 2254 | hitEvent.health = health.current; |
| 2255 | hitEvent.maxHealth = health.max; |
| 2256 | } |
| 2257 | } |
| 2258 | } |
| 2259 | |
| 2260 | events.push(...maybeReflectDamage(world, attackerId, targetId, targetHandle, damage, now)); |
| 2261 | |
| 2262 | if (attackerHandle != null) |
| 2263 | { markFleeOnHit(world, targetId, attackerId); } |
| 2264 | |
| 2265 | if (attackerHandle != null) |
| 2266 | { |
| 2267 | const attackerCharacter = world.ecs.get(attackerHandle, Component.character); |
| 2268 | if (attackerCharacter) |
| 2269 | { |
| 2270 | const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile, damage); |
| 2271 | if (xpAward) |
| 2272 | { |
| 2273 | events.push({ |
| 2274 | type: "skills-updated", |
| 2275 | entityId: attackerId, |
| 2276 | characterId: attackerCharacter.characterId, |
| 2277 | skills: xpAward.skills, |
| 2278 | combatLevel: xpAward.combatLevel, |
| 2279 | stored: xpAward.stored, |
| 2280 | levelUps: xpAward.levelUps ?? [] |
| 2281 | }); |
| 2282 | } |
| 2283 | } |
| 2284 | } |
| 2285 | |
| 2286 | if (health && health.current <= 0) |
| 2287 | { |
| 2288 | clearEngage(world.ecs, attackerId); |
| 2289 | clearEngage(world.ecs, targetId); |
| 2290 | clearAttackersTargeting(world.ecs, targetId); |
| 2291 | if (targetCharacter && !world.ecs.has(targetHandle, Component.dead)) |
| 2292 | { |
| 2293 | const path = world.ecs.get(targetHandle, Component.path); |
| 2294 | if (path) |
| 2295 | { path.tiles = []; } |
| 2296 | const follow = world.ecs.get(targetHandle, Component.follow); |
| 2297 | if (follow) |
| 2298 | { |
| 2299 | follow.targetEntityId = null; |
| 2300 | follow.trail = []; |
| 2301 | } |
| 2302 | world.ecs.add(targetHandle, Component.dead, {}); |
| 2303 | silenceDeadPlayer(world.ecs, targetHandle); |
| 2304 | const identity = world.ecs.get(targetHandle, Component.networkIdentity); |
| 2305 | events.push({ |
| 2306 | type: "player-died", |
| 2307 | entityId: targetId, |
| 2308 | attackerId, |
| 2309 | characterId: targetCharacter.characterId, |
| 2310 | sessionId: identity?.sessionId ?? null, |
| 2311 | tileX: to.tileX, |
| 2312 | tileY: to.tileY, |
| 2313 | health: 0, |
| 2314 | maxHealth: health.max |
| 2315 | }); |
| 2316 | } |
| 2317 | const creature = world.ecs.get(targetHandle, Component.creature); |
| 2318 | if (creature && !world.ecs.get(targetHandle, Component.character)) |
| 2319 | { |
| 2320 | events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); |
| 2321 | } |
| 2322 | } |
| 2323 | return events; |
| 2324 | } |
| 2325 | |
| 2326 | /** |
| 2327 | * Drops, despawn, and `mob-killed` for bounty / town-guard reaction. |
| 2328 | * Shared by melee and spell kill paths. |
| 2329 | */ |
| 2330 | export function finalizeMobKill (world, attackerId, targetId, targetHandle, tileX, tileY, now) |
| 2331 | { |
| 2332 | const events = []; |
| 2333 | const handle = targetHandle ?? world.ecs.handleOf(targetId); |
| 2334 | if (handle == null) |
| 2335 | { return events; } |
| 2336 | const creature = world.ecs.get(handle, Component.creature); |
| 2337 | const origin = world.ecs.get(handle, Component.spawnOrigin); |
| 2338 | const appearance = world.ecs.get(handle, Component.appearance); |
| 2339 | const summon = world.ecs.get(handle, Component.summon); |
| 2340 | if (summon?.kind === "jadeite-fairy") |
| 2341 | { |
| 2342 | const respawnAt = now + JADEITE_FAIRY_RESPAWN_MS; |
| 2343 | const characterId = summon.ownerCharacterId | 0; |
| 2344 | if (!world.jadeiteFairyTimers) |
| 2345 | { world.jadeiteFairyTimers = new Map(); } |
| 2346 | if (characterId) |
| 2347 | { world.jadeiteFairyTimers.set(characterId, respawnAt); } |
| 2348 | const ownerHandle = summon.ownerEntityId != null |
| 2349 | ? world.ecs.handleOf(summon.ownerEntityId) |
| 2350 | : null; |
| 2351 | const character = ownerHandle != null |
| 2352 | ? world.ecs.get(ownerHandle, Component.character) |
| 2353 | : null; |
| 2354 | if (character) |
| 2355 | { character.jadeiteFairyRespawnAt = respawnAt; } |
| 2356 | } |
| 2357 | events.push(...spawnMobDrops(world, handle, tileX, tileY, now, attackerId)); |
| 2358 | events.push({ |
| 2359 | type: "mob-killed", |
| 2360 | entityId: targetId, |
| 2361 | attackerId, |
| 2362 | mobTypeId: creature?.mobTypeId ?? null, |
| 2363 | level: creature?.level ?? origin?.level ?? 1, |
| 2364 | bounty: Math.max(0, origin?.bounty | 0 || 0), |
| 2365 | spawnerId: origin?.spawnerId ?? null, |
| 2366 | originTileX: origin?.originTileX ?? tileX, |
| 2367 | originTileY: origin?.originTileY ?? tileY, |
| 2368 | wanderRangeTiles: origin?.wanderRangeTiles ?? 0, |
| 2369 | townGuard: !!origin?.townGuard, |
| 2370 | displayName: appearance?.firstName ?? null, |
| 2371 | tileX, |
| 2372 | tileY |
| 2373 | }); |
| 2374 | if (origin?.spawnerId) |
| 2375 | { |
| 2376 | scheduleSpawnerRespawn( |
| 2377 | world, |
| 2378 | origin.spawnerId, |
| 2379 | origin.respawnDelaySeconds ?? 25, |
| 2380 | now |
| 2381 | ); |
| 2382 | } |
| 2383 | const view = world.destroyEntity?.(targetId) ?? null; |
| 2384 | if (view) |
| 2385 | { |
| 2386 | events.push({ |
| 2387 | type: "entity-despawn", |
| 2388 | entityId: targetId, |
| 2389 | tileX: view.tileX, |
| 2390 | tileY: view.tileY, |
| 2391 | cause: "death" |
| 2392 | }); |
| 2393 | } |
| 2394 | return events; |
| 2395 | } |
| 2396 | |
| 2397 | /** Apply HP loss and shared death/loot side-effects (used by spell impacts). */ |
| 2398 | export function applyDamageAndKill (world, attackerId, targetId, damage, now = Date.now(), options = {}) |
| 2399 | { |
| 2400 | const events = []; |
| 2401 | const targetHandle = world.ecs.handleOf(targetId); |
| 2402 | if (targetHandle == null) |
| 2403 | { return events; } |
| 2404 | const to = world.ecs.get(targetHandle, Component.position); |
| 2405 | if (!to) |
| 2406 | { return events; } |
| 2407 | const health = world.ecs.get(targetHandle, Component.health); |
| 2408 | if (health) |
| 2409 | { |
| 2410 | health.current = Math.max(0, (health.current | 0) - damage); |
| 2411 | markHealthDamaged(health, now); |
| 2412 | } |
| 2413 | events.push({ |
| 2414 | type: "combat-hit", |
| 2415 | attackerId, |
| 2416 | targetId, |
| 2417 | damage, |
| 2418 | tileX: to.tileX, |
| 2419 | tileY: to.tileY, |
| 2420 | health: health?.current ?? 0, |
| 2421 | maxHealth: health?.max ?? 0 |
| 2422 | }); |
| 2423 | |
| 2424 | const attackerHandle = world.ecs.handleOf(attackerId); |
| 2425 | if (attackerHandle != null && ensureMobCombat(world.ecs, targetId)) |
| 2426 | { |
| 2427 | const attackerIsPlayer = !!world.ecs.get(attackerHandle, Component.character); |
| 2428 | const targetCombat = world.ecs.get(targetHandle, Component.combat); |
| 2429 | if (targetCombat && targetCombat.targetEntityId == null) |
| 2430 | { engageTarget(world.ecs, targetId, attackerId, now); } |
| 2431 | if (attackerIsPlayer) |
| 2432 | { markSeekCover(world.ecs, targetId); } |
| 2433 | } |
| 2434 | if (attackerHandle != null) |
| 2435 | { markFleeOnHit(world, targetId, attackerId); } |
| 2436 | if (attackerHandle != null && world.ecs.get(targetHandle, Component.character)) |
| 2437 | { |
| 2438 | const attackerCreature = world.ecs.get(attackerHandle, Component.creature); |
| 2439 | if (attackerCreature) |
| 2440 | { maybePlayerRetaliate(world, targetId, attackerId, now); } |
| 2441 | } |
| 2442 | |
| 2443 | const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage); |
| 2444 | if (healthXp) |
| 2445 | { |
| 2446 | events.push({ |
| 2447 | type: "skills-updated", |
| 2448 | entityId: targetId, |
| 2449 | characterId: healthXp.characterId, |
| 2450 | skills: healthXp.skills, |
| 2451 | combatLevel: healthXp.combatLevel, |
| 2452 | stored: healthXp.stored, |
| 2453 | levelUps: healthXp.levelUps ?? [] |
| 2454 | }); |
| 2455 | } |
| 2456 | |
| 2457 | events.push(...maybeReflectDamage(world, attackerId, targetId, targetHandle, damage, now, options)); |
| 2458 | |
| 2459 | if (health && health.current <= 0) |
| 2460 | { |
| 2461 | clearEngage(world.ecs, attackerId); |
| 2462 | clearEngage(world.ecs, targetId); |
| 2463 | clearAttackersTargeting(world.ecs, targetId); |
| 2464 | const targetCharacter = world.ecs.get(targetHandle, Component.character); |
| 2465 | if (targetCharacter && !world.ecs.has(targetHandle, Component.dead)) |
| 2466 | { |
| 2467 | const path = world.ecs.get(targetHandle, Component.path); |
| 2468 | if (path) |
| 2469 | { path.tiles = []; } |
| 2470 | world.ecs.add(targetHandle, Component.dead, {}); |
| 2471 | silenceDeadPlayer(world.ecs, targetHandle); |
| 2472 | const identity = world.ecs.get(targetHandle, Component.networkIdentity); |
| 2473 | events.push({ |
| 2474 | type: "player-died", |
| 2475 | entityId: targetId, |
| 2476 | attackerId, |
| 2477 | characterId: targetCharacter.characterId, |
| 2478 | sessionId: identity?.sessionId ?? null, |
| 2479 | tileX: to.tileX, |
| 2480 | tileY: to.tileY, |
| 2481 | health: 0, |
| 2482 | maxHealth: health.max |
| 2483 | }); |
| 2484 | } |
| 2485 | const creature = world.ecs.get(targetHandle, Component.creature); |
| 2486 | if (creature && !targetCharacter) |
| 2487 | { events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); } |
| 2488 | } |
| 2489 | return events; |
| 2490 | } |
| 2491 | |
| 2492 | function maybeReflectDamage (world, attackerId, targetId, targetHandle, damage, now, options = {}) |
| 2493 | { |
| 2494 | if (options.noReflect || !(damage > 0) || attackerId == null || attackerId === targetId) |
| 2495 | { return []; } |
| 2496 | const equipment = world.ecs.get(targetHandle, Component.equipment); |
| 2497 | const fraction = damageReflectFraction(equipment); |
| 2498 | if (!(fraction > 0)) |
| 2499 | { return []; } |
| 2500 | const attackerHandle = world.ecs.handleOf(attackerId); |
| 2501 | if (attackerHandle == null) |
| 2502 | { return []; } |
| 2503 | const reflectDamage = Math.max(1, Math.floor(damage * fraction)); |
| 2504 | return applyDamageAndKill(world, targetId, attackerId, reflectDamage, now, { noReflect: true }); |
| 2505 | } |