BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

service.js 18.0 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 { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
13import {
14 effectiveSkillLevel,
15 equipmentBonusesFromSlots
16} from "../../../shared/equipment/stats.js";
17import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
18import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
19import { chunkBoundsAround, findPath } from "../navigation/astar.js";
20import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
21import { rayReaches } from "../../../shared/lighting/raycast.js";
22
23export function chebyshev (ax, ay, bx, by)
24{
25 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
26}
27
28export function attackProfileOf (ecs, handle)
29{
30 const equipment = ecs.get(handle, Component.equipment);
31 const weapon = equipment?.slots?.weapon;
32 if (weapon?.itemId != null)
33 {
34 const attack = itemDefinition(weapon.itemId)?.equipment?.attack;
35 if (attack)
36 { return { ...attack }; }
37 }
38 const creature = ecs.get(handle, Component.creature);
39 if (creature)
40 {
41 const def = mobDefinition(creature.mobTypeId);
42 if (mobCanFightType(creature.mobTypeId))
43 { return mobMeleeAttackProfile(def); }
44 }
45 return { ...UNARMED_ATTACK };
46}
47
48export function ensureMobCombat (ecs, entityId)
49{
50 const handle = ecs.handleOf(entityId);
51 if (handle == null)
52 { return false; }
53 const creature = ecs.get(handle, Component.creature);
54 if (!creature || !mobCanFightType(creature.mobTypeId))
55 { return false; }
56 const def = mobDefinition(creature.mobTypeId);
57 if (!ecs.get(handle, Component.combat))
58 { ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
59 if (!ecs.get(handle, Component.skills))
60 { ecs.add(handle, Component.skills, { levels: mobSkillLevels(def) }); }
61 return true;
62}
63
64function attackerSkillLevel (skills, profile, skillId)
65{
66 if (profile.mobAttackSkill != null)
67 { return profile.mobAttackSkill; }
68 return skillLevel(skills, skillId);
69}
70
71function defenderSkillLevel (skills, skillId, equipment = null)
72{
73 const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots) : {};
74 return effectiveSkillLevel(skills, skillId, bonuses);
75}
76
77function playerCombatLevels (ecs, handle, profile)
78{
79 const skills = ecs.get(handle, Component.skills);
80 const equipment = ecs.get(handle, Component.equipment);
81 const bonuses = equipmentBonusesFromSlots(equipment?.slots);
82 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
83 bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0);
84 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
85 return {
86 hitLevel: skillLevel(skills, profile.hitSkillId),
87 damageLevel: effectiveSkillLevel(skills, profile.damageSkillId, bonuses),
88 agilityLevel: effectiveSkillLevel(skills, SkillId.dexterity, bonuses),
89 defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses)
90 };
91}
92
93export function isUntargetable (ecs, handle)
94{
95 const creature = ecs.get(handle, Component.creature);
96 if (!creature)
97 { return false; }
98 return !!mobDefinition(creature.mobTypeId)?.untargetable;
99}
100
101export function engageTarget (ecs, attackerId, targetId, now = Date.now())
102{
103 const handle = ecs.handleOf(attackerId);
104 if (handle == null)
105 { return false; }
106 let combat = ecs.get(handle, Component.combat);
107 if (!combat)
108 { combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
109 const targetChanged = combat.targetEntityId !== targetId;
110 combat.targetEntityId = targetId;
111 combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now);
112 if (targetChanged)
113 {
114 const path = ecs.get(handle, Component.path);
115 if (path)
116 { path.tiles = []; }
117 }
118 return true;
119}
120
121export function clearEngage (ecs, entityId)
122{
123 const handle = ecs.handleOf(entityId);
124 const combat = handle != null ? ecs.get(handle, Component.combat) : null;
125 if (combat)
126 { combat.targetEntityId = null; }
127}
128
129export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)
130{
131 return rayReaches(fromX, fromY, toX, toY, (x, y) => world.isEnterable(x, y));
132}
133
134/**
135 * Aggressive mobs auto-engage the nearest player character within aggro range
136 * when they have line of sight. Does nothing while already engaged.
137 */
138export function stepAggression (world, now = Date.now())
139{
140 for (const entity of world.ecs.query(Component.creature, Component.position))
141 {
142 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
143 { continue; }
144 const def = mobDefinition(entity.creature.mobTypeId);
145 if (!mobIsAggressive(def))
146 { continue; }
147 if (world.ecs.has(entity.handle, Component.dead))
148 { continue; }
149 const health = world.ecs.get(entity.handle, Component.health);
150 if (health && health.current <= 0)
151 { continue; }
152 const combat = world.ecs.get(entity.handle, Component.combat);
153 if (combat?.targetEntityId != null)
154 { continue; }
155
156 const range = mobAggroRangeTiles(def);
157 let bestId = null;
158 let bestDist = Infinity;
159 for (const player of world.ecs.query(Component.character, Component.position))
160 {
161 if (world.ecs.has(player.handle, Component.dead))
162 { continue; }
163 const playerHealth = world.ecs.get(player.handle, Component.health);
164 if (playerHealth && playerHealth.current <= 0)
165 { continue; }
166 const dist = chebyshev(
167 entity.position.tileX,
168 entity.position.tileY,
169 player.position.tileX,
170 player.position.tileY
171 );
172 if (dist < 1 || dist > range)
173 { continue; }
174 if (!hasCombatLineOfSight(
175 world,
176 entity.position.tileX,
177 entity.position.tileY,
178 player.position.tileX,
179 player.position.tileY
180 ))
181 { continue; }
182 if (dist < bestDist)
183 {
184 bestDist = dist;
185 bestId = player.entityId;
186 }
187 }
188 if (bestId == null)
189 { continue; }
190 if (!ensureMobCombat(world.ecs, entity.entityId))
191 { continue; }
192 engageTarget(world.ecs, entity.entityId, bestId, now);
193 }
194}
195
196/** Local entity handle or a nearby ghost snapshot for cross-worker combat. */
197export function resolveCombatTarget (world, targetId)
198{
199 const handle = world.ecs.handleOf(targetId);
200 if (handle != null)
201 {
202 const pos = world.ecs.get(handle, Component.position);
203 if (!pos)
204 { return null; }
205 if (isUntargetable(world.ecs, handle))
206 { return null; }
207 return {
208 local: true,
209 handle,
210 pos,
211 health: world.ecs.get(handle, Component.health)
212 };
213 }
214 const ghost = world.ghosts?.get?.(targetId);
215 if (!ghost || ghost.untargetable)
216 { return null; }
217 const health = ghost.health != null
218 ? { current: ghost.health, max: ghost.maxHealth ?? ghost.health }
219 : null;
220 return {
221 local: false,
222 handle: null,
223 pos: { tileX: ghost.tileX, tileY: ghost.tileY },
224 health
225 };
226}
227
228function attackerCombatLevels (ecs, attackerHandle, profile)
229{
230 const attackerCharacter = ecs.get(attackerHandle, Component.character);
231 if (attackerCharacter)
232 { return playerCombatLevels(ecs, attackerHandle, profile); }
233 const skills = ecs.get(attackerHandle, Component.skills);
234 return {
235 hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId),
236 damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId),
237 agilityLevel: skillLevel(skills, SkillId.dexterity),
238 defenceLevel: skillLevel(skills, SkillId.defence)
239 };
240}
241
242export function stepCombat (world, now = Date.now())
243{
244 const events = [];
245 for (const entity of world.ecs.query(Component.combat, Component.position))
246 {
247 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
248 { continue; }
249 const combat = entity.combat;
250 const targetId = combat.targetEntityId;
251 if (targetId == null)
252 { continue; }
253 const target = resolveCombatTarget(world, targetId);
254 if (!target)
255 {
256 combat.targetEntityId = null;
257 continue;
258 }
259 if (target.health && target.health.current <= 0)
260 {
261 combat.targetEntityId = null;
262 continue;
263 }
264
265 const profile = attackProfileOf(world.ecs, entity.handle);
266 if (profile.mode !== "melee")
267 { continue; }
268
269 const targetPos = target.pos;
270 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
271 clearCombatApproachPath(world.ecs, entity.handle, dist);
272 if (dist > 1)
273 {
274 queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos);
275 continue;
276 }
277 if (dist !== 1)
278 { continue; }
279 const attackerHealth = world.ecs.get(entity.handle, Component.health);
280 if (attackerHealth && attackerHealth.current <= 0)
281 { continue; }
282 if ((combat.nextSwingAt || 0) > now)
283 { continue; }
284
285 combat.nextSwingAt = now + (profile.cooldownMs || 800);
286 events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now));
287 }
288 return events;
289}
290
291function clearCombatApproachPath (ecs, handle, distToTarget)
292{
293 if (distToTarget > 1)
294 { return; }
295 const path = ecs.get(handle, Component.path);
296 if (path?.tiles?.length)
297 { path.tiles = []; }
298}
299
300function queueMeleeApproach (world, entityId, handle, position, targetPos)
301{
302 if (world.frozen?.has?.(entityId))
303 { return; }
304 let path = world.ecs.get(handle, Component.path);
305 if (!path)
306 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
307
308 if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) <= 1)
309 {
310 path.tiles = [];
311 return;
312 }
313
314 const goal = bestAdjacentGoal(world, entityId, position, targetPos);
315 if (!goal)
316 {
317 path.tiles = [];
318 return;
319 }
320
321 if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal))
322 { return; }
323
324 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
325 const tiles = findPath(
326 position.tileX,
327 position.tileY,
328 goal.x,
329 goal.y,
330 (x, y) => world.walkableFor(entityId, x, y),
331 bounds.minX,
332 bounds.minY,
333 bounds.maxX,
334 bounds.maxY
335 );
336 if (!tiles.length)
337 {
338 path.tiles = [];
339 return;
340 }
341 path.tiles = tiles;
342 const movement = world.ecs.get(handle, Component.movement);
343 if (movement)
344 { movement.walkCarry = 0; }
345}
346
347function meleePathStale (world, entityId, position, targetPos, path, goal)
348{
349 const dest = path.tiles[path.tiles.length - 1];
350 if (dest.x !== goal.x || dest.y !== goal.y)
351 { return true; }
352 if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1)
353 { return true; }
354 const next = path.tiles[0];
355 if (!next)
356 { return true; }
357 const blockedByOther = !world.walkableFor(entityId, next.x, next.y)
358 && !(next.x === targetPos.tileX && next.y === targetPos.tileY);
359 return blockedByOther;
360}
361
362function bestAdjacentGoal (world, entityId, position, targetPos)
363{
364 const dirs = [
365 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
366 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
367 ];
368 let best = null;
369 let bestDist = Infinity;
370 for (const dir of dirs)
371 {
372 const x = targetPos.tileX + dir.x;
373 const y = targetPos.tileY + dir.y;
374 if (!world.walkableFor(entityId, x, y) && !(x === position.tileX && y === position.tileY))
375 { continue; }
376 const dist = chebyshev(position.tileX, position.tileY, x, y);
377 if (dist < bestDist)
378 {
379 bestDist = dist;
380 best = { x, y };
381 }
382 }
383 return best;
384}
385
386export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now())
387{
388 const events = [];
389 const attackerHandle = world.ecs.handleOf(attackerId);
390 if (attackerHandle == null)
391 { return events; }
392 const target = resolveCombatTarget(world, targetId);
393 if (!target)
394 { return events; }
395 const from = world.ecs.get(attackerHandle, Component.position);
396 const to = target.pos;
397 if (!from || !to)
398 { return events; }
399 if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1)
400 { return events; }
401
402 events.push({
403 type: "combat-swing",
404 attackerId,
405 targetId,
406 tileX: to.tileX,
407 tileY: to.tileY,
408 fromTileX: from.tileX,
409 fromTileY: from.tileY
410 });
411
412 if (!target.local)
413 {
414 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
415 events.push({
416 type: "remote-melee-resolve",
417 attackerId,
418 targetId,
419 profile,
420 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile),
421 attackerIsPlayer: !!attackerCharacter,
422 now,
423 tileX: to.tileX,
424 tileY: to.tileY
425 });
426 return events;
427 }
428
429 return events.concat(applyLocalMeleeHit(
430 world,
431 attackerId,
432 targetId,
433 attackerHandle,
434 target.handle,
435 profile,
436 now,
437 to
438 ));
439}
440
441/** Authoritative hit resolution when the defender lives on this worker. */
442export function applyRemoteMeleeSwing (world, payload)
443{
444 const targetHandle = world.ecs.handleOf(payload.targetId);
445 if (targetHandle == null)
446 { return { events: [], forwards: [] }; }
447 const to = world.ecs.get(targetHandle, Component.position);
448 if (!to)
449 { return { events: [], forwards: [] }; }
450
451 const events = applyLocalMeleeHit(
452 world,
453 payload.attackerId,
454 payload.targetId,
455 null,
456 targetHandle,
457 payload.profile,
458 payload.now ?? Date.now(),
459 to,
460 payload.attackerLevels
461 );
462
463 const forwards = [];
464 if (payload.attackerIsPlayer && ensureMobCombat(world.ecs, payload.targetId))
465 { engageTarget(world.ecs, payload.targetId, payload.attackerId, payload.now ?? Date.now()); }
466 if (!payload.attackerIsPlayer)
467 {
468 const targetCharacter = world.ecs.get(targetHandle, Component.character);
469 if (targetCharacter)
470 { engageTarget(world.ecs, payload.targetId, payload.attackerId, payload.now ?? Date.now()); }
471 }
472 const hitEvent = events.find((event) => event.type === "combat-hit");
473 if (hitEvent && payload.attackerIsPlayer)
474 {
475 forwards.push({
476 type: "forward-combat-xp",
477 entityId: payload.attackerId,
478 profile: payload.profile
479 });
480 }
481 return { events, forwards };
482}
483
484function applyLocalMeleeHit (
485 world,
486 attackerId,
487 targetId,
488 attackerHandle,
489 targetHandle,
490 profile,
491 now,
492 to,
493 attackerLevelsOverride = null
494)
495{
496 const events = [];
497 if (targetHandle == null)
498 { return events; }
499
500 if (attackerHandle != null)
501 {
502 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
503 // Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.
504 if (attackerCharacter && ensureMobCombat(world.ecs, targetId))
505 { engageTarget(world.ecs, targetId, attackerId, now); }
506 }
507
508 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
509 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
510 const attackerLevels = attackerLevelsOverride
511 ?? (attackerHandle != null ? attackerCombatLevels(world.ecs, attackerHandle, profile) : null);
512 if (!attackerLevels)
513 { return events; }
514
515 const agilityLevel = defenderSkillLevel(
516 defenderSkills,
517 SkillId.dexterity,
518 defenderEquipment
519 );
520 const defenceLevel = defenderSkillLevel(
521 defenderSkills,
522 SkillId.defence,
523 defenderEquipment
524 );
525
526 const resolved = resolvePhysicalAttack({
527 hitSkillLevel: attackerLevels.hitLevel,
528 agilitySkillLevel: agilityLevel,
529 damageSkillLevel: attackerLevels.damageLevel,
530 defenceSkillLevel: defenceLevel,
531 baseDamage: profile.baseDamage ?? 1
532 });
533
534 if (resolved.outcome === "miss")
535 {
536 events.push({
537 type: "combat-miss",
538 attackerId,
539 targetId,
540 tileX: to.tileX,
541 tileY: to.tileY
542 });
543 return events;
544 }
545
546 if (resolved.outcome === "block")
547 {
548 events.push({
549 type: "combat-block",
550 attackerId,
551 targetId,
552 tileX: to.tileX,
553 tileY: to.tileY
554 });
555 return events;
556 }
557
558 const damage = resolved.damage;
559 const targetCharacter = world.ecs.get(targetHandle, Component.character);
560 if (targetCharacter)
561 { syncPlayerHealth(world.ecs, targetHandle); }
562 const health = world.ecs.get(targetHandle, Component.health);
563 if (health)
564 {
565 health.current = Math.max(0, (health.current | 0) - damage);
566 }
567 events.push({
568 type: "combat-hit",
569 attackerId,
570 targetId,
571 damage,
572 tileX: to.tileX,
573 tileY: to.tileY,
574 health: health?.current ?? 0,
575 maxHealth: health?.max ?? 0
576 });
577
578 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
579 if (healthXp)
580 {
581 events.push({
582 type: "skills-updated",
583 entityId: targetId,
584 characterId: healthXp.characterId,
585 skills: healthXp.view,
586 stored: healthXp.stored,
587 levelUps: healthXp.levelUps ?? []
588 });
589 if (health)
590 {
591 const hitEvent = events[events.length - 2];
592 if (hitEvent?.type === "combat-hit")
593 {
594 hitEvent.health = health.current;
595 hitEvent.maxHealth = health.max;
596 }
597 }
598 }
599
600 if (attackerHandle != null)
601 {
602 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
603 if (attackerCharacter)
604 {
605 const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile);
606 if (xpAward)
607 {
608 events.push({
609 type: "skills-updated",
610 entityId: attackerId,
611 characterId: attackerCharacter.characterId,
612 skills: xpAward.view,
613 stored: xpAward.stored,
614 levelUps: xpAward.levelUps ?? []
615 });
616 }
617 }
618 }
619
620 if (health && health.current <= 0)
621 {
622 clearEngage(world.ecs, attackerId);
623 clearEngage(world.ecs, targetId);
624 for (const entity of world.ecs.query(Component.combat))
625 {
626 if (entity.combat.targetEntityId === targetId)
627 { entity.combat.targetEntityId = null; }
628 }
629 if (targetCharacter && !world.ecs.has(targetHandle, Component.dead))
630 {
631 const path = world.ecs.get(targetHandle, Component.path);
632 if (path)
633 { path.tiles = []; }
634 const follow = world.ecs.get(targetHandle, Component.follow);
635 if (follow)
636 {
637 follow.targetEntityId = null;
638 follow.trail = [];
639 }
640 world.ecs.add(targetHandle, Component.dead, {});
641 const identity = world.ecs.get(targetHandle, Component.networkIdentity);
642 events.push({
643 type: "player-died",
644 entityId: targetId,
645 attackerId,
646 characterId: targetCharacter.characterId,
647 sessionId: identity?.sessionId ?? null,
648 tileX: to.tileX,
649 tileY: to.tileY,
650 health: 0,
651 maxHealth: health.max
652 });
653 }
654 const creature = world.ecs.get(targetHandle, Component.creature);
655 if (creature && !world.ecs.get(targetHandle, Component.character))
656 {
657 const view = world.destroyEntity?.(targetId) ?? null;
658 if (view)
659 {
660 events.push({
661 type: "entity-despawn",
662 entityId: targetId,
663 tileX: view.tileX,
664 tileY: view.tileY
665 });
666 }
667 }
668 }
669 return events;
670}