BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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