BlueGit

timfa questward

Files

questward / server / src / spells / service.js

service.js

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