BlueGit

timfa questward

Files

questward / server / src / spells / service.js

service.js

service.js 19.1 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
3import { SpellId, spellDefinition, spellDifficulty } from "../../../shared/definitions/spells.js";
4import {
5 canCastSpell,
6 defaultPlayerSpells,
7 normalizePlayerSpells,
8 publicSpellsView,
9 storedPlayerSpells,
10 toggleFavorite,
11 learnSpell
12} from "../../../shared/spells/state.js";
13import {
14 CAST_FLASH_MS,
15 COMBAT_RANGE_TILES,
16 LIGHT_DURATION_MS_PER_MIND,
17 SPELL_COOLDOWN_MS,
18 SPELL_PROJECTILE_MS,
19 castFlashRadiusTiles
20} from "../../../shared/spells/constants.js";
21import {
22 mobElementAffinities,
23 ElementMultiplier,
24 resolveMagicAttack,
25 resolveSpellCast,
26 resolveSpellPotency
27} from "../../../shared/combat/magic.js";
28import { mobDefinition } from "../../../shared/definitions/mobs.js";
29import { awardCombatHitXp, awardDamageHealthXp, awardSpellCastXp, syncPlayerHealth } from "../skills/service.js";
30import { equipmentBonusesFromSlots, effectiveSkillLevel } from "../../../shared/equipment/stats.js";
31import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
32import {
33 chebyshev,
34 hasCombatLineOfSight,
35 queueStandInRangeApproach,
36 resolveCombatTarget,
37 applyDamageAndKill
38} from "../combat/service.js";
39import { publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
40import { spellCastXpFromDifficulty } from "../../../shared/skills/progression.js";
41import { publicSpellLight, SpellLightRegistry } from "./lights.js";
42import { SpellbookItemId, spellbookInstance } from "../../../shared/definitions/spellItems.js";
43import { bagView } from "../items/bags.js";
44
45const MAGIC_ATTACK_PROFILE = Object.freeze({
46 hitSkillId: SkillId.magic,
47 damageSkillId: SkillId.mind
48});
49
50export function ensureSpellComponents (ecs, handle, storedSpells = null)
51{
52 if (!ecs.get(handle, Component.spells))
53 {
54 ecs.add(handle, Component.spells, normalizePlayerSpells(storedSpells ?? defaultPlayerSpells()));
55 }
56 if (!ecs.get(handle, Component.spellcasting))
57 {
58 ecs.add(handle, Component.spellcasting, {
59 armedSpellId: null,
60 repeatSpellId: null,
61 repeatTargetEntityId: null,
62 nextCastAt: 0
63 });
64 }
65}
66
67export function handleSpellCommand (world, sessionId, command, now = Date.now())
68{
69 switch (command.type)
70 {
71 case "set-spell-favorite":
72 return setSpellFavorite(world, sessionId, command, now);
73 case "set-spell-autocast":
74 return setSpellAutoCast(world, sessionId, command, now);
75 case "arm-spell":
76 return armSpell(world, sessionId, command, now);
77 case "cancel-arm-spell":
78 return cancelArmSpell(world, sessionId, command, now);
79 case "cast-spell-tile":
80 return castSpellAtTile(world, sessionId, command, now);
81 case "cast-spell-entity":
82 return castSpellAtEntity(world, sessionId, command, now);
83 case "read-spellbook":
84 return readSpellbook(world, sessionId, command, now);
85 default:
86 return null;
87 }
88}
89
90function requirePlayer (world, sessionId, characterId)
91{
92 for (const entity of world.ecs.query(Component.networkIdentity, Component.character))
93 {
94 if (entity.networkIdentity.sessionId !== sessionId)
95 { continue; }
96 if (entity.character.characterId !== characterId)
97 { continue; }
98 return { handle: entity.handle, entityId: entity.entityId, character: entity.character };
99 }
100 const error = new Error("Character not found.");
101 error.userFacing = true;
102 throw error;
103}
104
105function spellsUpdatedEvent (entityId, characterId, spells, skills, levelUps = [])
106{
107 return {
108 type: "spells-updated",
109 entityId,
110 characterId,
111 spells: publicSpellsView(spells, skills),
112 stored: storedPlayerSpells(spells),
113 autoCast: !!spells.autoCast,
114 levelUps
115 };
116}
117
118function setSpellFavorite (world, sessionId, command, now)
119{
120 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
121 ensureSpellComponents(world.ecs, handle);
122 const skills = world.ecs.get(handle, Component.skills);
123 const spells = world.ecs.get(handle, Component.spells);
124 const result = toggleFavorite(spells, command.spellId, skills);
125 if (result.error)
126 {
127 const error = new Error(result.error);
128 error.userFacing = true;
129 throw error;
130 }
131 Object.assign(spells, result.spells);
132 const events = [];
133 if (result.changed)
134 {
135 events.push(spellsUpdatedEvent(entityId, character.characterId, spells, skills));
136 }
137 return { events };
138}
139
140function setSpellAutoCast (world, sessionId, command, now)
141{
142 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
143 ensureSpellComponents(world.ecs, handle);
144 const skills = world.ecs.get(handle, Component.skills);
145 const spells = world.ecs.get(handle, Component.spells);
146 spells.autoCast = !!command.enabled;
147 const casting = world.ecs.get(handle, Component.spellcasting);
148 if (!spells.autoCast)
149 {
150 casting.repeatSpellId = null;
151 casting.repeatTargetEntityId = null;
152 }
153 return {
154 events: [spellsUpdatedEvent(entityId, character.characterId, spells, skills)]
155 };
156}
157
158function armSpell (world, sessionId, command, now)
159{
160 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
161 ensureSpellComponents(world.ecs, handle);
162 const skills = world.ecs.get(handle, Component.skills);
163 const spells = world.ecs.get(handle, Component.spells);
164 const check = canCastSpell(skills, spells, command.spellId);
165 if (!check.ok)
166 {
167 const error = new Error(check.reason);
168 error.userFacing = true;
169 throw error;
170 }
171 const casting = world.ecs.get(handle, Component.spellcasting);
172 casting.armedSpellId = command.spellId;
173 casting.repeatSpellId = null;
174 casting.repeatTargetEntityId = null;
175 casting.pendingCast = null;
176 return {
177 events: [{
178 type: "spell-armed",
179 entityId,
180 characterId: character.characterId,
181 spellId: command.spellId
182 }]
183 };
184}
185
186function cancelArmSpell (world, sessionId, command)
187{
188 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
189 const casting = world.ecs.get(handle, Component.spellcasting);
190 if (!casting)
191 { return { events: [] }; }
192 casting.armedSpellId = null;
193 casting.repeatSpellId = null;
194 casting.repeatTargetEntityId = null;
195 casting.pendingCast = null;
196 return {
197 events: [{
198 type: "spell-disarmed",
199 entityId,
200 characterId: character.characterId
201 }]
202 };
203}
204
205function casterMagicLevels (ecs, handle, settings = null)
206{
207 const skills = ecs.get(handle, Component.skills);
208 const equipment = ecs.get(handle, Component.equipment);
209 const bonuses = equipmentBonusesFromSlots(equipment?.slots, settings);
210 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
211 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
212 return {
213 magic: effectiveSkillLevel(skills, SkillId.magic, bonuses),
214 mind: effectiveSkillLevel(skills, SkillId.mind, bonuses)
215 };
216}
217
218function validateCastRange (world, handle, tileX, tileY, now)
219{
220 const pos = world.ecs.get(handle, Component.position);
221 if (!pos)
222 { return { ok: false, reason: "You are not in the world." }; }
223 const dist = chebyshev(pos.tileX, pos.tileY, tileX, tileY);
224 if (dist > COMBAT_RANGE_TILES)
225 { return { ok: false, reason: "That is out of range." }; }
226 if (!hasCombatLineOfSight(world, pos.tileX, pos.tileY, tileX, tileY))
227 { return { ok: false, reason: "You cannot see that spot." }; }
228 return { ok: true };
229}
230
231function resolvePendingCastTarget (world, pending)
232{
233 if (pending.targetEntityId == null)
234 {
235 return {
236 tileX: pending.tileX | 0,
237 tileY: pending.tileY | 0,
238 targetEntityId: null
239 };
240 }
241 const target = resolveCombatTarget(world, pending.targetEntityId);
242 if (!target)
243 { return null; }
244 return {
245 tileX: target.pos.tileX,
246 tileY: target.pos.tileY,
247 targetEntityId: pending.targetEntityId
248 };
249}
250
251function queueSpellApproach (world, handle, entityId, target, minStandDist)
252{
253 const position = world.ecs.get(handle, Component.position);
254 if (!position)
255 { return; }
256 queueStandInRangeApproach(
257 world,
258 entityId,
259 handle,
260 position,
261 target.tileX,
262 target.tileY,
263 COMBAT_RANGE_TILES,
264 minStandDist
265 );
266}
267
268function beginCastOrApproach (world, sessionId, characterId, spellId, target, now, minStandDist = 0)
269{
270 const { handle, entityId } = requirePlayer(world, sessionId, characterId);
271 ensureSpellComponents(world.ecs, handle);
272 const casting = world.ecs.get(handle, Component.spellcasting);
273 const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now);
274 if (!rangeCheck.ok)
275 {
276 casting.pendingCast = {
277 spellId,
278 tileX: target.tileX,
279 tileY: target.tileY,
280 targetEntityId: target.targetEntityId ?? null
281 };
282 queueSpellApproach(world, handle, entityId, target, minStandDist);
283 return { events: [] };
284 }
285 casting.pendingCast = null;
286 return executeCast(world, sessionId, characterId, spellId, target, now);
287}
288
289function castSpellAtTile (world, sessionId, command, now)
290{
291 const spellId = command.spellId;
292 const def = spellDefinition(spellId);
293 if (!def || def.target !== "tile")
294 {
295 const error = new Error("That spell needs a different target.");
296 error.userFacing = true;
297 throw error;
298 }
299 return beginCastOrApproach(world, sessionId, command.characterId, spellId, {
300 tileX: command.tileX | 0,
301 tileY: command.tileY | 0,
302 targetEntityId: null
303 }, now, 0);
304}
305
306function castSpellAtEntity (world, sessionId, command, now)
307{
308 const spellId = command.spellId;
309 const def = spellDefinition(spellId);
310 if (!def || def.target !== "entity")
311 {
312 const error = new Error("That spell needs a tile target.");
313 error.userFacing = true;
314 throw error;
315 }
316 const target = resolveCombatTarget(world, command.targetEntityId);
317 if (!target)
318 {
319 const error = new Error("Target is not here.");
320 error.userFacing = true;
321 throw error;
322 }
323 return beginCastOrApproach(world, sessionId, command.characterId, spellId, {
324 tileX: target.pos.tileX,
325 tileY: target.pos.tileY,
326 targetEntityId: command.targetEntityId
327 }, now, 1);
328}
329
330function executeCast (world, sessionId, characterId, spellId, target, now)
331{
332 const { handle, entityId, character } = requirePlayer(world, sessionId, characterId);
333 ensureSpellComponents(world.ecs, handle);
334 const skills = world.ecs.get(handle, Component.skills);
335 const spells = world.ecs.get(handle, Component.spells);
336 const casting = world.ecs.get(handle, Component.spellcasting);
337 const def = spellDefinition(spellId);
338 const check = canCastSpell(skills, spells, spellId);
339 if (!check.ok)
340 {
341 const error = new Error(check.reason);
342 error.userFacing = true;
343 throw error;
344 }
345 if (now < (casting.nextCastAt || 0))
346 {
347 const error = new Error("You are not ready to cast yet.");
348 error.userFacing = true;
349 throw error;
350 }
351 const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now);
352 if (!rangeCheck.ok)
353 {
354 const error = new Error(rangeCheck.reason);
355 error.userFacing = true;
356 throw error;
357 }
358
359 const levels = casterMagicLevels(world.ecs, handle, world.settings);
360 const difficulty = spellDifficulty(def);
361 const cast = resolveSpellCast({
362 magicSkillLevel: levels.magic,
363 spellDifficulty: difficulty
364 });
365
366 const events = [];
367 const from = world.ecs.get(handle, Component.position);
368 casting.armedSpellId = null;
369 casting.repeatSpellId = null;
370 casting.repeatTargetEntityId = null;
371 casting.nextCastAt = now + SPELL_COOLDOWN_MS;
372 events.push({
373 type: "spell-disarmed",
374 entityId,
375 characterId: character.characterId
376 });
377
378 if (!cast.success)
379 {
380 events.push({
381 type: "spell-fizzle",
382 casterId: entityId,
383 spellId,
384 fromTileX: from.tileX,
385 fromTileY: from.tileY,
386 tileX: target.tileX,
387 tileY: target.tileY
388 });
389 return { events };
390 }
391
392 const xpAward = awardSpellCastXp(world.ecs, handle, difficulty);
393 if (xpAward)
394 {
395 events.push({
396 type: "skills-updated",
397 entityId,
398 characterId: character.characterId,
399 skills: xpAward.view,
400 stored: xpAward.stored,
401 levelUps: xpAward.levelUps ?? []
402 });
403 }
404
405 const flashRadius = castFlashRadiusTiles(def.tier);
406 events.push({
407 type: "spell-cast-flash",
408 casterId: entityId,
409 tileX: from.tileX,
410 tileY: from.tileY,
411 radiusTiles: flashRadius,
412 durationMs: CAST_FLASH_MS,
413 tier: def.tier
414 });
415
416 world.pendingSpellImpacts.push({
417 executeAt: now + SPELL_PROJECTILE_MS,
418 casterEntityId: entityId,
419 casterCharacterId: character.characterId,
420 spellId,
421 targetTileX: target.tileX,
422 targetTileY: target.tileY,
423 targetEntityId: target.targetEntityId,
424 levels
425 });
426
427 events.push({
428 type: "spell-projectile",
429 casterId: entityId,
430 spellId,
431 targetId: target.targetEntityId ?? null,
432 fromTileX: from.tileX,
433 fromTileY: from.tileY,
434 tileX: target.tileX,
435 tileY: target.tileY,
436 durationMs: SPELL_PROJECTILE_MS,
437 sprite: def.projectileSprite
438 });
439
440 if (def.autoRepeat && spells.autoCast && target.targetEntityId != null)
441 {
442 casting.repeatSpellId = spellId;
443 casting.repeatTargetEntityId = target.targetEntityId;
444 }
445 else
446 {
447 casting.repeatSpellId = null;
448 casting.repeatTargetEntityId = null;
449 }
450
451 return { events };
452}
453
454function targetAffinitiesForEntity (world, entityId)
455{
456 if (entityId == null)
457 { return {}; }
458 const handle = world.ecs.handleOf(entityId);
459 if (handle == null)
460 { return {}; }
461 const creature = world.ecs.get(handle, Component.creature);
462 if (!creature)
463 { return {}; }
464 return mobElementAffinities(mobDefinition(creature.mobTypeId));
465}
466
467export function processSpellImpacts (world, now = Date.now())
468{
469 const queue = world.pendingSpellImpacts ?? [];
470 if (!queue.length)
471 { return []; }
472 const events = [];
473 const keep = [];
474 for (const impact of queue)
475 {
476 if (impact.executeAt > now)
477 {
478 keep.push(impact);
479 continue;
480 }
481 events.push(...applySpellImpact(world, impact, now));
482 }
483 world.pendingSpellImpacts = keep;
484 return events;
485}
486
487function applySpellImpact (world, impact, now)
488{
489 const def = spellDefinition(impact.spellId);
490 if (!def)
491 { return []; }
492 const events = [];
493 events.push({
494 type: "spell-cast-flash",
495 casterId: impact.casterEntityId,
496 tileX: impact.targetTileX,
497 tileY: impact.targetTileY,
498 radiusTiles: castFlashRadiusTiles(def.tier),
499 durationMs: CAST_FLASH_MS,
500 tier: def.tier
501 });
502
503 if (impact.spellId === SpellId.light)
504 {
505 world.spellLights = world.spellLights ?? new SpellLightRegistry();
506 const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;
507 const durationMs = mindRoll * LIGHT_DURATION_MS_PER_MIND;
508 const { light, extended } = world.spellLights.placeOrExtend({
509 tileX: impact.targetTileX,
510 tileY: impact.targetTileY,
511 ownerEntityId: impact.casterEntityId,
512 durationMs,
513 now
514 });
515 events.push({
516 type: extended ? "spell-light-update" : "spell-light-appear",
517 ...publicSpellLight(light, now)
518 });
519 return events;
520 }
521
522 if (impact.spellId === SpellId.spark && impact.targetEntityId != null)
523 {
524 const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);
525 const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;
526 let multiplier = ElementMultiplier.neutral;
527 const affinity = affinities[def.element ?? "fire"];
528 if (affinity === "weak")
529 { multiplier = ElementMultiplier.weak; }
530 else if (affinity === "resistant")
531 { multiplier = ElementMultiplier.resistant; }
532 const damage = Math.max(1, Math.floor(mindRoll * multiplier));
533 events.push(...applyDamageAndKill(
534 world,
535 impact.casterEntityId,
536 impact.targetEntityId,
537 damage,
538 now
539 ));
540 const casterHandle = world.ecs.handleOf(impact.casterEntityId);
541 if (casterHandle != null && impact.casterCharacterId)
542 {
543 const xp = awardCombatHitXp(world.ecs, casterHandle, MAGIC_ATTACK_PROFILE, damage);
544 if (xp)
545 {
546 events.push({
547 type: "skills-updated",
548 entityId: impact.casterEntityId,
549 characterId: impact.casterCharacterId,
550 skills: xp.view,
551 stored: xp.stored,
552 levelUps: xp.levelUps ?? []
553 });
554 }
555 }
556 }
557 return events;
558}
559
560export function stepPendingSpellCast (world, now = Date.now())
561{
562 const events = [];
563 for (const entity of world.ecs.query(Component.spellcasting, Component.character, Component.networkIdentity))
564 {
565 const casting = entity.spellcasting;
566 if (!casting?.pendingCast)
567 { continue; }
568 const pending = casting.pendingCast;
569 const target = resolvePendingCastTarget(world, pending);
570 if (!target)
571 {
572 casting.pendingCast = null;
573 continue;
574 }
575 const rangeCheck = validateCastRange(world, entity.handle, target.tileX, target.tileY, now);
576 if (!rangeCheck.ok)
577 {
578 const minStandDist = target.targetEntityId != null ? 1 : 0;
579 queueSpellApproach(world, entity.handle, entity.entityId, target, minStandDist);
580 continue;
581 }
582 casting.pendingCast = null;
583 const result = executeCast(
584 world,
585 entity.networkIdentity.sessionId,
586 entity.character.characterId,
587 pending.spellId,
588 target,
589 now
590 );
591 events.push(...(result.events ?? []));
592 }
593 return events;
594}
595
596export function stepSpellAutoCast (world, now = Date.now())
597{
598 const events = [];
599 for (const entity of world.ecs.query(Component.spellcasting, Component.spells, Component.character))
600 {
601 const casting = entity.spellcasting;
602 const spells = entity.spells;
603 if (!spells.autoCast || !casting.repeatSpellId || casting.repeatTargetEntityId == null)
604 { continue; }
605 if (now < (casting.nextCastAt || 0))
606 { continue; }
607 const def = spellDefinition(casting.repeatSpellId);
608 if (!def?.autoRepeat)
609 { continue; }
610 const target = resolveCombatTarget(world, casting.repeatTargetEntityId);
611 if (!target || (target.health && target.health.current <= 0))
612 {
613 casting.repeatSpellId = null;
614 casting.repeatTargetEntityId = null;
615 continue;
616 }
617 const range = validateCastRange(world, entity.handle, target.pos.tileX, target.pos.tileY, now);
618 if (!range.ok)
619 { continue; }
620 const sessionId = entity.networkIdentity?.sessionId;
621 if (!sessionId)
622 { continue; }
623 const result = executeCast(
624 world,
625 sessionId,
626 entity.character.characterId,
627 casting.repeatSpellId,
628 {
629 tileX: target.pos.tileX,
630 tileY: target.pos.tileY,
631 targetEntityId: casting.repeatTargetEntityId
632 },
633 now
634 );
635 events.push(...(result.events ?? []));
636 }
637 return events;
638}
639
640export function tickSpellLights (world, now = Date.now())
641{
642 if (!world.spellLights)
643 { return []; }
644 return world.spellLights.tick(world, now);
645}
646
647function readSpellbook (world, sessionId, command, now)
648{
649 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
650 ensureSpellComponents(world.ecs, handle);
651 const inventory = world.ecs.get(handle, Component.inventory);
652 const slotIndex = command.slotIndex | 0;
653 const slot = inventory?.slots?.[slotIndex];
654 if (!slot?.instance || slot.instance.kind !== "spellbook")
655 {
656 const error = new Error("That is not a spellbook.");
657 error.userFacing = true;
658 throw error;
659 }
660 const spellId = slot.instance.spellId;
661 const spells = world.ecs.get(handle, Component.spells);
662 const skills = world.ecs.get(handle, Component.skills);
663 const learned = learnSpell(spells, spellId);
664 if (!learned.changed)
665 {
666 const error = new Error("You already know that spell.");
667 error.userFacing = true;
668 throw error;
669 }
670 Object.assign(spells, learned.spells);
671 inventory.slots[slotIndex] = null;
672 const events = [
673 spellsUpdatedEvent(entityId, character.characterId, spells, skills)
674 ];
675 return {
676 events,
677 private: bagView(world.ecs, handle)
678 };
679}
680
681export function createSpellbookStack (spellId)
682{
683 const instance = spellbookInstance(spellId);
684 if (!instance)
685 { return null; }
686 const itemId = spellId === SpellId.spark
687 ? SpellbookItemId.sparkSpellbook
688 : null;
689 if (itemId == null)
690 { return null; }
691 return { itemId, quantity: 1, instance };
692}