BlueGit

timfa questward

Files

questward / server / src / spells / service.js

service.js

service.js 28.6 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{
6 canCastSpell,
7 defaultPlayerSpells,
8 normalizePlayerSpells,
9 publicSpellsView,
10 storedPlayerSpells,
11 toggleFavorite,
12 learnSpell
13} from "../../../shared/spells/state.js";
14import
15{
16 CAST_FLASH_MS,
17 COMBAT_RANGE_TILES,
18 LIGHT_DURATION_MS_PER_MIND,
19 SPELL_COOLDOWN_MS,
20 SPELL_LIGHT_RANGE_TILES,
21 SPELL_PROJECTILE_MS,
22 castFlashRadiusTiles
23} from "../../../shared/spells/constants.js";
24import
25{
26 mobDamageAffinities,
27 mobElementAffinities,
28 ElementMultiplier,
29 resolveMagicAttack,
30 resolveSpellCast,
31 resolveSpellPotency
32} from "../../../shared/combat/magic.js";
33import { mobDefinition } from "../../../shared/definitions/mobs.js";
34import { awardCombatHitXp, awardDamageHealthXp, awardSpellCastXp, syncPlayerHealth } from "../skills/service.js";
35import { equipmentBonusesFromSlots, effectiveSkillLevel } from "../../../shared/equipment/stats.js";
36import { statusSkillBonuses, applyStatusEffect, emptyStatusEffects, StatusEffectType, publicStatusEffectsView, hasStatusEffect } from "../../../shared/statusEffects/rules.js";
37import
38{
39 chebyshev,
40 clearEngage,
41 hasCombatLineOfSight,
42 queueStandInRangeApproach,
43 resolveCombatTarget,
44 applyDamageAndKill
45} from "../combat/service.js";
46import { publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
47import { spellCastXpFromDifficulty } from "../../../shared/skills/progression.js";
48import { publicSpellLight, SpellLightRegistry } from "./lights.js";
49import { spellbookInstance, spellbookItemIdForSpell, spellIdFromSpellbookStack } from "../../../shared/definitions/spellItems.js";
50import { itemDefinition } from "../../../shared/definitions/items.js";
51import { bagView } from "../items/bags.js";
52import { applyTindersAtTile, tindersTileStillNeedsCast } from "./tinders.js";
53
54const MAGIC_ATTACK_PROFILE = Object.freeze({
55 hitSkillId: SkillId.magic,
56 damageSkillId: SkillId.mind
57});
58
59export function ensureSpellComponents (ecs, handle, storedSpells = null)
60{
61 if (!ecs.get(handle, Component.spells))
62 {
63 ecs.add(handle, Component.spells, normalizePlayerSpells(storedSpells ?? defaultPlayerSpells()));
64 }
65 if (!ecs.get(handle, Component.spellcasting))
66 {
67 ecs.add(handle, Component.spellcasting, emptySpellcasting());
68 }
69 else
70 { normalizeSpellcasting(ecs.get(handle, Component.spellcasting)); }
71}
72
73export function emptySpellcasting ()
74{
75 return {
76 armedSpellId: null,
77 repeatSpellId: null,
78 repeatTargetEntityId: null,
79 repeatTileX: null,
80 repeatTileY: null,
81 nextCastAt: 0,
82 pendingCast: null
83 };
84}
85
86function normalizeSpellcasting (casting)
87{
88 if (!casting)
89 { return; }
90 if (!("repeatTileX" in casting))
91 { casting.repeatTileX = null; }
92 if (!("repeatTileY" in casting))
93 { casting.repeatTileY = null; }
94}
95
96/** Clear auto-repeat / pending cast state (move, melee, cancel, …). */
97export function clearSpellAutoRepeat (casting)
98{
99 if (!casting)
100 { return; }
101 casting.repeatSpellId = null;
102 casting.repeatTargetEntityId = null;
103 casting.repeatTileX = null;
104 casting.repeatTileY = null;
105 casting.pendingCast = null;
106}
107
108function stopCasterMovement (world, handle, entityId)
109{
110 clearEngage(world.ecs, entityId);
111 const path = world.ecs.get(handle, Component.path);
112 if (path?.tiles?.length)
113 { path.tiles = []; }
114 const movement = world.ecs.get(handle, Component.movement);
115 if (movement)
116 { movement.walkCarry = 0; }
117}
118
119export function handleSpellCommand (world, sessionId, command, now = Date.now())
120{
121 switch (command.type)
122 {
123 case "set-spell-favorite":
124 return setSpellFavorite(world, sessionId, command, now);
125 case "set-spell-autocast":
126 return setSpellAutoCast(world, sessionId, command, now);
127 case "arm-spell":
128 return armSpell(world, sessionId, command, now);
129 case "cancel-arm-spell":
130 return cancelArmSpell(world, sessionId, command, now);
131 case "cast-spell-tile":
132 return castSpellAtTile(world, sessionId, command, now);
133 case "cast-spell-entity":
134 return castSpellAtEntity(world, sessionId, command, now);
135 case "read-spellbook":
136 return readSpellbook(world, sessionId, command, now);
137 default:
138 return null;
139 }
140}
141
142function requirePlayer (world, sessionId, characterId)
143{
144 for (const entity of world.ecs.query(Component.networkIdentity, Component.character))
145 {
146 if (entity.networkIdentity.sessionId !== sessionId)
147 { continue; }
148 if (entity.character.characterId !== characterId)
149 { continue; }
150 if (world.ecs.has(entity.handle, Component.dead))
151 {
152 const error = new Error("You are dead.");
153 error.userFacing = true;
154 throw error;
155 }
156 return { handle: entity.handle, entityId: entity.entityId, character: entity.character };
157 }
158 const error = new Error("Character not found.");
159 error.userFacing = true;
160 throw error;
161}
162
163function spellsUpdatedEvent (entityId, characterId, spells, skills, levelUps = [])
164{
165 return {
166 type: "spells-updated",
167 entityId,
168 characterId,
169 spells: publicSpellsView(spells, skills),
170 stored: storedPlayerSpells(spells),
171 autoCast: !!spells.autoCast,
172 levelUps
173 };
174}
175
176function setSpellFavorite (world, sessionId, command, now)
177{
178 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
179 ensureSpellComponents(world.ecs, handle);
180 const skills = world.ecs.get(handle, Component.skills);
181 const spells = world.ecs.get(handle, Component.spells);
182 const result = toggleFavorite(spells, command.spellId, skills);
183 if (result.error)
184 {
185 const error = new Error(result.error);
186 error.userFacing = true;
187 throw error;
188 }
189 Object.assign(spells, result.spells);
190 const events = [];
191 if (result.changed)
192 {
193 events.push(spellsUpdatedEvent(entityId, character.characterId, spells, skills));
194 }
195 return { events };
196}
197
198function setSpellAutoCast (world, sessionId, command, now)
199{
200 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
201 ensureSpellComponents(world.ecs, handle);
202 const skills = world.ecs.get(handle, Component.skills);
203 const spells = world.ecs.get(handle, Component.spells);
204 spells.autoCast = !!command.enabled;
205 const casting = world.ecs.get(handle, Component.spellcasting);
206 if (!spells.autoCast)
207 { clearSpellAutoRepeat(casting); }
208 return {
209 events: [spellsUpdatedEvent(entityId, character.characterId, spells, skills)]
210 };
211}
212
213function armSpell (world, sessionId, command, now)
214{
215 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
216 ensureSpellComponents(world.ecs, handle);
217 const skills = world.ecs.get(handle, Component.skills);
218 const spells = world.ecs.get(handle, Component.spells);
219 const check = canCastSpell(skills, spells, command.spellId);
220 if (!check.ok)
221 {
222 const error = new Error(check.reason);
223 error.userFacing = true;
224 throw error;
225 }
226 const casting = world.ecs.get(handle, Component.spellcasting);
227 casting.armedSpellId = command.spellId;
228 casting.pendingCast = null;
229 /** Re-arming the active auto-repeat spell must not cancel it (favourite bar clicks). */
230 if (casting.repeatSpellId != null && casting.repeatSpellId !== command.spellId)
231 {
232 casting.repeatSpellId = null;
233 casting.repeatTargetEntityId = null;
234 casting.repeatTileX = null;
235 casting.repeatTileY = null;
236 }
237 return {
238 events: [{
239 type: "spell-armed",
240 entityId,
241 characterId: character.characterId,
242 spellId: command.spellId
243 }]
244 };
245}
246
247function cancelArmSpell (world, sessionId, command)
248{
249 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
250 const casting = world.ecs.get(handle, Component.spellcasting);
251 if (!casting)
252 { return { events: [] }; }
253 casting.armedSpellId = null;
254 casting.pendingCast = null;
255 /**
256 * Do not clear auto-repeat here. Cast already disarms then sets repeat; a late
257 * cancel-arm (right-click while the client still thought it was armed) used to
258 * wipe that repeat and leave the player falling back to melee.
259 */
260 return {
261 events: [{
262 type: "spell-disarmed",
263 entityId,
264 characterId: character.characterId
265 }]
266 };
267}
268
269function casterMagicLevels (ecs, handle, settings = null)
270{
271 const skills = ecs.get(handle, Component.skills);
272 const equipment = ecs.get(handle, Component.equipment);
273 const bonuses = equipmentBonusesFromSlots(equipment?.slots, settings);
274 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
275 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
276 return {
277 magic: effectiveSkillLevel(skills, SkillId.magic, bonuses),
278 mind: effectiveSkillLevel(skills, SkillId.mind, bonuses)
279 };
280}
281
282function validateCastRange (world, handle, tileX, tileY, now)
283{
284 const pos = world.ecs.get(handle, Component.position);
285 if (!pos)
286 { return { ok: false, reason: "You are not in the world." }; }
287 const dist = chebyshev(pos.tileX, pos.tileY, tileX, tileY);
288 if (dist > COMBAT_RANGE_TILES)
289 { return { ok: false, reason: "That is out of range." }; }
290 if (!hasCombatLineOfSight(world, pos.tileX, pos.tileY, tileX, tileY))
291 { return { ok: false, reason: "You cannot see that spot." }; }
292 return { ok: true };
293}
294
295function resolvePendingCastTarget (world, pending)
296{
297 if (pending.targetEntityId == null)
298 {
299 return {
300 tileX: pending.tileX | 0,
301 tileY: pending.tileY | 0,
302 targetEntityId: null
303 };
304 }
305 const target = resolveCombatTarget(world, pending.targetEntityId);
306 if (!target)
307 { return null; }
308 return {
309 tileX: target.pos.tileX,
310 tileY: target.pos.tileY,
311 targetEntityId: pending.targetEntityId
312 };
313}
314
315function queueSpellApproach (world, handle, entityId, target, minStandDist)
316{
317 const position = world.ecs.get(handle, Component.position);
318 if (!position)
319 { return; }
320 queueStandInRangeApproach(
321 world,
322 entityId,
323 handle,
324 position,
325 target.tileX,
326 target.tileY,
327 COMBAT_RANGE_TILES,
328 minStandDist
329 );
330}
331
332function beginCastOrApproach (world, sessionId, characterId, spellId, target, now, minStandDist = 0)
333{
334 const { handle, entityId } = requirePlayer(world, sessionId, characterId);
335 ensureSpellComponents(world.ecs, handle);
336 const casting = world.ecs.get(handle, Component.spellcasting);
337 stopCasterMovement(world, handle, entityId);
338 const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now);
339 if (!rangeCheck.ok)
340 {
341 casting.pendingCast = {
342 spellId,
343 tileX: target.tileX,
344 tileY: target.tileY,
345 targetEntityId: target.targetEntityId ?? null
346 };
347 queueSpellApproach(world, handle, entityId, target, minStandDist);
348 return { events: [] };
349 }
350 casting.pendingCast = null;
351 return executeCast(world, sessionId, characterId, spellId, target, now);
352}
353
354function castSpellAtTile (world, sessionId, command, now)
355{
356 const spellId = command.spellId;
357 const def = spellDefinition(spellId);
358 if (!def || def.target !== "tile")
359 {
360 const error = new Error("That spell needs a different target.");
361 error.userFacing = true;
362 throw error;
363 }
364 return beginCastOrApproach(world, sessionId, command.characterId, spellId, {
365 tileX: command.tileX | 0,
366 tileY: command.tileY | 0,
367 targetEntityId: null
368 }, now, 0);
369}
370
371function castSpellAtEntity (world, sessionId, command, now)
372{
373 const spellId = command.spellId;
374 const def = spellDefinition(spellId);
375 if (!def || def.target !== "entity")
376 {
377 const error = new Error("That spell needs a tile target.");
378 error.userFacing = true;
379 throw error;
380 }
381 const { entityId: casterEntityId } = requirePlayer(world, sessionId, command.characterId);
382 const target = resolveCombatTarget(world, command.targetEntityId);
383 if (!target)
384 {
385 const error = new Error("Target is not here.");
386 error.userFacing = true;
387 throw error;
388 }
389 const selfTarget = command.targetEntityId === casterEntityId;
390 return beginCastOrApproach(world, sessionId, command.characterId, spellId, {
391 tileX: target.pos.tileX,
392 tileY: target.pos.tileY,
393 targetEntityId: command.targetEntityId
394 }, now, selfTarget ? 0 : 1);
395}
396
397function executeCast (world, sessionId, characterId, spellId, target, now)
398{
399 const { handle, entityId, character } = requirePlayer(world, sessionId, characterId);
400 ensureSpellComponents(world.ecs, handle);
401 const skills = world.ecs.get(handle, Component.skills);
402 const spells = world.ecs.get(handle, Component.spells);
403 const casting = world.ecs.get(handle, Component.spellcasting);
404 const def = spellDefinition(spellId);
405 const check = canCastSpell(skills, spells, spellId);
406 if (!check.ok)
407 {
408 const error = new Error(check.reason);
409 error.userFacing = true;
410 throw error;
411 }
412 if (now < (casting.nextCastAt || 0))
413 {
414 const error = new Error("You are not ready to cast yet.");
415 error.userFacing = true;
416 throw error;
417 }
418 const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now);
419 if (!rangeCheck.ok)
420 {
421 const error = new Error(rangeCheck.reason);
422 error.userFacing = true;
423 throw error;
424 }
425
426 stopCasterMovement(world, handle, entityId);
427
428 const levels = casterMagicLevels(world.ecs, handle, world.settings);
429 const difficulty = spellDifficulty(def);
430 const cast = resolveSpellCast({
431 magicSkillLevel: levels.magic,
432 spellDifficulty: difficulty
433 });
434
435 const events = [];
436 const from = world.ecs.get(handle, Component.position);
437 casting.armedSpellId = null;
438 casting.nextCastAt = now + SPELL_COOLDOWN_MS;
439 events.push({
440 type: "spell-disarmed",
441 entityId,
442 characterId: character.characterId
443 });
444
445 // Keep / refresh auto-repeat even on fizzle so we keep trying until cancelled.
446 rememberAutoRepeat(casting, spells, def, spellId, target);
447
448 if (!cast.success)
449 {
450 events.push({
451 type: "spell-fizzle",
452 casterId: entityId,
453 spellId,
454 fromTileX: from.tileX,
455 fromTileY: from.tileY,
456 tileX: target.tileX,
457 tileY: target.tileY
458 });
459 return { events };
460 }
461
462 const xpAward = awardSpellCastXp(world.ecs, handle, difficulty);
463 if (xpAward)
464 {
465 events.push({
466 type: "skills-updated",
467 entityId,
468 characterId: character.characterId,
469 skills: xpAward.view,
470 stored: xpAward.stored,
471 levelUps: xpAward.levelUps ?? []
472 });
473 }
474
475 const flashRadius = castFlashRadiusTiles(def.tier);
476 events.push({
477 type: "spell-cast-flash",
478 casterId: entityId,
479 tileX: from.tileX,
480 tileY: from.tileY,
481 radiusTiles: flashRadius,
482 durationMs: CAST_FLASH_MS,
483 tier: def.tier
484 });
485
486 world.pendingSpellImpacts.push({
487 executeAt: now + SPELL_PROJECTILE_MS,
488 casterEntityId: entityId,
489 casterCharacterId: character.characterId,
490 spellId,
491 targetTileX: target.tileX,
492 targetTileY: target.tileY,
493 targetEntityId: target.targetEntityId,
494 levels
495 });
496
497 events.push({
498 type: "spell-projectile",
499 casterId: entityId,
500 spellId,
501 targetId: target.targetEntityId ?? null,
502 fromTileX: from.tileX,
503 fromTileY: from.tileY,
504 tileX: target.tileX,
505 tileY: target.tileY,
506 durationMs: SPELL_PROJECTILE_MS,
507 sprite: def.projectileSprite
508 });
509
510 return { events };
511}
512
513function rememberAutoRepeat (casting, spells, def, spellId, target)
514{
515 if (!casting || !spells?.autoCast || !def?.autoRepeat)
516 {
517 clearSpellAutoRepeat(casting);
518 return;
519 }
520 if (def.target === "entity" && target?.targetEntityId != null)
521 {
522 casting.repeatSpellId = spellId;
523 casting.repeatTargetEntityId = target.targetEntityId | 0;
524 casting.repeatTileX = null;
525 casting.repeatTileY = null;
526 casting.pendingCast = null;
527 return;
528 }
529 if (def.target === "tile")
530 {
531 casting.repeatSpellId = spellId;
532 casting.repeatTargetEntityId = null;
533 casting.repeatTileX = target.tileX | 0;
534 casting.repeatTileY = target.tileY | 0;
535 casting.pendingCast = null;
536 return;
537 }
538 clearSpellAutoRepeat(casting);
539}
540
541function targetAffinitiesForEntity (world, entityId)
542{
543 if (entityId == null)
544 { return {}; }
545 const handle = world.ecs.handleOf(entityId);
546 if (handle == null)
547 { return {}; }
548 const creature = world.ecs.get(handle, Component.creature);
549 if (!creature)
550 { return {}; }
551 return mobDamageAffinities(mobDefinition(creature.mobTypeId));
552}
553
554function applySpellImpact (world, impact, now)
555{
556 const def = spellDefinition(impact.spellId);
557 if (!def)
558 { return []; }
559 const events = [];
560 events.push({
561 type: "spell-cast-flash",
562 casterId: impact.casterEntityId,
563 tileX: impact.targetTileX,
564 tileY: impact.targetTileY,
565 radiusTiles: castFlashRadiusTiles(def.tier),
566 durationMs: CAST_FLASH_MS,
567 tier: def.tier
568 });
569
570 const effect = def.effect ?? impact.spellId;
571 if (effect === "light" || effect === "dark")
572 {
573 events.push(...applyLightOrDarkImpact(world, impact, def, effect, now));
574 return events;
575 }
576 if (effect === "damage")
577 {
578 events.push(...applyDamageSpellImpact(world, impact, def, now));
579 return events;
580 }
581 if (effect === "poison")
582 {
583 events.push(...applyPoisonImpact(world, impact, def, now));
584 return events;
585 }
586 if (effect === "drain")
587 {
588 events.push(...applyDrainImpact(world, impact, now));
589 return events;
590 }
591 if (effect === "revitalize")
592 {
593 events.push(...applyRevitalizeImpact(world, impact, now));
594 return events;
595 }
596 if (effect === "tinders")
597 {
598 events.push(...applyTindersImpact(world, impact, now));
599 return events;
600 }
601 if (effect === "shade")
602 {
603 events.push(...applyShadeImpact(world, impact, now));
604 return events;
605 }
606 return events;
607}
608
609function mindRollOf (impact)
610{
611 return resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;
612}
613
614function applyLightOrDarkImpact (world, impact, def, effect, now)
615{
616 const events = [];
617 world.spellLights = world.spellLights ?? new SpellLightRegistry();
618 const mindRoll = mindRollOf(impact);
619 const durationMs = Math.max(1, mindRoll) * LIGHT_DURATION_MS_PER_MIND;
620 const baseRange = mindRoll === 0
621 ? SPELL_LIGHT_RANGE_TILES * 0.5
622 : SPELL_LIGHT_RANGE_TILES;
623 const kind = effect === "dark" ? "dark" : "light";
624 const { light, extended } = world.spellLights.placeOrExtend({
625 tileX: impact.targetTileX,
626 tileY: impact.targetTileY,
627 ownerEntityId: impact.casterEntityId,
628 durationMs,
629 baseRange,
630 kind,
631 now
632 });
633 const appear = kind === "dark"
634 ? (extended ? "spell-dark-update" : "spell-dark-appear")
635 : (extended ? "spell-light-update" : "spell-light-appear");
636 events.push({ type: appear, ...publicSpellLight(light, now) });
637 return events;
638}
639
640function elementalDamageMultiplier (def, affinities)
641{
642 let multiplier = ElementMultiplier.neutral;
643 const affinity = affinities[def.element ?? "none"];
644 if (affinity === "weak")
645 { multiplier = ElementMultiplier.weak; }
646 else if (affinity === "resistant")
647 { multiplier = ElementMultiplier.resistant; }
648 return multiplier;
649}
650
651function applyDamageSpellImpact (world, impact, def, now)
652{
653 if (impact.targetEntityId == null)
654 { return []; }
655 const events = [];
656 const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);
657 const mindRoll = mindRollOf(impact);
658 const multiplier = elementalDamageMultiplier(def, affinities);
659 const damage = Math.max(1, Math.floor(mindRoll * multiplier));
660 events.push(...applyDamageAndKill(
661 world,
662 impact.casterEntityId,
663 impact.targetEntityId,
664 damage,
665 now
666 ));
667 events.push(...awardMagicHitXp(world, impact, damage));
668 return events;
669}
670
671function awardMagicHitXp (world, impact, damage)
672{
673 const events = [];
674 const casterHandle = world.ecs.handleOf(impact.casterEntityId);
675 if (casterHandle == null || !impact.casterCharacterId)
676 { return events; }
677 const xp = awardCombatHitXp(world.ecs, casterHandle, MAGIC_ATTACK_PROFILE, damage);
678 if (xp)
679 {
680 events.push({
681 type: "skills-updated",
682 entityId: impact.casterEntityId,
683 characterId: impact.casterCharacterId,
684 skills: xp.view,
685 stored: xp.stored,
686 levelUps: xp.levelUps ?? []
687 });
688 }
689 return events;
690}
691
692function ensureEntityStatusEffects (ecs, handle)
693{
694 let component = ecs.get(handle, Component.statusEffects);
695 if (!component)
696 { component = ecs.add(handle, Component.statusEffects, emptyStatusEffects()); }
697 return component;
698}
699
700function applyPoisonImpact (world, impact, def, now)
701{
702 if (impact.targetEntityId == null)
703 { return []; }
704 const target = resolveCombatTarget(world, impact.targetEntityId);
705 if (!target?.local || target.handle == null)
706 { return []; }
707 const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);
708 const mindRoll = mindRollOf(impact);
709 const multiplier = elementalDamageMultiplier(def, affinities);
710 const total = Math.max(1, Math.floor(mindRoll * multiplier * 2));
711 const durationMs = total * 1000;
712 const status = ensureEntityStatusEffects(world.ecs, target.handle);
713 applyStatusEffect(status, {
714 type: StatusEffectType.healthDrain,
715 durationMs,
716 amountPerSecond: 1
717 }, now);
718 return [{
719 type: "status-effects-entity",
720 entityId: impact.targetEntityId,
721 effects: publicStatusEffectsView(status, now)
722 }];
723}
724
725function applyDrainImpact (world, impact, now)
726{
727 if (impact.targetEntityId == null)
728 { return []; }
729 const target = resolveCombatTarget(world, impact.targetEntityId);
730 if (!target?.local || target.handle == null)
731 { return []; }
732 if (!world.ecs.get(target.handle, Component.stamina))
733 { return []; }
734 const mindRoll = mindRollOf(impact);
735 const durationMs = Math.max(1000, mindRoll * 3 * 1000);
736 const status = ensureEntityStatusEffects(world.ecs, target.handle);
737 applyStatusEffect(status, {
738 type: StatusEffectType.staminaDrain,
739 durationMs,
740 amountPerSecond: 1
741 }, now);
742 applyStatusEffect(status, {
743 type: StatusEffectType.staminaBlock,
744 durationMs,
745 amountPerSecond: 0
746 }, now);
747 const character = world.ecs.get(target.handle, Component.character);
748 const events = [{
749 type: "status-effects-entity",
750 entityId: impact.targetEntityId,
751 effects: publicStatusEffectsView(status, now)
752 }];
753 if (character?.characterId)
754 {
755 events.push({
756 type: "status-effects",
757 characterId: character.characterId,
758 effects: publicStatusEffectsView(status, now),
759 blind: hasStatusEffect(status, StatusEffectType.blind, now)
760 });
761 }
762 return events;
763}
764
765function applyRevitalizeImpact (world, impact, now)
766{
767 if (impact.targetEntityId == null)
768 { return []; }
769 const target = resolveCombatTarget(world, impact.targetEntityId);
770 if (!target?.local || target.handle == null)
771 { return []; }
772 if (!world.ecs.get(target.handle, Component.health))
773 { return []; }
774 const mindRoll = mindRollOf(impact);
775 const healTotal = Math.max(1, mindRoll);
776 const durationMs = healTotal * 1000;
777 const status = ensureEntityStatusEffects(world.ecs, target.handle);
778 applyStatusEffect(status, {
779 type: StatusEffectType.healthRegen,
780 durationMs,
781 amountPerSecond: 1
782 }, now);
783 const character = world.ecs.get(target.handle, Component.character);
784 const events = [{
785 type: "status-effects-entity",
786 entityId: impact.targetEntityId,
787 effects: publicStatusEffectsView(status, now)
788 }];
789 if (character?.characterId)
790 {
791 events.push({
792 type: "status-effects",
793 characterId: character.characterId,
794 effects: publicStatusEffectsView(status, now),
795 blind: hasStatusEffect(status, StatusEffectType.blind, now)
796 });
797 }
798 return events;
799}
800
801function applyTindersImpact (world, impact, now)
802{
803 const events = applyTindersAtTile(world, impact, now);
804 const casterHandle = world.ecs.handleOf(impact.casterEntityId);
805 const sessionId = casterHandle != null
806 ? world.ecs.get(casterHandle, Component.networkIdentity)?.sessionId
807 : null;
808 for (const event of events)
809 {
810 if (event.type === "command-error" && sessionId != null)
811 { event.sessionId = sessionId; }
812 }
813 return events;
814}
815
816function applyShadeImpact (world, impact, now)
817{
818 const mindRoll = mindRollOf(impact);
819 const durationMs = Math.max(1000, mindRoll * 3 * 1000);
820 const casterHandle = world.ecs.handleOf(impact.casterEntityId);
821 const mindLevel = impact.levels?.mind | 0 || 1;
822 const level = Math.max(1, Math.min(99, Math.floor(mindLevel * 0.75)));
823 return [{
824 type: "summon-entity",
825 ownerEntityId: impact.casterEntityId,
826 ownerCharacterId: impact.casterCharacterId ?? null,
827 tileX: impact.targetTileX,
828 tileY: impact.targetTileY,
829 level,
830 expiresAt: now + durationMs,
831 mobTypeId: "shade"
832 }];
833}
834
835export function processSpellImpacts (world, now = Date.now())
836{
837 const queue = world.pendingSpellImpacts ?? [];
838 if (!queue.length)
839 { return []; }
840 const events = [];
841 const keep = [];
842 for (const impact of queue)
843 {
844 if (impact.executeAt > now)
845 {
846 keep.push(impact);
847 continue;
848 }
849 events.push(...applySpellImpact(world, impact, now));
850 }
851 world.pendingSpellImpacts = keep;
852 return events;
853}
854
855export function stepPendingSpellCast (world, now = Date.now())
856{
857 const events = [];
858 for (const entity of world.ecs.query(Component.spellcasting, Component.character, Component.networkIdentity))
859 {
860 if (world.ecs.has(entity.handle, Component.dead))
861 {
862 if (entity.spellcasting)
863 { entity.spellcasting.pendingCast = null; }
864 continue;
865 }
866 const casting = entity.spellcasting;
867 if (!casting?.pendingCast)
868 { continue; }
869 const pending = casting.pendingCast;
870 const target = resolvePendingCastTarget(world, pending);
871 if (!target)
872 {
873 casting.pendingCast = null;
874 continue;
875 }
876 const rangeCheck = validateCastRange(world, entity.handle, target.tileX, target.tileY, now);
877 if (!rangeCheck.ok)
878 {
879 const minStandDist = target.targetEntityId != null ? 1 : 0;
880 queueSpellApproach(world, entity.handle, entity.entityId, target, minStandDist);
881 continue;
882 }
883 casting.pendingCast = null;
884 const result = executeCast(
885 world,
886 entity.networkIdentity.sessionId,
887 entity.character.characterId,
888 pending.spellId,
889 target,
890 now
891 );
892 events.push(...(result.events ?? []));
893 }
894 return events;
895}
896
897export function stepSpellAutoCast (world, now = Date.now())
898{
899 const events = [];
900 for (const entity of world.ecs.query(
901 Component.spellcasting,
902 Component.spells,
903 Component.character,
904 Component.networkIdentity
905 ))
906 {
907 if (world.ecs.has(entity.handle, Component.dead))
908 {
909 clearSpellAutoRepeat(entity.spellcasting);
910 continue;
911 }
912 const casting = entity.spellcasting;
913 const spells = entity.spells;
914 normalizeSpellcasting(casting);
915 if (!spells.autoCast || !casting.repeatSpellId)
916 { continue; }
917 if (now < (casting.nextCastAt || 0))
918 { continue; }
919 const def = spellDefinition(casting.repeatSpellId);
920 if (!def?.autoRepeat)
921 {
922 clearSpellAutoRepeat(casting);
923 continue;
924 }
925
926 const sessionId = entity.networkIdentity.sessionId;
927 if (!sessionId)
928 { continue; }
929
930 let target = null;
931 let minStandDist = 0;
932 if (casting.repeatTargetEntityId != null)
933 {
934 const resolved = resolveCombatTarget(world, casting.repeatTargetEntityId);
935 if (!resolved || (resolved.health && resolved.health.current <= 0))
936 {
937 clearSpellAutoRepeat(casting);
938 continue;
939 }
940 target = {
941 tileX: resolved.pos.tileX,
942 tileY: resolved.pos.tileY,
943 targetEntityId: casting.repeatTargetEntityId
944 };
945 minStandDist = casting.repeatTargetEntityId === entity.entityId ? 0 : 1;
946 }
947 else if (casting.repeatTileX != null && casting.repeatTileY != null)
948 {
949 if (!tileAutoCastStillValid(world, casting.repeatSpellId, casting.repeatTileX, casting.repeatTileY))
950 {
951 clearSpellAutoRepeat(casting);
952 continue;
953 }
954 target = {
955 tileX: casting.repeatTileX | 0,
956 tileY: casting.repeatTileY | 0,
957 targetEntityId: null
958 };
959 minStandDist = 0;
960 }
961 else
962 {
963 clearSpellAutoRepeat(casting);
964 continue;
965 }
966
967 const range = validateCastRange(world, entity.handle, target.tileX, target.tileY, now);
968 if (!range.ok)
969 {
970 queueSpellApproach(world, entity.handle, entity.entityId, target, minStandDist);
971 continue;
972 }
973
974 const result = executeCast(
975 world,
976 sessionId,
977 entity.character.characterId,
978 casting.repeatSpellId,
979 target,
980 now
981 );
982 events.push(...(result.events ?? []));
983 }
984 return events;
985}
986
987function tileAutoCastStillValid (world, spellId, tileX, tileY)
988{
989 const def = spellDefinition(spellId);
990 if (!def)
991 { return false; }
992 if (def.effect === "tinders")
993 { return tindersTileStillNeedsCast(world, tileX, tileY); }
994 return true;
995}
996
997export function tickSpellLights (world, now = Date.now())
998{
999 if (!world.spellLights)
1000 { return []; }
1001 return world.spellLights.tick(world, now);
1002}
1003
1004function readSpellbook (world, sessionId, command, now)
1005{
1006 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
1007 ensureSpellComponents(world.ecs, handle);
1008 const inventory = world.ecs.get(handle, Component.inventory);
1009 const slotIndex = command.slotIndex | 0;
1010 const slot = inventory?.slots?.[slotIndex];
1011 const itemDef = itemDefinition(slot?.itemId);
1012 const spellId = spellIdFromSpellbookStack(slot, itemDef);
1013 if (!spellId)
1014 {
1015 const error = new Error("That is not a spellbook.");
1016 error.userFacing = true;
1017 throw error;
1018 }
1019 const spells = world.ecs.get(handle, Component.spells);
1020 const skills = world.ecs.get(handle, Component.skills);
1021 const learned = learnSpell(spells, spellId);
1022 if (!learned.changed)
1023 {
1024 const error = new Error("You already know that spell.");
1025 error.userFacing = true;
1026 throw error;
1027 }
1028 Object.assign(spells, learned.spells);
1029 inventory.slots[slotIndex] = null;
1030 const events = [
1031 spellsUpdatedEvent(entityId, character.characterId, spells, skills)
1032 ];
1033 return {
1034 events,
1035 private: bagView(world.ecs, handle)
1036 };
1037}
1038
1039export function createSpellbookStack (spellId)
1040{
1041 const instance = spellbookInstance(spellId);
1042 const itemId = spellbookItemIdForSpell(spellId);
1043 if (!instance || itemId == null)
1044 { return null; }
1045 return { itemId, quantity: 1, instance };
1046}