BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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