BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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