BlueGit

timfa questward

Files

questward / server / src / spells / service.js

service.js

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