BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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