BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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