BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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