BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

editor fixes, spawner additions
timfa Tim Falken · pushed by timfa · 2 months ago
87524d95 History
service.js 43.6 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 } from "../../../shared/definitions/mobs.js";
5import {
6 mobCanFightType,
7 mobCanFight,
8 mobMeleeAttackProfile,
9 mobSkillLevels,
10 mobIsAggressive,
11 mobAggroRangeTiles
12} from "../../../shared/definitions/mobCombat.js";
13import { spellDefinition } from "../../../shared/definitions/spells.js";
14import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
15import {
16 effectiveHitSkillInDarkness,
17 aggroDistanceMultiplier
18} from "../../../shared/combat/darkness.js";
19import {
20 bakedTileLight01,
21 entityLightAtTile,
22 tileCombatLight01,
23 tileIndexLocal
24} from "../../../shared/lighting/combatLight.js";
25import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
26import {
27 effectiveSkillLevel,
28 equipmentBonusesFromSlots
29} from "../../../shared/equipment/stats.js";
30import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
31import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js";
32import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
33import { chunkBoundsAround, findPath } from "../navigation/astar.js";
34import { findPathToNearestGoal } from "../../../shared/navigation/bfs.js";
35import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
36import { rayReaches } from "../../../shared/lighting/raycast.js";
37import { tileToChunk } from "../world/coordinates.js";
38import { stackQuantity } from "../../../shared/items/inventory.js";
39import { addGroundItem, publicGroundItem } from "../items/bags.js";
40import { resolveItemDualTint } from "../../../shared/render/tint.js";
41import { castMobAttackSpell } from "../spells/mobCast.js";
42import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
43import { scheduleSpawnerRespawn } from "../simulation/spawners.js";
44
45export function chebyshev (ax, ay, bx, by)
46{
47 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
48}
49
50export function attackProfileOf (ecs, handle)
51{
52 const creature = ecs.get(handle, Component.creature);
53 const level = creatureLevel(ecs, handle);
54 const equipment = ecs.get(handle, Component.equipment);
55 const weapon = equipment?.slots?.weapon;
56 if (weapon?.itemId != null)
57 {
58 const attack = itemDefinition(weapon.itemId)?.equipment?.attack;
59 if (attack)
60 {
61 const profile = { ...attack };
62 if (creature)
63 { profile.mobAttackSkill = level; }
64 return profile;
65 }
66 }
67 if (creature)
68 {
69 const def = mobDefinition(creature.mobTypeId);
70 if (mobCanFightType(creature.mobTypeId))
71 { return mobMeleeAttackProfile(def, level); }
72 }
73 return { ...UNARMED_ATTACK };
74}
75
76function creatureLevel (ecs, handle)
77{
78 const creature = ecs.get(handle, Component.creature);
79 if (!creature)
80 { return 1; }
81 if (creature.level != null)
82 { return Math.max(1, creature.level | 0 || 1); }
83 const origin = ecs.get(handle, Component.spawnOrigin);
84 if (origin?.level != null)
85 { return Math.max(1, origin.level | 0 || 1); }
86 const def = mobDefinition(creature.mobTypeId);
87 return Math.max(1, def?.attackSkill | 0 || 1);
88}
89
90export function weaponEquipmentKind (ecs, handle)
91{
92 const equipment = ecs.get(handle, Component.equipment);
93 const weapon = equipment?.slots?.weapon;
94 if (!weapon?.itemId)
95 { return null; }
96 return itemDefinition(weapon.itemId)?.equipment?.kind ?? null;
97}
98
99export function ensureMobCombat (ecs, entityId)
100{
101 const handle = ecs.handleOf(entityId);
102 if (handle == null)
103 { return false; }
104 const creature = ecs.get(handle, Component.creature);
105 if (!creature || !mobCanFightType(creature.mobTypeId))
106 { return false; }
107 const def = mobDefinition(creature.mobTypeId);
108 const level = creatureLevel(ecs, handle);
109 if (!ecs.get(handle, Component.combat))
110 { ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
111 if (!ecs.get(handle, Component.skills))
112 { ecs.add(handle, Component.skills, { levels: mobSkillLevels(def, level) }); }
113 return true;
114}
115
116function attackerSkillLevel (skills, profile, skillId)
117{
118 if (profile.mobAttackSkill != null)
119 { return profile.mobAttackSkill; }
120 return skillLevel(skills, skillId);
121}
122
123function defenderSkillLevel (skills, skillId, equipment = null, settings = null)
124{
125 const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots, settings) : {};
126 return effectiveSkillLevel(skills, skillId, bonuses);
127}
128
129function playerCombatLevels (ecs, handle, profile, settings = null)
130{
131 const skills = ecs.get(handle, Component.skills);
132 const equipment = ecs.get(handle, Component.equipment);
133 const bonuses = equipmentBonusesFromSlots(equipment?.slots, settings);
134 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
135 bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0);
136 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
137
138 return {
139 hitLevel: skillLevel(skills, profile.hitSkillId ?? SkillId.unarmed),
140 damageLevel: effectiveSkillLevel(skills, profile.damageSkillId ?? SkillId.strength, bonuses),
141 agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses),
142 defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses)
143 };
144}
145
146export function isUntargetable (ecs, handle)
147{
148 const creature = ecs.get(handle, Component.creature);
149 if (!creature)
150 { return false; }
151 return !!mobDefinition(creature.mobTypeId)?.untargetable;
152}
153
154export function engageTarget (ecs, attackerId, targetId, now = Date.now())
155{
156 const handle = ecs.handleOf(attackerId);
157 if (handle == null)
158 { return false; }
159 let combat = ecs.get(handle, Component.combat);
160 if (!combat)
161 { combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
162 const targetChanged = combat.targetEntityId !== targetId;
163 combat.targetEntityId = targetId;
164 if (targetChanged)
165 {
166 // New engage (or switch): allow an immediate swing; keep cadence if already on this target.
167 combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now);
168 const path = ecs.get(handle, Component.path);
169 if (path)
170 { path.tiles = []; }
171 }
172 return true;
173}
174
175export function clearEngage (ecs, entityId)
176{
177 const handle = ecs.handleOf(entityId);
178 const combat = handle != null ? ecs.get(handle, Component.combat) : null;
179 if (combat)
180 { combat.targetEntityId = null; }
181}
182
183export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)
184{
185 const isClear = world.isClearForRangedAttack
186 ? (x, y) => world.isClearForRangedAttack(x, y)
187 : (x, y) => world.isEnterable(x, y);
188 return rayReaches(fromX, fromY, toX, toY, isClear);
189}
190
191/** Target-tile lighting 0–1 (baked + entity lights + time of day). */
192export function tileLightAt (world, tileX, tileY, now = Date.now())
193{
194 const data = world.chunkData?.(tileToChunk(tileX), tileToChunk(tileY));
195 const index = tileIndexLocal(tileX, tileY);
196 const baked = bakedTileLight01(data?.light, index);
197 const entity = entityLightAtTile(world.ecs, Component, tileX, tileY, now);
198 const worldTime = world.worldTime?.(now);
199 return tileCombatLight01({
200 bakedLight01: baked,
201 entityLight01: entity,
202 worldHour: worldTime?.hour ?? 12,
203 nightDarkness: world.settings?.nightDarkness ?? 0.72
204 });
205}
206
207function arrowStackInOffhand (equipment)
208{
209 const stack = equipment?.slots?.offhand;
210 if (!stack)
211 { return null; }
212 const def = itemDefinition(stack.itemId);
213 if (def?.equipment?.kind !== EquipmentKind.arrowAmmo)
214 { return null; }
215 return stack;
216}
217
218function consumeArrow (ecs, handle)
219{
220 const equipment = ecs.get(handle, Component.equipment);
221 const stack = arrowStackInOffhand(equipment);
222 if (!stack || stackQuantity(stack.quantity) <= 0)
223 { return false; }
224 if (stackQuantity(stack.quantity) <= 1)
225 { equipment.slots.offhand = null; }
226 else
227 { stack.quantity = stackQuantity(stack.quantity) - 1; }
228 return true;
229}
230
231/** Fixed `quantity`, or inclusive `quantityMin`/`quantityMax` range (default 1). */
232function rollDropQuantity (drop)
233{
234 if (drop.quantityMin != null || drop.quantityMax != null)
235 {
236 const min = Math.max(0, Math.floor(Number(drop.quantityMin ?? 1)));
237 const max = Math.max(min, Math.floor(Number(drop.quantityMax ?? min)));
238 return min + Math.floor(Math.random() * (max - min + 1));
239 }
240 return Math.max(1, Math.floor(Number(drop.quantity ?? 1)));
241}
242
243function spawnMobDrops (world, targetHandle, tileX, tileY, now, attackerId = null)
244{
245 const creature = world.ecs.get(targetHandle, Component.creature);
246 if (!creature)
247 { return []; }
248 const def = mobDefinition(creature.mobTypeId);
249 const mobName = entityCombatDisplayName(world.ecs, targetHandle)
250 || def?.displayName
251 || "a creature";
252 let killerName = "someone";
253 if (attackerId != null)
254 {
255 const attackerHandle = world.ecs.handleOf(attackerId);
256 if (attackerHandle != null)
257 { killerName = entityCombatDisplayName(world.ecs, attackerHandle) || "someone"; }
258 }
259 const origin = lootOrigin(mobName, killerName);
260 const events = [];
261 const spawnOrigin = world.ecs.get(targetHandle, Component.spawnOrigin);
262 const dropTable = [
263 ...(def?.drops ?? []),
264 ...(Array.isArray(spawnOrigin?.drops) ? spawnOrigin.drops : [])
265 ];
266 for (const drop of dropTable)
267 {
268 if (Math.random() > (drop.chance ?? 1))
269 { continue; }
270 const quantity = rollDropQuantity(drop);
271 if (quantity <= 0)
272 { continue; }
273 const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
274 const stack = attachOrigins({
275 itemId: drop.itemId,
276 quantity,
277 origins: [{ origin, quantity }]
278 });
279 const item = {
280 groundItemId,
281 tileX,
282 tileY,
283 stack,
284 droppedAt: now,
285 expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000),
286 source: "mob-drop"
287 };
288 addGroundItem(world, item);
289 events.push({
290 type: "ground-item-appear",
291 ...publicGroundItem(item),
292 stack: item.stack,
293 droppedAt: item.droppedAt,
294 source: item.source,
295 expiresAt: item.expiresAt
296 });
297 }
298 return events;
299}
300
301function entityCombatDisplayName (ecs, handle)
302{
303 const appearance = ecs.get(handle, Component.appearance);
304 const fromAppearance = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
305 if (fromAppearance)
306 { return fromAppearance; }
307 const creature = ecs.get(handle, Component.creature);
308 if (creature?.mobTypeId)
309 {
310 const def = mobDefinition(creature.mobTypeId);
311 if (def?.displayName)
312 { return def.displayName; }
313 }
314 return null;
315}
316
317function projectileDualTintFromAttacker (ecs, handle)
318{
319 const equipment = ecs.get(handle, Component.equipment);
320 const stack = arrowStackInOffhand(equipment);
321 if (!stack)
322 { return null; }
323 return resolveItemDualTint(stack, itemDefinition(stack.itemId));
324}
325
326function publicDualTint (dualTint)
327{
328 if (!dualTint)
329 { return null; }
330 return {
331 shaftTint: dualTint.shaft,
332 tipTint: dualTint.tip
333 };
334}
335
336function missProjectileTile (targetTileX, targetTileY, rng = Math.random)
337{
338 const angle = rng() * Math.PI * 2;
339 const dist = rng();
340 return {
341 tileX: Math.round(targetTileX + Math.cos(angle) * dist),
342 tileY: Math.round(targetTileY + Math.sin(angle) * dist)
343 };
344}
345
346/**
347 * Aggressive mobs auto-engage the nearest player character within aggro range
348 * when they have line of sight. Does nothing while already engaged.
349 */
350export function stepAggression (world, now = Date.now())
351{
352 for (const entity of world.ecs.query(Component.creature, Component.position))
353 {
354 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
355 { continue; }
356 const def = mobDefinition(entity.creature.mobTypeId);
357 const origin = world.ecs.get(entity.handle, Component.spawnOrigin);
358 const aggressive = origin
359 ? !!origin.aggressive
360 : mobIsAggressive(def);
361 if (!aggressive || !mobCanFight(def))
362 { continue; }
363 if (world.ecs.has(entity.handle, Component.dead))
364 { continue; }
365 const health = world.ecs.get(entity.handle, Component.health);
366 if (health && health.current <= 0)
367 { continue; }
368 const combat = world.ecs.get(entity.handle, Component.combat);
369 if (combat?.targetEntityId != null)
370 { continue; }
371
372 const range = mobAggroRangeTiles(def);
373 let bestId = null;
374 let bestDist = Infinity;
375 for (const player of world.ecs.query(Component.character, Component.position))
376 {
377 if (world.ecs.has(player.handle, Component.dead))
378 { continue; }
379 const playerHealth = world.ecs.get(player.handle, Component.health);
380 if (playerHealth && playerHealth.current <= 0)
381 { continue; }
382 const dist = chebyshev(
383 entity.position.tileX,
384 entity.position.tileY,
385 player.position.tileX,
386 player.position.tileY
387 );
388 if (dist < 1 || dist > range)
389 { continue; }
390 let effectiveDist = dist;
391 if (dist > 1)
392 {
393 const light = tileLightAt(world, player.position.tileX, player.position.tileY);
394 effectiveDist = dist * aggroDistanceMultiplier(light);
395 }
396 if (effectiveDist > range)
397 { continue; }
398 if (!hasCombatLineOfSight(
399 world,
400 entity.position.tileX,
401 entity.position.tileY,
402 player.position.tileX,
403 player.position.tileY
404 ))
405 { continue; }
406 if (dist < bestDist)
407 {
408 bestDist = dist;
409 bestId = player.entityId;
410 }
411 }
412 if (bestId == null)
413 { continue; }
414 if (!ensureMobCombat(world.ecs, entity.entityId))
415 { continue; }
416 engageTarget(world.ecs, entity.entityId, bestId, now);
417 }
418}
419
420/** Local entity handle or a nearby ghost snapshot for cross-worker combat. */
421export function resolveCombatTarget (world, targetId)
422{
423 const handle = world.ecs.handleOf(targetId);
424 if (handle != null)
425 {
426 const pos = world.ecs.get(handle, Component.position);
427 if (!pos)
428 { return null; }
429 if (isUntargetable(world.ecs, handle))
430 { return null; }
431 return {
432 local: true,
433 handle,
434 pos,
435 health: world.ecs.get(handle, Component.health)
436 };
437 }
438 const ghost = world.ghosts?.get?.(targetId);
439 if (!ghost || ghost.untargetable)
440 { return null; }
441 const health = ghost.health != null
442 ? { current: ghost.health, max: ghost.maxHealth ?? ghost.health }
443 : null;
444 return {
445 local: false,
446 handle: null,
447 pos: { tileX: ghost.tileX, tileY: ghost.tileY },
448 health
449 };
450}
451
452function attackerCombatLevels (ecs, attackerHandle, profile, settings = null)
453{
454 const attackerCharacter = ecs.get(attackerHandle, Component.character);
455 if (attackerCharacter)
456 { return playerCombatLevels(ecs, attackerHandle, profile, settings); }
457 const skills = ecs.get(attackerHandle, Component.skills);
458 return {
459 hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId),
460 damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId),
461 agilityLevel: skillLevel(skills, SkillId.agility),
462 defenceLevel: skillLevel(skills, SkillId.defence)
463 };
464}
465
466export function stepCombat (world, now = Date.now())
467{
468 const events = [];
469 for (const entity of world.ecs.query(Component.combat, Component.position))
470 {
471 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
472 { continue; }
473 const combat = entity.combat;
474 const targetId = combat.targetEntityId;
475 if (targetId == null)
476 { continue; }
477 const target = resolveCombatTarget(world, targetId);
478 if (!target)
479 {
480 combat.targetEntityId = null;
481 continue;
482 }
483 if (target.health && target.health.current <= 0)
484 {
485 combat.targetEntityId = null;
486 continue;
487 }
488
489 const profile = attackProfileOf(world.ecs, entity.handle);
490 const targetPos = target.pos;
491 const isCreature = !!world.ecs.get(entity.handle, Component.creature)
492 && !world.ecs.get(entity.handle, Component.character);
493 const weaponKind = weaponEquipmentKind(world.ecs, entity.handle);
494 const isStaff = weaponKind === EquipmentKind.staff;
495
496 if (profile.mode === "ranged")
497 {
498 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
499 const maxRange = profile.rangeTiles | 0 || COMBAT_RANGE_TILES;
500 const equipment = world.ecs.get(entity.handle, Component.equipment);
501 const hasArrows = isCreature
502 || (arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0);
503 const inRange = dist >= 1 && dist <= maxRange
504 && hasCombatLineOfSight(
505 world,
506 entity.position.tileX,
507 entity.position.tileY,
508 targetPos.tileX,
509 targetPos.tileY
510 );
511 if (!inRange || !hasArrows)
512 {
513 if (inRange && !hasArrows && now >= (combat.nextSwingAt || 0)
514 && world.ecs.get(entity.handle, Component.character))
515 {
516 combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200);
517 events.push({
518 type: "combat-no-arrows",
519 attackerId: entity.entityId,
520 sessionId: world.ecs.get(entity.handle, Component.networkIdentity)?.sessionId ?? null
521 });
522 }
523 queueRangedApproach(world, entity.entityId, entity.handle, entity.position, targetPos, maxRange);
524 continue;
525 }
526 clearCombatApproachPath(world.ecs, entity.handle);
527 if (now < (combat.nextSwingAt || 0))
528 { continue; }
529 combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200);
530 events.push(...resolveRangedShot(world, entity.entityId, targetId, profile, now, targetPos));
531 continue;
532 }
533
534 if (profile.mode !== "melee" && !isStaff)
535 { continue; }
536
537 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
538 const canSwing = !isStaff
539 && dist === 1
540 && world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY);
541 const attackSpells = isCreature ? eligibleMobAttackSpells(world.ecs, entity.handle) : [];
542 const shouldCast = isCreature && attackSpells.length > 0 && (isStaff || !canSwing);
543
544 if (shouldCast)
545 {
546 const inSpellRange = dist >= 1 && dist <= COMBAT_RANGE_TILES
547 && hasCombatLineOfSight(
548 world,
549 entity.position.tileX,
550 entity.position.tileY,
551 targetPos.tileX,
552 targetPos.tileY
553 );
554 if (!inSpellRange)
555 {
556 queueStandInRangeApproach(
557 world,
558 entity.entityId,
559 entity.handle,
560 entity.position,
561 targetPos.tileX,
562 targetPos.tileY,
563 COMBAT_RANGE_TILES,
564 1
565 );
566 continue;
567 }
568 clearCombatApproachPath(world.ecs, entity.handle);
569 if (now < (combat.nextSwingAt || 0))
570 { continue; }
571 const picked = pickMobAttackSpell(attackSpells);
572 if (!picked)
573 {
574 combat.nextSwingAt = now + SPELL_COOLDOWN_MS;
575 continue;
576 }
577 combat.nextSwingAt = now + SPELL_COOLDOWN_MS;
578 events.push(...castMobAttackSpell(world, entity.entityId, targetId, picked.spellId, now));
579 continue;
580 }
581
582 if (!canSwing)
583 {
584 if (isStaff)
585 {
586 queueStandInRangeApproach(
587 world,
588 entity.entityId,
589 entity.handle,
590 entity.position,
591 targetPos.tileX,
592 targetPos.tileY,
593 COMBAT_RANGE_TILES,
594 1
595 );
596 }
597 else
598 { queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos); }
599 continue;
600 }
601 clearCombatApproachPath(world.ecs, entity.handle);
602 const attackerHealth = world.ecs.get(entity.handle, Component.health);
603 if (attackerHealth && attackerHealth.current <= 0)
604 { continue; }
605 if ((combat.nextSwingAt || 0) > now)
606 { continue; }
607
608 combat.nextSwingAt = now + (profile.cooldownMs || 800);
609 events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now));
610 }
611 return events;
612}
613
614function eligibleMobAttackSpells (ecs, handle)
615{
616 const spells = ecs.get(handle, Component.spells);
617 if (!spells?.known?.length)
618 { return []; }
619 const level = creatureLevel(ecs, handle);
620 const chances = spells.castChances ?? {};
621 const out = [];
622 for (const spellId of spells.known)
623 {
624 const def = spellDefinition(spellId);
625 if (!def || def.target !== "entity")
626 { continue; }
627 const minLevel = Math.max(1, def.minMagicLevel | 0 || 1);
628 if (level < minLevel)
629 { continue; }
630 const chance = Math.max(0, Math.min(100, Number(chances[spellId]) || 0)) | 0;
631 if (chance <= 0)
632 { continue; }
633 out.push({ spellId, chance });
634 }
635 return out;
636}
637
638function pickMobAttackSpell (spells)
639{
640 if (!spells.length)
641 { return null; }
642 const pick = spells[Math.floor(Math.random() * spells.length)];
643 if ((Math.random() * 100) >= pick.chance)
644 { return null; }
645 return pick;
646}
647
648function clearCombatApproachPath (ecs, handle)
649{
650 const path = ecs.get(handle, Component.path);
651 if (path?.tiles?.length)
652 { path.tiles = []; }
653}
654
655function combatTileKey (tileX, tileY)
656{
657 return `${tileX},${tileY}`;
658}
659
660/** Tiles claimed by other combatants fighting the same target (position, next step, path goal). */
661function collectCombatAllyReservations (world, entityId, targetEntityId)
662{
663 const reserved = new Set();
664 if (targetEntityId == null)
665 { return reserved; }
666 for (const entity of world.ecs.query(Component.combat, Component.position))
667 {
668 if (entity.entityId === entityId)
669 { continue; }
670 if (entity.combat.targetEntityId !== targetEntityId)
671 { continue; }
672 reserved.add(combatTileKey(entity.position.tileX, entity.position.tileY));
673 const allyPath = world.ecs.get(entity.handle, Component.path);
674 if (!allyPath?.tiles?.length)
675 { continue; }
676 const next = allyPath.tiles[0];
677 if (next)
678 { reserved.add(combatTileKey(next.x, next.y)); }
679 const dest = allyPath.tiles[allyPath.tiles.length - 1];
680 if (dest)
681 { reserved.add(combatTileKey(dest.x, dest.y)); }
682 }
683 return reserved;
684}
685
686function combatGoalPreference (entityId, tileX, tileY)
687{
688 return ((tileX * 73856093) ^ (tileY * 19349663) ^ (entityId * 83492791)) >>> 0;
689}
690
691export function queueMeleeApproach (world, entityId, handle, position, targetPos)
692{
693 if (world.frozen?.has?.(entityId))
694 { return; }
695 let path = world.ecs.get(handle, Component.path);
696 if (!path)
697 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
698
699 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY)
700 ?? true;
701 if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) === 1 && aloneHere)
702 {
703 path.tiles = [];
704 return;
705 }
706
707 const combat = world.ecs.get(handle, Component.combat);
708 const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null);
709 const goal = bestAdjacentGoal(world, entityId, position, targetPos, reserved);
710 if (!goal)
711 {
712 path.tiles = [];
713 return;
714 }
715
716 if (goal.x === position.tileX && goal.y === position.tileY)
717 {
718 path.tiles = [];
719 return;
720 }
721
722 if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved))
723 { return; }
724
725 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
726 const preferVertical = !!world.ecs.get(handle, Component.character);
727 const tiles = findPath(
728 position.tileX,
729 position.tileY,
730 goal.x,
731 goal.y,
732 (x, y) =>
733 {
734 if (x === goal.x && y === goal.y)
735 {
736 return world.isClearStanding?.(entityId, x, y)
737 ?? world.walkableFor(entityId, x, y);
738 }
739 return world.walkableFor(entityId, x, y);
740 },
741 bounds.minX,
742 bounds.minY,
743 bounds.maxX,
744 bounds.maxY,
745 { preferVertical }
746 );
747 if (!tiles.length)
748 {
749 path.tiles = [];
750 return;
751 }
752 path.tiles = tiles;
753 const movement = world.ecs.get(handle, Component.movement);
754 if (movement)
755 { movement.walkCarry = 0; }
756}
757
758/**
759 * Path toward the nearest reachable tile from which `targetTile` is in Chebyshev range with LOS.
760 * Goal is chosen by BFS flood from the actor (shortest walk), not min Chebyshev (which biases top-left).
761 * @param {number} minStandDist Minimum stand-off from target (0 = may stand on target tile).
762 */
763export function queueStandInRangeApproach (
764 world,
765 entityId,
766 handle,
767 position,
768 targetTileX,
769 targetTileY,
770 maxRange,
771 minStandDist = 1
772)
773{
774 if (world.frozen?.has?.(entityId))
775 { return; }
776 let path = world.ecs.get(handle, Component.path);
777 if (!path)
778 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
779
780 const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY);
781 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true;
782 if (
783 distToTarget <= maxRange
784 && distToTarget >= minStandDist
785 && aloneHere
786 && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY)
787 )
788 {
789 path.tiles = [];
790 return;
791 }
792
793 const combat = world.ecs.get(handle, Component.combat);
794 const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null);
795 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
796 const isWalkable = (x, y) => world.walkableFor(entityId, x, y);
797 const isGoal = (x, y) =>
798 {
799 const standOff = chebyshev(x, y, targetTileX, targetTileY);
800 if (standOff < minStandDist || standOff > maxRange)
801 { return false; }
802 if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y)))
803 { return false; }
804 const key = combatTileKey(x, y);
805 if (reserved.has(key) && !(x === position.tileX && y === position.tileY))
806 { return false; }
807 return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY);
808 };
809
810 const tiles = findPathToNearestGoal(
811 position.tileX,
812 position.tileY,
813 isGoal,
814 isWalkable,
815 bounds.minX,
816 bounds.minY,
817 bounds.maxX,
818 bounds.maxY
819 );
820 if (!tiles.length)
821 {
822 path.tiles = [];
823 return;
824 }
825 const bestGoal = tiles[tiles.length - 1];
826 if (path.tiles?.length && !standInRangePathStale(
827 world,
828 entityId,
829 path,
830 bestGoal,
831 targetTileX,
832 targetTileY,
833 maxRange,
834 minStandDist,
835 reserved,
836 position
837 ))
838 { return; }
839 path.tiles = tiles;
840 const movement = world.ecs.get(handle, Component.movement);
841 if (movement)
842 { movement.walkCarry = 0; }
843}
844
845function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange)
846{
847 queueStandInRangeApproach(
848 world,
849 entityId,
850 handle,
851 position,
852 targetPos.tileX,
853 targetPos.tileY,
854 maxRange,
855 1
856 );
857}
858
859export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos)
860{
861 const events = [];
862 const attackerHandle = world.ecs.handleOf(attackerId);
863 if (attackerHandle == null)
864 { return events; }
865 const from = world.ecs.get(attackerHandle, Component.position);
866 if (!from || !targetPos)
867 { return events; }
868 const isCreature = !!world.ecs.get(attackerHandle, Component.creature)
869 && !world.ecs.get(attackerHandle, Component.character);
870 if (!isCreature && !consumeArrow(world.ecs, attackerHandle))
871 { return events; }
872
873 const snapshot = { tileX: targetPos.tileX, tileY: targetPos.tileY };
874 const target = resolveCombatTarget(world, targetId);
875 if (!target)
876 { return events; }
877
878 if (!target.local)
879 {
880 events.push({
881 type: "remote-ranged-resolve",
882 attackerId,
883 targetId,
884 profile,
885 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings),
886 attackerIsPlayer: !!world.ecs.get(attackerHandle, Component.character),
887 now,
888 tileX: snapshot.tileX,
889 tileY: snapshot.tileY,
890 fromTileX: from.tileX,
891 fromTileY: from.tileY,
892 ...(publicDualTint(projectileDualTintFromAttacker(world.ecs, attackerHandle)) ?? {})
893 });
894 return events;
895 }
896
897 const hitEvents = applyLocalMeleeHit(
898 world,
899 attackerId,
900 targetId,
901 attackerHandle,
902 target.handle,
903 profile,
904 now,
905 snapshot
906 );
907 const outcome = hitEvents.find((e) =>
908 e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block");
909 let endX = snapshot.tileX;
910 let endY = snapshot.tileY;
911 if (outcome?.type === "combat-miss")
912 {
913 const miss = missProjectileTile(snapshot.tileX, snapshot.tileY);
914 endX = miss.tileX;
915 endY = miss.tileY;
916 }
917 else
918 {
919 const currentPos = world.ecs.get(target.handle, Component.position);
920 if (currentPos)
921 {
922 endX = currentPos.tileX;
923 endY = currentPos.tileY;
924 }
925 }
926 events.push({
927 type: "combat-projectile",
928 attackerId,
929 targetId,
930 fromTileX: from.tileX,
931 fromTileY: from.tileY,
932 tileX: endX,
933 tileY: endY,
934 durationMs: RANGED_PROJECTILE_MS,
935 trackTarget: outcome?.type !== "combat-miss",
936 ...(publicDualTint(projectileDualTintFromAttacker(world.ecs, attackerHandle)) ?? {})
937 });
938 return events.concat(hitEvents);
939}
940
941function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist, reserved, position)
942{
943 const dest = path.tiles[path.tiles.length - 1];
944 if (dest.x !== goal.x || dest.y !== goal.y)
945 { return true; }
946 const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY);
947 if (standOff < minStandDist || standOff > maxRange)
948 { return true; }
949 if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY))
950 { return true; }
951 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
952 { return true; }
953 const destKey = combatTileKey(dest.x, dest.y);
954 if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY))
955 { return true; }
956 const next = path.tiles[0];
957 if (!next)
958 { return true; }
959 if (!world.walkableFor(entityId, next.x, next.y))
960 { return true; }
961 return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true);
962}
963
964function meleePathStale (world, entityId, position, targetPos, path, goal, reserved)
965{
966 const dest = path.tiles[path.tiles.length - 1];
967 if (dest.x !== goal.x || dest.y !== goal.y)
968 { return true; }
969 if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1)
970 { return true; }
971 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
972 { return true; }
973 const destKey = combatTileKey(dest.x, dest.y);
974 if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY))
975 { return true; }
976 const next = path.tiles[0];
977 if (!next)
978 { return true; }
979 if (!world.walkableFor(entityId, next.x, next.y))
980 { return true; }
981 return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true);
982}
983
984function bestAdjacentGoal (world, entityId, position, targetPos, reserved = null)
985{
986 const dirs = [
987 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
988 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
989 ];
990 let best = null;
991 let bestDist = Infinity;
992 let bestPref = Infinity;
993 for (const dir of dirs)
994 {
995 const x = targetPos.tileX + dir.x;
996 const y = targetPos.tileY + dir.y;
997 const isHere = x === position.tileX && y === position.tileY;
998 const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true;
999 const key = combatTileKey(x, y);
1000 if (reserved?.has(key) && !(isHere && aloneHere))
1001 { continue; }
1002 const clear = world.isClearStanding?.(entityId, x, y)
1003 ?? world.walkableFor(entityId, x, y);
1004 if (!clear && !isHere)
1005 { continue; }
1006 if (isHere && !aloneHere)
1007 { continue; }
1008 const dist = chebyshev(position.tileX, position.tileY, x, y);
1009 const pref = combatGoalPreference(entityId, x, y);
1010 if (dist < bestDist || (dist === bestDist && pref < bestPref))
1011 {
1012 bestDist = dist;
1013 bestPref = pref;
1014 best = { x, y };
1015 }
1016 }
1017 return best;
1018}
1019
1020export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now())
1021{
1022 const events = [];
1023 const attackerHandle = world.ecs.handleOf(attackerId);
1024 if (attackerHandle == null)
1025 { return events; }
1026 const target = resolveCombatTarget(world, targetId);
1027 if (!target)
1028 { return events; }
1029 const from = world.ecs.get(attackerHandle, Component.position);
1030 const to = target.pos;
1031 if (!from || !to)
1032 { return events; }
1033 if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1)
1034 { return events; }
1035 if (world.isClearStanding && !world.isClearStanding(attackerId, from.tileX, from.tileY))
1036 { return events; }
1037
1038 events.push({
1039 type: "combat-swing",
1040 attackerId,
1041 targetId,
1042 tileX: to.tileX,
1043 tileY: to.tileY,
1044 fromTileX: from.tileX,
1045 fromTileY: from.tileY
1046 });
1047
1048 if (!target.local)
1049 {
1050 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
1051 events.push({
1052 type: "remote-melee-resolve",
1053 attackerId,
1054 targetId,
1055 profile,
1056 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings),
1057 attackerIsPlayer: !!attackerCharacter,
1058 now,
1059 tileX: to.tileX,
1060 tileY: to.tileY
1061 });
1062 return events;
1063 }
1064
1065 return events.concat(applyLocalMeleeHit(
1066 world,
1067 attackerId,
1068 targetId,
1069 attackerHandle,
1070 target.handle,
1071 profile,
1072 now,
1073 to
1074 ));
1075}
1076
1077/** Authoritative ranged hit when the defender lives on this worker. */
1078export function applyRemoteRangedShot (world, payload)
1079{
1080 const targetHandle = world.ecs.handleOf(payload.targetId);
1081 if (targetHandle == null)
1082 { return { events: [], forwards: [] }; }
1083 const snapshot = {
1084 tileX: payload.tileX,
1085 tileY: payload.tileY
1086 };
1087
1088 const hitEvents = applyLocalMeleeHit(
1089 world,
1090 payload.attackerId,
1091 payload.targetId,
1092 null,
1093 targetHandle,
1094 payload.profile,
1095 payload.now ?? Date.now(),
1096 snapshot,
1097 payload.attackerLevels,
1098 payload.attackerIsPlayer
1099 );
1100
1101 const outcome = hitEvents.find((e) =>
1102 e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block");
1103 let endX = snapshot.tileX;
1104 let endY = snapshot.tileY;
1105 if (outcome?.type === "combat-miss")
1106 {
1107 const miss = missProjectileTile(snapshot.tileX, snapshot.tileY);
1108 endX = miss.tileX;
1109 endY = miss.tileY;
1110 }
1111 else
1112 {
1113 const currentPos = world.ecs.get(targetHandle, Component.position);
1114 if (currentPos)
1115 {
1116 endX = currentPos.tileX;
1117 endY = currentPos.tileY;
1118 }
1119 }
1120
1121 const events = [{
1122 type: "combat-projectile",
1123 attackerId: payload.attackerId,
1124 targetId: payload.targetId,
1125 fromTileX: payload.fromTileX,
1126 fromTileY: payload.fromTileY,
1127 tileX: endX,
1128 tileY: endY,
1129 durationMs: RANGED_PROJECTILE_MS,
1130 trackTarget: outcome?.type !== "combat-miss",
1131 shaftTint: payload.shaftTint ?? null,
1132 tipTint: payload.tipTint ?? null
1133 }, ...hitEvents];
1134
1135 const forwards = [];
1136 const hitEvent = hitEvents.find((event) => event.type === "combat-hit");
1137 if (hitEvent && payload.attackerIsPlayer)
1138 {
1139 forwards.push({
1140 type: "forward-combat-xp",
1141 entityId: payload.attackerId,
1142 profile: payload.profile,
1143 damage: hitEvent.damage
1144 });
1145 }
1146 return { events, forwards };
1147}
1148
1149/** Authoritative hit resolution when the defender lives on this worker. */
1150export function applyRemoteMeleeSwing (world, payload)
1151{
1152 const targetHandle = world.ecs.handleOf(payload.targetId);
1153 if (targetHandle == null)
1154 { return { events: [], forwards: [] }; }
1155 const to = world.ecs.get(targetHandle, Component.position);
1156 if (!to)
1157 { return { events: [], forwards: [] }; }
1158
1159 const events = applyLocalMeleeHit(
1160 world,
1161 payload.attackerId,
1162 payload.targetId,
1163 null,
1164 targetHandle,
1165 payload.profile,
1166 payload.now ?? Date.now(),
1167 to,
1168 payload.attackerLevels,
1169 payload.attackerIsPlayer
1170 );
1171
1172 const forwards = [];
1173 const hitEvent = events.find((event) => event.type === "combat-hit");
1174 if (hitEvent && payload.attackerIsPlayer)
1175 {
1176 forwards.push({
1177 type: "forward-combat-xp",
1178 entityId: payload.attackerId,
1179 profile: payload.profile,
1180 damage: hitEvent.damage
1181 });
1182 }
1183 return { events, forwards };
1184}
1185
1186function applyLocalMeleeHit (
1187 world,
1188 attackerId,
1189 targetId,
1190 attackerHandle,
1191 targetHandle,
1192 profile,
1193 now,
1194 to,
1195 attackerLevelsOverride = null,
1196 attackerIsPlayerOverride = null
1197)
1198{
1199 const events = [];
1200 if (targetHandle == null)
1201 { return events; }
1202
1203 const attackerIsPlayer = attackerIsPlayerOverride != null
1204 ? !!attackerIsPlayerOverride
1205 : (attackerHandle != null ? !!world.ecs.get(attackerHandle, Component.character) : null);
1206
1207 // Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.
1208 if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId))
1209 { engageTarget(world.ecs, targetId, attackerId, now); }
1210 if (attackerIsPlayer === false)
1211 {
1212 const targetCharacter = world.ecs.get(targetHandle, Component.character);
1213 if (targetCharacter)
1214 {
1215 engageTarget(world.ecs, targetId, attackerId, now);
1216 const follow = world.ecs.get(targetHandle, Component.follow);
1217 if (follow)
1218 {
1219 follow.targetEntityId = null;
1220 follow.trail = [];
1221 }
1222 if (world.ecs.has(targetHandle, Component.gather))
1223 { world.ecs.remove(targetHandle, Component.gather); }
1224 }
1225 }
1226
1227 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
1228 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
1229 const attackerLevels = attackerLevelsOverride
1230 ?? (attackerHandle != null
1231 ? attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings)
1232 : null);
1233 if (!attackerLevels)
1234 { return events; }
1235
1236 const agilityLevel = defenderSkillLevel(
1237 defenderSkills,
1238 SkillId.agility,
1239 defenderEquipment,
1240 world.settings
1241 );
1242 const defenceLevel = defenderSkillLevel(
1243 defenderSkills,
1244 SkillId.defence,
1245 defenderEquipment,
1246 world.settings
1247 );
1248
1249 const resolved = resolvePhysicalAttack({
1250 hitSkillLevel: effectiveHitSkillInDarkness(
1251 attackerLevels.hitLevel,
1252 tileLightAt(world, to.tileX, to.tileY)
1253 ),
1254 agilitySkillLevel: agilityLevel,
1255 damageSkillLevel: attackerLevels.damageLevel,
1256 defenceSkillLevel: defenceLevel
1257 });
1258
1259 if (resolved.outcome === "miss")
1260 {
1261 events.push({
1262 type: "combat-miss",
1263 attackerId,
1264 targetId,
1265 tileX: to.tileX,
1266 tileY: to.tileY
1267 });
1268 const dodgeXp = awardCombatAvoidanceXp(
1269 world.ecs,
1270 targetHandle,
1271 SkillId.agility,
1272 resolved.damageRoll
1273 );
1274 if (dodgeXp)
1275 {
1276 events.push({
1277 type: "skills-updated",
1278 entityId: targetId,
1279 characterId: dodgeXp.characterId,
1280 skills: dodgeXp.view,
1281 stored: dodgeXp.stored,
1282 levelUps: dodgeXp.levelUps ?? []
1283 });
1284 }
1285 return events;
1286 }
1287
1288 if (resolved.outcome === "block")
1289 {
1290 events.push({
1291 type: "combat-block",
1292 attackerId,
1293 targetId,
1294 tileX: to.tileX,
1295 tileY: to.tileY
1296 });
1297 const blockXp = awardCombatAvoidanceXp(
1298 world.ecs,
1299 targetHandle,
1300 SkillId.defence,
1301 resolved.damageRoll
1302 );
1303 if (blockXp)
1304 {
1305 events.push({
1306 type: "skills-updated",
1307 entityId: targetId,
1308 characterId: blockXp.characterId,
1309 skills: blockXp.view,
1310 stored: blockXp.stored,
1311 levelUps: blockXp.levelUps ?? []
1312 });
1313 }
1314 return events;
1315 }
1316
1317 const damage = resolved.damage;
1318 const targetCharacter = world.ecs.get(targetHandle, Component.character);
1319 if (targetCharacter)
1320 { syncPlayerHealth(world.ecs, targetHandle); }
1321 const health = world.ecs.get(targetHandle, Component.health);
1322 if (health)
1323 {
1324 health.current = Math.max(0, (health.current | 0) - damage);
1325 }
1326 events.push({
1327 type: "combat-hit",
1328 attackerId,
1329 targetId,
1330 damage,
1331 tileX: to.tileX,
1332 tileY: to.tileY,
1333 health: health?.current ?? 0,
1334 maxHealth: health?.max ?? 0
1335 });
1336
1337 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
1338 if (healthXp)
1339 {
1340 events.push({
1341 type: "skills-updated",
1342 entityId: targetId,
1343 characterId: healthXp.characterId,
1344 skills: healthXp.view,
1345 stored: healthXp.stored,
1346 levelUps: healthXp.levelUps ?? []
1347 });
1348 if (health)
1349 {
1350 const hitEvent = events[events.length - 2];
1351 if (hitEvent?.type === "combat-hit")
1352 {
1353 hitEvent.health = health.current;
1354 hitEvent.maxHealth = health.max;
1355 }
1356 }
1357 }
1358
1359 if (attackerHandle != null)
1360 {
1361 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
1362 if (attackerCharacter)
1363 {
1364 const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile, damage);
1365 if (xpAward)
1366 {
1367 events.push({
1368 type: "skills-updated",
1369 entityId: attackerId,
1370 characterId: attackerCharacter.characterId,
1371 skills: xpAward.view,
1372 stored: xpAward.stored,
1373 levelUps: xpAward.levelUps ?? []
1374 });
1375 }
1376 }
1377 }
1378
1379 if (health && health.current <= 0)
1380 {
1381 clearEngage(world.ecs, attackerId);
1382 clearEngage(world.ecs, targetId);
1383 for (const entity of world.ecs.query(Component.combat))
1384 {
1385 if (entity.combat.targetEntityId === targetId)
1386 { entity.combat.targetEntityId = null; }
1387 }
1388 if (targetCharacter && !world.ecs.has(targetHandle, Component.dead))
1389 {
1390 const path = world.ecs.get(targetHandle, Component.path);
1391 if (path)
1392 { path.tiles = []; }
1393 const follow = world.ecs.get(targetHandle, Component.follow);
1394 if (follow)
1395 {
1396 follow.targetEntityId = null;
1397 follow.trail = [];
1398 }
1399 world.ecs.add(targetHandle, Component.dead, {});
1400 const identity = world.ecs.get(targetHandle, Component.networkIdentity);
1401 events.push({
1402 type: "player-died",
1403 entityId: targetId,
1404 attackerId,
1405 characterId: targetCharacter.characterId,
1406 sessionId: identity?.sessionId ?? null,
1407 tileX: to.tileX,
1408 tileY: to.tileY,
1409 health: 0,
1410 maxHealth: health.max
1411 });
1412 }
1413 const creature = world.ecs.get(targetHandle, Component.creature);
1414 if (creature && !world.ecs.get(targetHandle, Component.character))
1415 {
1416 events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now));
1417 }
1418 }
1419 return events;
1420}
1421
1422/**
1423 * Drops, despawn, and `mob-killed` for bounty / town-guard reaction.
1424 * Shared by melee and spell kill paths.
1425 */
1426export function finalizeMobKill (world, attackerId, targetId, targetHandle, tileX, tileY, now)
1427{
1428 const events = [];
1429 const handle = targetHandle ?? world.ecs.handleOf(targetId);
1430 if (handle == null)
1431 { return events; }
1432 const creature = world.ecs.get(handle, Component.creature);
1433 const origin = world.ecs.get(handle, Component.spawnOrigin);
1434 const appearance = world.ecs.get(handle, Component.appearance);
1435 events.push(...spawnMobDrops(world, handle, tileX, tileY, now, attackerId));
1436 events.push({
1437 type: "mob-killed",
1438 entityId: targetId,
1439 attackerId,
1440 mobTypeId: creature?.mobTypeId ?? null,
1441 level: creature?.level ?? origin?.level ?? 1,
1442 bounty: Math.max(0, origin?.bounty | 0 || 0),
1443 spawnerId: origin?.spawnerId ?? null,
1444 originTileX: origin?.originTileX ?? tileX,
1445 originTileY: origin?.originTileY ?? tileY,
1446 wanderRangeTiles: origin?.wanderRangeTiles ?? 0,
1447 townGuard: !!origin?.townGuard,
1448 displayName: appearance?.firstName ?? null,
1449 tileX,
1450 tileY
1451 });
1452 if (origin?.spawnerId)
1453 {
1454 scheduleSpawnerRespawn(
1455 world,
1456 origin.spawnerId,
1457 origin.respawnDelaySeconds ?? 0,
1458 now
1459 );
1460 }
1461 const view = world.destroyEntity?.(targetId) ?? null;
1462 if (view)
1463 {
1464 events.push({
1465 type: "entity-despawn",
1466 entityId: targetId,
1467 tileX: view.tileX,
1468 tileY: view.tileY
1469 });
1470 }
1471 return events;
1472}
1473
1474/** Apply HP loss and shared death/loot side-effects (used by spell impacts). */
1475export function applyDamageAndKill (world, attackerId, targetId, damage, now = Date.now())
1476{
1477 const events = [];
1478 const targetHandle = world.ecs.handleOf(targetId);
1479 if (targetHandle == null)
1480 { return events; }
1481 const to = world.ecs.get(targetHandle, Component.position);
1482 if (!to)
1483 { return events; }
1484 const health = world.ecs.get(targetHandle, Component.health);
1485 if (health)
1486 { health.current = Math.max(0, (health.current | 0) - damage); }
1487 events.push({
1488 type: "combat-hit",
1489 attackerId,
1490 targetId,
1491 damage,
1492 tileX: to.tileX,
1493 tileY: to.tileY,
1494 health: health?.current ?? 0,
1495 maxHealth: health?.max ?? 0
1496 });
1497
1498 const attackerHandle = world.ecs.handleOf(attackerId);
1499 if (attackerHandle != null && ensureMobCombat(world.ecs, targetId))
1500 {
1501 const targetCombat = world.ecs.get(targetHandle, Component.combat);
1502 if (targetCombat && targetCombat.targetEntityId == null)
1503 { engageTarget(world.ecs, targetId, attackerId, now); }
1504 }
1505 if (attackerHandle != null && world.ecs.get(targetHandle, Component.character))
1506 {
1507 const attackerCreature = world.ecs.get(attackerHandle, Component.creature);
1508 if (attackerCreature)
1509 {
1510 engageTarget(world.ecs, targetId, attackerId, now);
1511 }
1512 }
1513
1514 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
1515 if (healthXp)
1516 {
1517 events.push({
1518 type: "skills-updated",
1519 entityId: targetId,
1520 characterId: healthXp.characterId,
1521 skills: healthXp.view,
1522 stored: healthXp.stored,
1523 levelUps: healthXp.levelUps ?? []
1524 });
1525 }
1526
1527 if (health && health.current <= 0)
1528 {
1529 clearEngage(world.ecs, attackerId);
1530 clearEngage(world.ecs, targetId);
1531 for (const entity of world.ecs.query(Component.combat))
1532 {
1533 if (entity.combat.targetEntityId === targetId)
1534 { entity.combat.targetEntityId = null; }
1535 }
1536 const targetCharacter = world.ecs.get(targetHandle, Component.character);
1537 if (targetCharacter && !world.ecs.has(targetHandle, Component.dead))
1538 {
1539 const path = world.ecs.get(targetHandle, Component.path);
1540 if (path)
1541 { path.tiles = []; }
1542 world.ecs.add(targetHandle, Component.dead, {});
1543 const identity = world.ecs.get(targetHandle, Component.networkIdentity);
1544 events.push({
1545 type: "player-died",
1546 entityId: targetId,
1547 attackerId,
1548 characterId: targetCharacter.characterId,
1549 sessionId: identity?.sessionId ?? null,
1550 tileX: to.tileX,
1551 tileY: to.tileY,
1552 health: 0,
1553 maxHealth: health.max
1554 });
1555 }
1556 const creature = world.ecs.get(targetHandle, Component.creature);
1557 if (creature && !targetCharacter)
1558 { events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); }
1559 }
1560 return events;
1561}