BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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