BlueGit

timfa questward

Files

questward / server / src / spells / service.js

service.js

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