BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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