BlueGit

timfa questward

Files

questward / server / src / spells / service.js

service.js

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