BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

service.js 31.6 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { itemDefinition } from "../../../shared/definitions/items.js";
3import { mobDefinition } from "../../../shared/definitions/mobs.js";
4import {
5 mobCanFightType,
6 mobMeleeAttackProfile,
7 mobSkillLevels,
8 mobIsAggressive,
9 mobAggroRangeTiles
10} from "../../../shared/definitions/mobCombat.js";
11import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
12import {
13 effectiveHitSkillInDarkness,
14 aggroDistanceMultiplier
15} from "../../../shared/combat/darkness.js";
16import {
17 bakedTileLight01,
18 entityLightAtTile,
19 tileCombatLight01,
20 tileIndexLocal
21} from "../../../shared/lighting/combatLight.js";
22import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
23import {
24 effectiveSkillLevel,
25 equipmentBonusesFromSlots
26} from "../../../shared/equipment/stats.js";
27import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
28import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS } from "../../../shared/spells/constants.js";
29import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
30import { chunkBoundsAround, findPath } from "../navigation/astar.js";
31import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
32import { rayReaches } from "../../../shared/lighting/raycast.js";
33import { tileToChunk } from "../world/coordinates.js";
34import { stackQuantity } from "../../../shared/items/inventory.js";
35import { addGroundItem, publicGroundItem } from "../items/bags.js";
36import { resolveItemDualTint } from "../../../shared/render/tint.js";
37
38export function chebyshev (ax, ay, bx, by)
39{
40 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
41}
42
43export function attackProfileOf (ecs, handle)
44{
45 const equipment = ecs.get(handle, Component.equipment);
46 const weapon = equipment?.slots?.weapon;
47 if (weapon?.itemId != null)
48 {
49 const attack = itemDefinition(weapon.itemId)?.equipment?.attack;
50 if (attack)
51 { return { ...attack }; }
52 }
53 const creature = ecs.get(handle, Component.creature);
54 if (creature)
55 {
56 const def = mobDefinition(creature.mobTypeId);
57 if (mobCanFightType(creature.mobTypeId))
58 { return mobMeleeAttackProfile(def); }
59 }
60 return { ...UNARMED_ATTACK };
61}
62
63export function ensureMobCombat (ecs, entityId)
64{
65 const handle = ecs.handleOf(entityId);
66 if (handle == null)
67 { return false; }
68 const creature = ecs.get(handle, Component.creature);
69 if (!creature || !mobCanFightType(creature.mobTypeId))
70 { return false; }
71 const def = mobDefinition(creature.mobTypeId);
72 if (!ecs.get(handle, Component.combat))
73 { ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
74 if (!ecs.get(handle, Component.skills))
75 { ecs.add(handle, Component.skills, { levels: mobSkillLevels(def) }); }
76 return true;
77}
78
79function attackerSkillLevel (skills, profile, skillId)
80{
81 if (profile.mobAttackSkill != null)
82 { return profile.mobAttackSkill; }
83 return skillLevel(skills, skillId);
84}
85
86function defenderSkillLevel (skills, skillId, equipment = null)
87{
88 const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots) : {};
89 return effectiveSkillLevel(skills, skillId, bonuses);
90}
91
92function playerCombatLevels (ecs, handle, profile)
93{
94 const skills = ecs.get(handle, Component.skills);
95 const equipment = ecs.get(handle, Component.equipment);
96 const bonuses = equipmentBonusesFromSlots(equipment?.slots);
97 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
98 bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0);
99 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
100
101 return {
102 hitLevel: skillLevel(skills, profile.hitSkillId ?? SkillId.unarmed),
103 damageLevel: effectiveSkillLevel(skills, profile.damageSkillId ?? SkillId.strength, bonuses),
104 agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses),
105 defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses)
106 };
107}
108
109export function isUntargetable (ecs, handle)
110{
111 const creature = ecs.get(handle, Component.creature);
112 if (!creature)
113 { return false; }
114 return !!mobDefinition(creature.mobTypeId)?.untargetable;
115}
116
117export function engageTarget (ecs, attackerId, targetId, now = Date.now())
118{
119 const handle = ecs.handleOf(attackerId);
120 if (handle == null)
121 { return false; }
122 let combat = ecs.get(handle, Component.combat);
123 if (!combat)
124 { combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
125 const targetChanged = combat.targetEntityId !== targetId;
126 combat.targetEntityId = targetId;
127 if (targetChanged)
128 {
129 // New engage (or switch): allow an immediate swing; keep cadence if already on this target.
130 combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now);
131 const path = ecs.get(handle, Component.path);
132 if (path)
133 { path.tiles = []; }
134 }
135 return true;
136}
137
138export function clearEngage (ecs, entityId)
139{
140 const handle = ecs.handleOf(entityId);
141 const combat = handle != null ? ecs.get(handle, Component.combat) : null;
142 if (combat)
143 { combat.targetEntityId = null; }
144}
145
146export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)
147{
148 const isClear = world.isClearForRangedAttack
149 ? (x, y) => world.isClearForRangedAttack(x, y)
150 : (x, y) => world.isEnterable(x, y);
151 return rayReaches(fromX, fromY, toX, toY, isClear);
152}
153
154/** Target-tile lighting 0–1 (baked + entity lights + time of day). */
155export function tileLightAt (world, tileX, tileY, now = Date.now())
156{
157 const data = world.chunkData?.(tileToChunk(tileX), tileToChunk(tileY));
158 const index = tileIndexLocal(tileX, tileY);
159 const baked = bakedTileLight01(data?.light, index);
160 const entity = entityLightAtTile(world.ecs, Component, tileX, tileY, now);
161 const worldTime = world.worldTime?.(now);
162 return tileCombatLight01({
163 bakedLight01: baked,
164 entityLight01: entity,
165 worldHour: worldTime?.hour ?? 12,
166 nightDarkness: world.settings?.nightDarkness ?? 0.72
167 });
168}
169
170function arrowStackInOffhand (equipment)
171{
172 const stack = equipment?.slots?.offhand;
173 if (!stack)
174 { return null; }
175 const def = itemDefinition(stack.itemId);
176 if (def?.equipment?.kind !== EquipmentKind.arrowAmmo)
177 { return null; }
178 return stack;
179}
180
181function consumeArrow (ecs, handle)
182{
183 const equipment = ecs.get(handle, Component.equipment);
184 const stack = arrowStackInOffhand(equipment);
185 if (!stack || stackQuantity(stack.quantity) <= 0)
186 { return false; }
187 if (stackQuantity(stack.quantity) <= 1)
188 { equipment.slots.offhand = null; }
189 else
190 { stack.quantity = stackQuantity(stack.quantity) - 1; }
191 return true;
192}
193
194function spawnMobDrops (world, targetHandle, tileX, tileY, now)
195{
196 const creature = world.ecs.get(targetHandle, Component.creature);
197 if (!creature)
198 { return []; }
199 const def = mobDefinition(creature.mobTypeId);
200 const events = [];
201 for (const drop of def?.drops ?? [])
202 {
203 if (Math.random() > (drop.chance ?? 1))
204 { continue; }
205 const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
206 const item = {
207 groundItemId,
208 tileX,
209 tileY,
210 stack: { itemId: drop.itemId, quantity: drop.quantity ?? 1 },
211 droppedAt: now,
212 expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000),
213 source: "mob-drop"
214 };
215 addGroundItem(world, item);
216 events.push({
217 type: "ground-item-appear",
218 ...publicGroundItem(item),
219 stack: item.stack,
220 droppedAt: item.droppedAt,
221 source: item.source,
222 expiresAt: item.expiresAt
223 });
224 }
225 return events;
226}
227
228function projectileDualTintFromAttacker (ecs, handle)
229{
230 const equipment = ecs.get(handle, Component.equipment);
231 const stack = arrowStackInOffhand(equipment);
232 if (!stack)
233 { return null; }
234 return resolveItemDualTint(stack, itemDefinition(stack.itemId));
235}
236
237function publicDualTint (dualTint)
238{
239 if (!dualTint)
240 { return null; }
241 return {
242 shaftTint: dualTint.shaft,
243 tipTint: dualTint.tip
244 };
245}
246
247function missProjectileTile (targetTileX, targetTileY, rng = Math.random)
248{
249 const angle = rng() * Math.PI * 2;
250 const dist = rng();
251 return {
252 tileX: Math.round(targetTileX + Math.cos(angle) * dist),
253 tileY: Math.round(targetTileY + Math.sin(angle) * dist)
254 };
255}
256
257/**
258 * Aggressive mobs auto-engage the nearest player character within aggro range
259 * when they have line of sight. Does nothing while already engaged.
260 */
261export function stepAggression (world, now = Date.now())
262{
263 for (const entity of world.ecs.query(Component.creature, Component.position))
264 {
265 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
266 { continue; }
267 const def = mobDefinition(entity.creature.mobTypeId);
268 if (!mobIsAggressive(def))
269 { continue; }
270 if (world.ecs.has(entity.handle, Component.dead))
271 { continue; }
272 const health = world.ecs.get(entity.handle, Component.health);
273 if (health && health.current <= 0)
274 { continue; }
275 const combat = world.ecs.get(entity.handle, Component.combat);
276 if (combat?.targetEntityId != null)
277 { continue; }
278
279 const range = mobAggroRangeTiles(def);
280 let bestId = null;
281 let bestDist = Infinity;
282 for (const player of world.ecs.query(Component.character, Component.position))
283 {
284 if (world.ecs.has(player.handle, Component.dead))
285 { continue; }
286 const playerHealth = world.ecs.get(player.handle, Component.health);
287 if (playerHealth && playerHealth.current <= 0)
288 { continue; }
289 const dist = chebyshev(
290 entity.position.tileX,
291 entity.position.tileY,
292 player.position.tileX,
293 player.position.tileY
294 );
295 if (dist < 1 || dist > range)
296 { continue; }
297 let effectiveDist = dist;
298 if (dist > 1)
299 {
300 const light = tileLightAt(world, player.position.tileX, player.position.tileY);
301 effectiveDist = dist * aggroDistanceMultiplier(light);
302 }
303 if (effectiveDist > range)
304 { continue; }
305 if (!hasCombatLineOfSight(
306 world,
307 entity.position.tileX,
308 entity.position.tileY,
309 player.position.tileX,
310 player.position.tileY
311 ))
312 { continue; }
313 if (dist < bestDist)
314 {
315 bestDist = dist;
316 bestId = player.entityId;
317 }
318 }
319 if (bestId == null)
320 { continue; }
321 if (!ensureMobCombat(world.ecs, entity.entityId))
322 { continue; }
323 engageTarget(world.ecs, entity.entityId, bestId, now);
324 }
325}
326
327/** Local entity handle or a nearby ghost snapshot for cross-worker combat. */
328export function resolveCombatTarget (world, targetId)
329{
330 const handle = world.ecs.handleOf(targetId);
331 if (handle != null)
332 {
333 const pos = world.ecs.get(handle, Component.position);
334 if (!pos)
335 { return null; }
336 if (isUntargetable(world.ecs, handle))
337 { return null; }
338 return {
339 local: true,
340 handle,
341 pos,
342 health: world.ecs.get(handle, Component.health)
343 };
344 }
345 const ghost = world.ghosts?.get?.(targetId);
346 if (!ghost || ghost.untargetable)
347 { return null; }
348 const health = ghost.health != null
349 ? { current: ghost.health, max: ghost.maxHealth ?? ghost.health }
350 : null;
351 return {
352 local: false,
353 handle: null,
354 pos: { tileX: ghost.tileX, tileY: ghost.tileY },
355 health
356 };
357}
358
359function attackerCombatLevels (ecs, attackerHandle, profile)
360{
361 const attackerCharacter = ecs.get(attackerHandle, Component.character);
362 if (attackerCharacter)
363 { return playerCombatLevels(ecs, attackerHandle, profile); }
364 const skills = ecs.get(attackerHandle, Component.skills);
365 return {
366 hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId),
367 damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId),
368 agilityLevel: skillLevel(skills, SkillId.agility),
369 defenceLevel: skillLevel(skills, SkillId.defence)
370 };
371}
372
373export function stepCombat (world, now = Date.now())
374{
375 const events = [];
376 for (const entity of world.ecs.query(Component.combat, Component.position))
377 {
378 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
379 { continue; }
380 const combat = entity.combat;
381 const targetId = combat.targetEntityId;
382 if (targetId == null)
383 { continue; }
384 const target = resolveCombatTarget(world, targetId);
385 if (!target)
386 {
387 combat.targetEntityId = null;
388 continue;
389 }
390 if (target.health && target.health.current <= 0)
391 {
392 combat.targetEntityId = null;
393 continue;
394 }
395
396 const profile = attackProfileOf(world.ecs, entity.handle);
397 const targetPos = target.pos;
398
399 if (profile.mode === "ranged")
400 {
401 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
402 const maxRange = profile.rangeTiles | 0 || COMBAT_RANGE_TILES;
403 const equipment = world.ecs.get(entity.handle, Component.equipment);
404 const hasArrows = arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0;
405 const inRange = dist >= 1 && dist <= maxRange
406 && hasCombatLineOfSight(
407 world,
408 entity.position.tileX,
409 entity.position.tileY,
410 targetPos.tileX,
411 targetPos.tileY
412 );
413 if (!inRange || !hasArrows)
414 {
415 if (inRange && !hasArrows && now >= (combat.nextSwingAt || 0)
416 && world.ecs.get(entity.handle, Component.character))
417 {
418 combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200);
419 events.push({
420 type: "combat-no-arrows",
421 attackerId: entity.entityId,
422 sessionId: world.ecs.get(entity.handle, Component.networkIdentity)?.sessionId ?? null
423 });
424 }
425 queueRangedApproach(world, entity.entityId, entity.handle, entity.position, targetPos, maxRange);
426 continue;
427 }
428 clearCombatApproachPath(world.ecs, entity.handle);
429 if (now < (combat.nextSwingAt || 0))
430 { continue; }
431 combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200);
432 events.push(...resolveRangedShot(world, entity.entityId, targetId, profile, now, targetPos));
433 continue;
434 }
435
436 if (profile.mode !== "melee")
437 { continue; }
438
439 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
440 const canSwing = dist === 1
441 && world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY);
442 if (!canSwing)
443 {
444 queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos);
445 continue;
446 }
447 clearCombatApproachPath(world.ecs, entity.handle);
448 const attackerHealth = world.ecs.get(entity.handle, Component.health);
449 if (attackerHealth && attackerHealth.current <= 0)
450 { continue; }
451 if ((combat.nextSwingAt || 0) > now)
452 { continue; }
453
454 combat.nextSwingAt = now + (profile.cooldownMs || 800);
455 events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now));
456 }
457 return events;
458}
459
460function clearCombatApproachPath (ecs, handle)
461{
462 const path = ecs.get(handle, Component.path);
463 if (path?.tiles?.length)
464 { path.tiles = []; }
465}
466
467export function queueMeleeApproach (world, entityId, handle, position, targetPos)
468{
469 if (world.frozen?.has?.(entityId))
470 { return; }
471 let path = world.ecs.get(handle, Component.path);
472 if (!path)
473 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
474
475 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY)
476 ?? true;
477 if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) === 1 && aloneHere)
478 {
479 path.tiles = [];
480 return;
481 }
482
483 const goal = bestAdjacentGoal(world, entityId, position, targetPos);
484 if (!goal)
485 {
486 path.tiles = [];
487 return;
488 }
489
490 if (goal.x === position.tileX && goal.y === position.tileY)
491 {
492 path.tiles = [];
493 return;
494 }
495
496 if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal))
497 { return; }
498
499 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
500 const preferVertical = !!world.ecs.get(handle, Component.character);
501 const tiles = findPath(
502 position.tileX,
503 position.tileY,
504 goal.x,
505 goal.y,
506 (x, y) =>
507 {
508 if (x === goal.x && y === goal.y)
509 {
510 return world.isClearStanding?.(entityId, x, y)
511 ?? world.walkableFor(entityId, x, y);
512 }
513 return world.walkableFor(entityId, x, y);
514 },
515 bounds.minX,
516 bounds.minY,
517 bounds.maxX,
518 bounds.maxY,
519 { preferVertical }
520 );
521 if (!tiles.length)
522 {
523 path.tiles = [];
524 return;
525 }
526 path.tiles = tiles;
527 const movement = world.ecs.get(handle, Component.movement);
528 if (movement)
529 { movement.walkCarry = 0; }
530}
531
532function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist)
533{
534 const dest = path.tiles[path.tiles.length - 1];
535 if (dest.x !== goal.x || dest.y !== goal.y)
536 { return true; }
537 const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY);
538 if (standOff < minStandDist || standOff > maxRange)
539 { return true; }
540 if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY))
541 { return true; }
542 const next = path.tiles[0];
543 if (!next)
544 { return true; }
545 return !world.walkableFor(entityId, next.x, next.y);
546}
547
548/**
549 * Path toward the nearest tile from which `targetTile` is in Chebyshev range with LOS.
550 * @param {number} minStandDist Minimum stand-off from target (0 = may stand on target tile).
551 */
552export function queueStandInRangeApproach (
553 world,
554 entityId,
555 handle,
556 position,
557 targetTileX,
558 targetTileY,
559 maxRange,
560 minStandDist = 1
561)
562{
563 if (world.frozen?.has?.(entityId))
564 { return; }
565 let path = world.ecs.get(handle, Component.path);
566 if (!path)
567 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
568
569 const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY);
570 if (
571 distToTarget <= maxRange
572 && distToTarget >= minStandDist
573 && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY)
574 )
575 {
576 path.tiles = [];
577 return;
578 }
579
580 let bestGoal = null;
581 let bestDist = Infinity;
582 for (let dy = -maxRange; dy <= maxRange; dy++)
583 {
584 for (let dx = -maxRange; dx <= maxRange; dx++)
585 {
586 const x = targetTileX + dx;
587 const y = targetTileY + dy;
588 const standOff = chebyshev(x, y, targetTileX, targetTileY);
589 if (standOff < minStandDist || standOff > maxRange)
590 { continue; }
591 if (!world.walkableFor(entityId, x, y))
592 { continue; }
593 if (!hasCombatLineOfSight(world, x, y, targetTileX, targetTileY))
594 { continue; }
595 const d = chebyshev(position.tileX, position.tileY, x, y);
596 if (d < bestDist)
597 {
598 bestDist = d;
599 bestGoal = { x, y };
600 }
601 }
602 }
603 if (!bestGoal)
604 {
605 path.tiles = [];
606 return;
607 }
608 if (bestGoal.x === position.tileX && bestGoal.y === position.tileY)
609 {
610 path.tiles = [];
611 return;
612 }
613 if (path.tiles?.length && !standInRangePathStale(
614 world,
615 entityId,
616 path,
617 bestGoal,
618 targetTileX,
619 targetTileY,
620 maxRange,
621 minStandDist
622 ))
623 { return; }
624 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
625 const preferVertical = !!world.ecs.get(handle, Component.character);
626 const tiles = findPath(
627 position.tileX,
628 position.tileY,
629 bestGoal.x,
630 bestGoal.y,
631 (x, y) => world.walkableFor(entityId, x, y),
632 bounds.minX,
633 bounds.minY,
634 bounds.maxX,
635 bounds.maxY,
636 { preferVertical }
637 );
638 path.tiles = tiles.length ? tiles : [];
639 const movement = world.ecs.get(handle, Component.movement);
640 if (movement)
641 { movement.walkCarry = 0; }
642}
643
644function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange)
645{
646 queueStandInRangeApproach(
647 world,
648 entityId,
649 handle,
650 position,
651 targetPos.tileX,
652 targetPos.tileY,
653 maxRange,
654 1
655 );
656}
657
658export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos)
659{
660 const events = [];
661 const attackerHandle = world.ecs.handleOf(attackerId);
662 if (attackerHandle == null)
663 { return events; }
664 const from = world.ecs.get(attackerHandle, Component.position);
665 if (!from || !targetPos)
666 { return events; }
667 if (!consumeArrow(world.ecs, attackerHandle))
668 { return events; }
669
670 const snapshot = { tileX: targetPos.tileX, tileY: targetPos.tileY };
671 const target = resolveCombatTarget(world, targetId);
672 if (!target)
673 { return events; }
674
675 if (!target.local)
676 {
677 events.push({
678 type: "remote-ranged-resolve",
679 attackerId,
680 targetId,
681 profile,
682 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile),
683 attackerIsPlayer: !!world.ecs.get(attackerHandle, Component.character),
684 now,
685 tileX: snapshot.tileX,
686 tileY: snapshot.tileY,
687 fromTileX: from.tileX,
688 fromTileY: from.tileY,
689 ...(publicDualTint(projectileDualTintFromAttacker(world.ecs, attackerHandle)) ?? {})
690 });
691 return events;
692 }
693
694 const hitEvents = applyLocalMeleeHit(
695 world,
696 attackerId,
697 targetId,
698 attackerHandle,
699 target.handle,
700 profile,
701 now,
702 snapshot
703 );
704 const outcome = hitEvents.find((e) =>
705 e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block");
706 let endX = snapshot.tileX;
707 let endY = snapshot.tileY;
708 if (outcome?.type === "combat-miss")
709 {
710 const miss = missProjectileTile(snapshot.tileX, snapshot.tileY);
711 endX = miss.tileX;
712 endY = miss.tileY;
713 }
714 else
715 {
716 const currentPos = world.ecs.get(target.handle, Component.position);
717 if (currentPos)
718 {
719 endX = currentPos.tileX;
720 endY = currentPos.tileY;
721 }
722 }
723 events.push({
724 type: "combat-projectile",
725 attackerId,
726 targetId,
727 fromTileX: from.tileX,
728 fromTileY: from.tileY,
729 tileX: endX,
730 tileY: endY,
731 durationMs: RANGED_PROJECTILE_MS,
732 ...publicDualTint(projectileDualTintFromAttacker(world.ecs, attackerHandle)) ?? {}
733 });
734 return events.concat(hitEvents);
735}
736
737function meleePathStale (world, entityId, position, targetPos, path, goal)
738{
739 const dest = path.tiles[path.tiles.length - 1];
740 if (dest.x !== goal.x || dest.y !== goal.y)
741 { return true; }
742 if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1)
743 { return true; }
744 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
745 { return true; }
746 const next = path.tiles[0];
747 if (!next)
748 { return true; }
749 return !world.walkableFor(entityId, next.x, next.y);
750}
751
752function bestAdjacentGoal (world, entityId, position, targetPos)
753{
754 const dirs = [
755 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
756 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
757 ];
758 let best = null;
759 let bestDist = Infinity;
760 for (const dir of dirs)
761 {
762 const x = targetPos.tileX + dir.x;
763 const y = targetPos.tileY + dir.y;
764 const isHere = x === position.tileX && y === position.tileY;
765 const clear = world.isClearStanding?.(entityId, x, y)
766 ?? world.walkableFor(entityId, x, y);
767 if (!clear && !isHere)
768 { continue; }
769 if (isHere && !(world.isClearStanding?.(entityId, x, y) ?? true))
770 { continue; }
771 const dist = chebyshev(position.tileX, position.tileY, x, y);
772 if (dist < bestDist)
773 {
774 bestDist = dist;
775 best = { x, y };
776 }
777 }
778 return best;
779}
780
781export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now())
782{
783 const events = [];
784 const attackerHandle = world.ecs.handleOf(attackerId);
785 if (attackerHandle == null)
786 { return events; }
787 const target = resolveCombatTarget(world, targetId);
788 if (!target)
789 { return events; }
790 const from = world.ecs.get(attackerHandle, Component.position);
791 const to = target.pos;
792 if (!from || !to)
793 { return events; }
794 if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1)
795 { return events; }
796 if (world.isClearStanding && !world.isClearStanding(attackerId, from.tileX, from.tileY))
797 { return events; }
798
799 events.push({
800 type: "combat-swing",
801 attackerId,
802 targetId,
803 tileX: to.tileX,
804 tileY: to.tileY,
805 fromTileX: from.tileX,
806 fromTileY: from.tileY
807 });
808
809 if (!target.local)
810 {
811 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
812 events.push({
813 type: "remote-melee-resolve",
814 attackerId,
815 targetId,
816 profile,
817 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile),
818 attackerIsPlayer: !!attackerCharacter,
819 now,
820 tileX: to.tileX,
821 tileY: to.tileY
822 });
823 return events;
824 }
825
826 return events.concat(applyLocalMeleeHit(
827 world,
828 attackerId,
829 targetId,
830 attackerHandle,
831 target.handle,
832 profile,
833 now,
834 to
835 ));
836}
837
838/** Authoritative ranged hit when the defender lives on this worker. */
839export function applyRemoteRangedShot (world, payload)
840{
841 const targetHandle = world.ecs.handleOf(payload.targetId);
842 if (targetHandle == null)
843 { return { events: [], forwards: [] }; }
844 const snapshot = {
845 tileX: payload.tileX,
846 tileY: payload.tileY
847 };
848
849 const hitEvents = applyLocalMeleeHit(
850 world,
851 payload.attackerId,
852 payload.targetId,
853 null,
854 targetHandle,
855 payload.profile,
856 payload.now ?? Date.now(),
857 snapshot,
858 payload.attackerLevels,
859 payload.attackerIsPlayer
860 );
861
862 const outcome = hitEvents.find((e) =>
863 e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block");
864 let endX = snapshot.tileX;
865 let endY = snapshot.tileY;
866 if (outcome?.type === "combat-miss")
867 {
868 const miss = missProjectileTile(snapshot.tileX, snapshot.tileY);
869 endX = miss.tileX;
870 endY = miss.tileY;
871 }
872 else
873 {
874 const currentPos = world.ecs.get(targetHandle, Component.position);
875 if (currentPos)
876 {
877 endX = currentPos.tileX;
878 endY = currentPos.tileY;
879 }
880 }
881
882 const events = [{
883 type: "combat-projectile",
884 attackerId: payload.attackerId,
885 targetId: payload.targetId,
886 fromTileX: payload.fromTileX,
887 fromTileY: payload.fromTileY,
888 tileX: endX,
889 tileY: endY,
890 durationMs: RANGED_PROJECTILE_MS,
891 shaftTint: payload.shaftTint ?? null,
892 tipTint: payload.tipTint ?? null
893 }, ...hitEvents];
894
895 const forwards = [];
896 const hitEvent = hitEvents.find((event) => event.type === "combat-hit");
897 if (hitEvent && payload.attackerIsPlayer)
898 {
899 forwards.push({
900 type: "forward-combat-xp",
901 entityId: payload.attackerId,
902 profile: payload.profile,
903 damage: hitEvent.damage
904 });
905 }
906 return { events, forwards };
907}
908
909/** Authoritative hit resolution when the defender lives on this worker. */
910export function applyRemoteMeleeSwing (world, payload)
911{
912 const targetHandle = world.ecs.handleOf(payload.targetId);
913 if (targetHandle == null)
914 { return { events: [], forwards: [] }; }
915 const to = world.ecs.get(targetHandle, Component.position);
916 if (!to)
917 { return { events: [], forwards: [] }; }
918
919 const events = applyLocalMeleeHit(
920 world,
921 payload.attackerId,
922 payload.targetId,
923 null,
924 targetHandle,
925 payload.profile,
926 payload.now ?? Date.now(),
927 to,
928 payload.attackerLevels,
929 payload.attackerIsPlayer
930 );
931
932 const forwards = [];
933 const hitEvent = events.find((event) => event.type === "combat-hit");
934 if (hitEvent && payload.attackerIsPlayer)
935 {
936 forwards.push({
937 type: "forward-combat-xp",
938 entityId: payload.attackerId,
939 profile: payload.profile,
940 damage: hitEvent.damage
941 });
942 }
943 return { events, forwards };
944}
945
946function applyLocalMeleeHit (
947 world,
948 attackerId,
949 targetId,
950 attackerHandle,
951 targetHandle,
952 profile,
953 now,
954 to,
955 attackerLevelsOverride = null,
956 attackerIsPlayerOverride = null
957)
958{
959 const events = [];
960 if (targetHandle == null)
961 { return events; }
962
963 const attackerIsPlayer = attackerIsPlayerOverride != null
964 ? !!attackerIsPlayerOverride
965 : (attackerHandle != null ? !!world.ecs.get(attackerHandle, Component.character) : null);
966
967 // Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.
968 if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId))
969 { engageTarget(world.ecs, targetId, attackerId, now); }
970 if (attackerIsPlayer === false)
971 {
972 const targetCharacter = world.ecs.get(targetHandle, Component.character);
973 if (targetCharacter)
974 {
975 engageTarget(world.ecs, targetId, attackerId, now);
976 const follow = world.ecs.get(targetHandle, Component.follow);
977 if (follow)
978 {
979 follow.targetEntityId = null;
980 follow.trail = [];
981 }
982 if (world.ecs.has(targetHandle, Component.gather))
983 { world.ecs.remove(targetHandle, Component.gather); }
984 }
985 }
986
987 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
988 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
989 const attackerLevels = attackerLevelsOverride
990 ?? (attackerHandle != null ? attackerCombatLevels(world.ecs, attackerHandle, profile) : null);
991 if (!attackerLevels)
992 { return events; }
993
994 const agilityLevel = defenderSkillLevel(
995 defenderSkills,
996 SkillId.agility,
997 defenderEquipment
998 );
999 const defenceLevel = defenderSkillLevel(
1000 defenderSkills,
1001 SkillId.defence,
1002 defenderEquipment
1003 );
1004
1005 const resolved = resolvePhysicalAttack({
1006 hitSkillLevel: effectiveHitSkillInDarkness(
1007 attackerLevels.hitLevel,
1008 tileLightAt(world, to.tileX, to.tileY)
1009 ),
1010 agilitySkillLevel: agilityLevel,
1011 damageSkillLevel: attackerLevels.damageLevel,
1012 defenceSkillLevel: defenceLevel
1013 });
1014
1015 if (resolved.outcome === "miss")
1016 {
1017 events.push({
1018 type: "combat-miss",
1019 attackerId,
1020 targetId,
1021 tileX: to.tileX,
1022 tileY: to.tileY
1023 });
1024 const dodgeXp = awardCombatAvoidanceXp(
1025 world.ecs,
1026 targetHandle,
1027 SkillId.agility,
1028 resolved.damageRoll
1029 );
1030 if (dodgeXp)
1031 {
1032 events.push({
1033 type: "skills-updated",
1034 entityId: targetId,
1035 characterId: dodgeXp.characterId,
1036 skills: dodgeXp.view,
1037 stored: dodgeXp.stored,
1038 levelUps: dodgeXp.levelUps ?? []
1039 });
1040 }
1041 return events;
1042 }
1043
1044 if (resolved.outcome === "block")
1045 {
1046 events.push({
1047 type: "combat-block",
1048 attackerId,
1049 targetId,
1050 tileX: to.tileX,
1051 tileY: to.tileY
1052 });
1053 const blockXp = awardCombatAvoidanceXp(
1054 world.ecs,
1055 targetHandle,
1056 SkillId.defence,
1057 resolved.damageRoll
1058 );
1059 if (blockXp)
1060 {
1061 events.push({
1062 type: "skills-updated",
1063 entityId: targetId,
1064 characterId: blockXp.characterId,
1065 skills: blockXp.view,
1066 stored: blockXp.stored,
1067 levelUps: blockXp.levelUps ?? []
1068 });
1069 }
1070 return events;
1071 }
1072
1073 const damage = resolved.damage;
1074 const targetCharacter = world.ecs.get(targetHandle, Component.character);
1075 if (targetCharacter)
1076 { syncPlayerHealth(world.ecs, targetHandle); }
1077 const health = world.ecs.get(targetHandle, Component.health);
1078 if (health)
1079 {
1080 health.current = Math.max(0, (health.current | 0) - damage);
1081 }
1082 events.push({
1083 type: "combat-hit",
1084 attackerId,
1085 targetId,
1086 damage,
1087 tileX: to.tileX,
1088 tileY: to.tileY,
1089 health: health?.current ?? 0,
1090 maxHealth: health?.max ?? 0
1091 });
1092
1093 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
1094 if (healthXp)
1095 {
1096 events.push({
1097 type: "skills-updated",
1098 entityId: targetId,
1099 characterId: healthXp.characterId,
1100 skills: healthXp.view,
1101 stored: healthXp.stored,
1102 levelUps: healthXp.levelUps ?? []
1103 });
1104 if (health)
1105 {
1106 const hitEvent = events[events.length - 2];
1107 if (hitEvent?.type === "combat-hit")
1108 {
1109 hitEvent.health = health.current;
1110 hitEvent.maxHealth = health.max;
1111 }
1112 }
1113 }
1114
1115 if (attackerHandle != null)
1116 {
1117 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
1118 if (attackerCharacter)
1119 {
1120 const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile, damage);
1121 if (xpAward)
1122 {
1123 events.push({
1124 type: "skills-updated",
1125 entityId: attackerId,
1126 characterId: attackerCharacter.characterId,
1127 skills: xpAward.view,
1128 stored: xpAward.stored,
1129 levelUps: xpAward.levelUps ?? []
1130 });
1131 }
1132 }
1133 }
1134
1135 if (health && health.current <= 0)
1136 {
1137 clearEngage(world.ecs, attackerId);
1138 clearEngage(world.ecs, targetId);
1139 for (const entity of world.ecs.query(Component.combat))
1140 {
1141 if (entity.combat.targetEntityId === targetId)
1142 { entity.combat.targetEntityId = null; }
1143 }
1144 if (targetCharacter && !world.ecs.has(targetHandle, Component.dead))
1145 {
1146 const path = world.ecs.get(targetHandle, Component.path);
1147 if (path)
1148 { path.tiles = []; }
1149 const follow = world.ecs.get(targetHandle, Component.follow);
1150 if (follow)
1151 {
1152 follow.targetEntityId = null;
1153 follow.trail = [];
1154 }
1155 world.ecs.add(targetHandle, Component.dead, {});
1156 const identity = world.ecs.get(targetHandle, Component.networkIdentity);
1157 events.push({
1158 type: "player-died",
1159 entityId: targetId,
1160 attackerId,
1161 characterId: targetCharacter.characterId,
1162 sessionId: identity?.sessionId ?? null,
1163 tileX: to.tileX,
1164 tileY: to.tileY,
1165 health: 0,
1166 maxHealth: health.max
1167 });
1168 }
1169 const creature = world.ecs.get(targetHandle, Component.creature);
1170 if (creature && !world.ecs.get(targetHandle, Component.character))
1171 {
1172 events.push(...spawnMobDrops(world, targetHandle, to.tileX, to.tileY, now));
1173 const view = world.destroyEntity?.(targetId) ?? null;
1174 if (view)
1175 {
1176 events.push({
1177 type: "entity-despawn",
1178 entityId: targetId,
1179 tileX: view.tileX,
1180 tileY: view.tileY
1181 });
1182 }
1183 }
1184 }
1185 return events;
1186}