BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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