BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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