BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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