BlueGit

timfa questward

Files

questward / server / src / spells / service.js

service.js

service.js 32.1 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 });
537 return { events };
538 }
539
540 const xpAward = awardSpellCastXp(world.ecs, handle, difficulty);
541 if (xpAward)
542 {
543 events.push({
544 type: "skills-updated",
545 entityId,
546 characterId: character.characterId,
547 skills: xpAward.skills,
548 combatLevel: xpAward.combatLevel,
549 stored: xpAward.stored,
550 levelUps: xpAward.levelUps ?? []
551 });
552 }
553
554 const flashRadius = castFlashRadiusTiles(def.tier);
555 events.push({
556 type: "spell-cast-flash",
557 casterId: entityId,
558 tileX: from.tileX,
559 tileY: from.tileY,
560 radiusTiles: flashRadius,
561 durationMs: CAST_FLASH_MS,
562 tier: def.tier
563 });
564
565 world.pendingSpellImpacts.push({
566 executeAt: now + SPELL_PROJECTILE_MS,
567 casterEntityId: entityId,
568 casterCharacterId: character.characterId,
569 spellId,
570 targetTileX: target.tileX,
571 targetTileY: target.tileY,
572 targetEntityId: target.targetEntityId,
573 levels
574 });
575
576 events.push({
577 type: "spell-projectile",
578 casterId: entityId,
579 spellId,
580 targetId: target.targetEntityId ?? null,
581 fromTileX: from.tileX,
582 fromTileY: from.tileY,
583 tileX: target.tileX,
584 tileY: target.tileY,
585 durationMs: SPELL_PROJECTILE_MS,
586 sprite: def.projectileSprite
587 });
588
589 return { events };
590}
591
592function rememberAutoRepeat (casting, spells, def, spellId, target, { staffCombat = false } = {})
593{
594 if (!casting || !def?.autoRepeat)
595 {
596 clearSpellAutoRepeat(casting);
597 return;
598 }
599 const continuingEntityRepeat = !!(
600 casting.repeatSpellId === spellId
601 && casting.repeatTargetEntityId != null
602 && target?.targetEntityId != null
603 && def.target === "entity"
604 );
605 if (!spells?.autoCast && !continuingEntityRepeat && !staffCombat)
606 {
607 clearSpellAutoRepeat(casting);
608 return;
609 }
610 if (def.target === "entity" && target?.targetEntityId != null)
611 {
612 casting.repeatSpellId = spellId;
613 casting.repeatTargetEntityId = target.targetEntityId | 0;
614 casting.repeatTileX = null;
615 casting.repeatTileY = null;
616 casting.pendingCast = null;
617 return;
618 }
619 if (def.target === "tile")
620 {
621 if (!spells?.autoCast)
622 {
623 clearSpellAutoRepeat(casting);
624 return;
625 }
626 casting.repeatSpellId = spellId;
627 casting.repeatTargetEntityId = null;
628 casting.repeatTileX = target.tileX | 0;
629 casting.repeatTileY = target.tileY | 0;
630 casting.pendingCast = null;
631 return;
632 }
633 clearSpellAutoRepeat(casting);
634}
635
636function targetAffinitiesForEntity (world, entityId)
637{
638 if (entityId == null)
639 { return {}; }
640 const handle = world.ecs.handleOf(entityId);
641 if (handle == null)
642 { return {}; }
643 const creature = world.ecs.get(handle, Component.creature);
644 const mobAffinities = creature
645 ? mobDamageAffinities(mobDefinition(creature.mobTypeId))
646 : {};
647 const equipment = world.ecs.get(handle, Component.equipment);
648 return mergeAffinities(mobAffinities, jewelryDamageAffinities(equipment));
649}
650
651function applySpellImpact (world, impact, now)
652{
653 const def = spellDefinition(impact.spellId);
654 if (!def)
655 { return []; }
656 const events = [];
657 events.push({
658 type: "spell-cast-flash",
659 casterId: impact.casterEntityId,
660 tileX: impact.targetTileX,
661 tileY: impact.targetTileY,
662 radiusTiles: castFlashRadiusTiles(def.tier),
663 durationMs: CAST_FLASH_MS,
664 tier: def.tier
665 });
666
667 const effect = def.effect ?? impact.spellId;
668 if (effect === "light" || effect === "dark")
669 {
670 events.push(...applyLightOrDarkImpact(world, impact, def, effect, now));
671 return events;
672 }
673 if (effect === "damage")
674 {
675 events.push(...applyDamageSpellImpact(world, impact, def, now));
676 return events;
677 }
678 if (effect === "poison")
679 {
680 events.push(...applyPoisonImpact(world, impact, def, now));
681 return events;
682 }
683 if (effect === "drain")
684 {
685 events.push(...applyDrainImpact(world, impact, now));
686 return events;
687 }
688 if (effect === "revitalize")
689 {
690 events.push(...applyRevitalizeImpact(world, impact, now));
691 return events;
692 }
693 if (effect === "tinders")
694 {
695 events.push(...applyTindersImpact(world, impact, now));
696 return events;
697 }
698 if (effect === "shade")
699 {
700 events.push(...applyShadeImpact(world, impact, now));
701 return events;
702 }
703 return events;
704}
705
706function mindRollOf (impact)
707{
708 return resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;
709}
710
711function mindDamageRollOf (impact, spellTier = 1)
712{
713 return rollSpellDamage(impact.levels.mind, spellTier);
714}
715
716function applyLightOrDarkImpact (world, impact, def, effect, now)
717{
718 const events = [];
719 world.spellLights = world.spellLights ?? new SpellLightRegistry();
720 const mindRoll = mindRollOf(impact);
721 const durationMs = Math.max(1, mindRoll) * LIGHT_DURATION_MS_PER_MIND;
722 const baseRange = mindRoll === 0
723 ? SPELL_LIGHT_RANGE_TILES * 0.5
724 : SPELL_LIGHT_RANGE_TILES;
725 const kind = effect === "dark" ? "dark" : "light";
726 const { light, extended } = world.spellLights.placeOrExtend({
727 tileX: impact.targetTileX,
728 tileY: impact.targetTileY,
729 ownerEntityId: impact.casterEntityId,
730 durationMs,
731 baseRange,
732 kind,
733 now
734 });
735 const appear = kind === "dark"
736 ? (extended ? "spell-dark-update" : "spell-dark-appear")
737 : (extended ? "spell-light-update" : "spell-light-appear");
738 events.push({ type: appear, ...publicSpellLight(light, now) });
739 return events;
740}
741
742function elementalDamageMultiplier (def, affinities)
743{
744 let multiplier = ElementMultiplier.neutral;
745 const affinity = affinities[def.element ?? "none"];
746 if (affinity === "weak")
747 { multiplier = ElementMultiplier.weak; }
748 else if (affinity === "resistant")
749 { multiplier = ElementMultiplier.resistant; }
750 return multiplier;
751}
752
753function applyDamageSpellImpact (world, impact, def, now)
754{
755 if (impact.targetEntityId == null)
756 { return []; }
757 const events = [];
758 const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);
759 const mindRoll = mindDamageRollOf(impact, def.tier);
760 const multiplier = elementalDamageMultiplier(def, affinities);
761 const damage = Math.max(1, Math.floor(mindRoll * multiplier));
762 events.push(...applyDamageAndKill(
763 world,
764 impact.casterEntityId,
765 impact.targetEntityId,
766 damage,
767 now
768 ));
769 events.push(...awardMagicHitXp(world, impact, damage));
770 return events;
771}
772
773function awardMagicHitXp (world, impact, damage)
774{
775 const events = [];
776 const casterHandle = world.ecs.handleOf(impact.casterEntityId);
777 if (casterHandle == null || !impact.casterCharacterId)
778 { return events; }
779 const xp = awardCombatHitXp(world.ecs, casterHandle, MAGIC_HIT_XP_PROFILE, damage);
780 if (xp)
781 {
782 events.push({
783 type: "skills-updated",
784 entityId: impact.casterEntityId,
785 characterId: impact.casterCharacterId,
786 skills: xp.skills,
787 combatLevel: xp.combatLevel,
788 stored: xp.stored,
789 levelUps: xp.levelUps ?? []
790 });
791 }
792 return events;
793}
794
795function ensureEntityStatusEffects (ecs, handle)
796{
797 let component = ecs.get(handle, Component.statusEffects);
798 if (!component)
799 { component = ecs.add(handle, Component.statusEffects, emptyStatusEffects()); }
800 return component;
801}
802
803function applyPoisonImpact (world, impact, def, now)
804{
805 if (impact.targetEntityId == null)
806 { return []; }
807 const target = resolveCombatTarget(world, impact.targetEntityId);
808 if (!target?.local || target.handle == null)
809 { return []; }
810 const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);
811 const mindRoll = mindRollOf(impact);
812 const multiplier = elementalDamageMultiplier(def, affinities);
813 const total = Math.max(1, Math.floor(mindRoll * multiplier * 2));
814 const durationMs = total * 1000;
815 const status = ensureEntityStatusEffects(world.ecs, target.handle);
816 applyStatusEffect(status, {
817 type: StatusEffectType.healthDrain,
818 durationMs,
819 amountPerSecond: 1
820 }, now);
821 return [{
822 type: "status-effects-entity",
823 entityId: impact.targetEntityId,
824 effects: publicStatusEffectsView(status, now)
825 }];
826}
827
828function applyDrainImpact (world, impact, now)
829{
830 if (impact.targetEntityId == null)
831 { return []; }
832 const target = resolveCombatTarget(world, impact.targetEntityId);
833 if (!target?.local || target.handle == null)
834 { return []; }
835 if (!world.ecs.get(target.handle, Component.stamina))
836 { return []; }
837 const mindRoll = mindRollOf(impact);
838 const durationMs = Math.max(1000, mindRoll * 3 * 1000);
839 const status = ensureEntityStatusEffects(world.ecs, target.handle);
840 applyStatusEffect(status, {
841 type: StatusEffectType.staminaDrain,
842 durationMs,
843 amountPerSecond: 1
844 }, now);
845 applyStatusEffect(status, {
846 type: StatusEffectType.staminaBlock,
847 durationMs,
848 amountPerSecond: 0
849 }, now);
850 const character = world.ecs.get(target.handle, Component.character);
851 const events = [{
852 type: "status-effects-entity",
853 entityId: impact.targetEntityId,
854 effects: publicStatusEffectsView(status, now)
855 }];
856 if (character?.characterId)
857 {
858 events.push({
859 type: "status-effects",
860 characterId: character.characterId,
861 effects: publicStatusEffectsView(status, now),
862 blind: hasStatusEffect(status, StatusEffectType.blind, now)
863 });
864 }
865 return events;
866}
867
868function applyRevitalizeImpact (world, impact, now)
869{
870 if (impact.targetEntityId == null)
871 { return []; }
872 const target = resolveCombatTarget(world, impact.targetEntityId);
873 if (!target?.local || target.handle == null)
874 { return []; }
875 if (!world.ecs.get(target.handle, Component.health))
876 { return []; }
877 const mindRoll = mindRollOf(impact);
878 const healTotal = Math.max(1, mindRoll);
879 const durationMs = healTotal * 1000;
880 const status = ensureEntityStatusEffects(world.ecs, target.handle);
881 applyStatusEffect(status, {
882 type: StatusEffectType.healthRegen,
883 durationMs,
884 amountPerSecond: 1
885 }, now);
886 const character = world.ecs.get(target.handle, Component.character);
887 const events = [{
888 type: "status-effects-entity",
889 entityId: impact.targetEntityId,
890 effects: publicStatusEffectsView(status, now)
891 }];
892 if (character?.characterId)
893 {
894 events.push({
895 type: "status-effects",
896 characterId: character.characterId,
897 effects: publicStatusEffectsView(status, now),
898 blind: hasStatusEffect(status, StatusEffectType.blind, now)
899 });
900 }
901 return events;
902}
903
904function applyTindersImpact (world, impact, now)
905{
906 const events = applyTindersAtTile(world, impact, now);
907 const casterHandle = world.ecs.handleOf(impact.casterEntityId);
908 const sessionId = casterHandle != null
909 ? world.ecs.get(casterHandle, Component.networkIdentity)?.sessionId
910 : null;
911 for (const event of events)
912 {
913 if (event.type === "command-error" && sessionId != null)
914 { event.sessionId = sessionId; }
915 }
916 return events;
917}
918
919function applyShadeImpact (world, impact, now)
920{
921 const mindRoll = mindRollOf(impact);
922 const durationMs = Math.max(1000, mindRoll * 3 * 1000);
923 const casterHandle = world.ecs.handleOf(impact.casterEntityId);
924 const mindLevel = impact.levels?.mind | 0 || 1;
925 const level = Math.max(1, Math.min(99, Math.floor(mindLevel * 0.75)));
926 return [{
927 type: "summon-entity",
928 ownerEntityId: impact.casterEntityId,
929 ownerCharacterId: impact.casterCharacterId ?? null,
930 tileX: impact.targetTileX,
931 tileY: impact.targetTileY,
932 level,
933 expiresAt: now + durationMs,
934 mobTypeId: "shade"
935 }];
936}
937
938export function processSpellImpacts (world, now = Date.now())
939{
940 const queue = world.pendingSpellImpacts ?? [];
941 if (!queue.length)
942 { return []; }
943 const events = [];
944 const keep = [];
945 for (const impact of queue)
946 {
947 if (impact.executeAt > now)
948 {
949 keep.push(impact);
950 continue;
951 }
952 events.push(...applySpellImpact(world, impact, now));
953 }
954 world.pendingSpellImpacts = keep;
955 return events;
956}
957
958export function stepPendingSpellCast (world, now = Date.now())
959{
960 const events = [];
961 for (const entity of world.ecs.query(Component.spellcasting, Component.character, Component.networkIdentity))
962 {
963 if (world.ecs.has(entity.handle, Component.dead))
964 {
965 if (entity.spellcasting)
966 { entity.spellcasting.pendingCast = null; }
967 continue;
968 }
969 const casting = entity.spellcasting;
970 if (!casting?.pendingCast)
971 { continue; }
972 const pending = casting.pendingCast;
973 const target = resolvePendingCastTarget(world, pending);
974 if (!target)
975 {
976 casting.pendingCast = null;
977 continue;
978 }
979 const rangeCheck = validateCastRange(world, entity.handle, target.tileX, target.tileY, now);
980 if (!rangeCheck.ok)
981 {
982 const minStandDist = target.targetEntityId != null ? 1 : 0;
983 queueSpellApproach(world, entity.handle, entity.entityId, target, minStandDist);
984 continue;
985 }
986 casting.pendingCast = null;
987 const result = executeCast(
988 world,
989 entity.networkIdentity.sessionId,
990 entity.character.characterId,
991 pending.spellId,
992 target,
993 now
994 );
995 events.push(...(result.events ?? []));
996 }
997 return events;
998}
999
1000export function stepSpellAutoCast (world, now = Date.now())
1001{
1002 const events = [];
1003 for (const entity of world.ecs.query(
1004 Component.spellcasting,
1005 Component.spells,
1006 Component.character,
1007 Component.networkIdentity
1008 ))
1009 {
1010 if (world.ecs.has(entity.handle, Component.dead))
1011 {
1012 clearSpellAutoRepeat(entity.spellcasting);
1013 continue;
1014 }
1015 const casting = entity.spellcasting;
1016 const spells = entity.spells;
1017 normalizeSpellcasting(casting);
1018 if (!casting.repeatSpellId)
1019 { continue; }
1020 if (now < (casting.nextCastAt || 0))
1021 { continue; }
1022 const def = spellDefinition(casting.repeatSpellId);
1023 if (!def?.autoRepeat)
1024 {
1025 clearSpellAutoRepeat(casting);
1026 continue;
1027 }
1028 /** UI auto-cast toggle gates starting repeats; combat retaliate may set repeat without it. */
1029 if (!spells.autoCast && casting.repeatTargetEntityId == null)
1030 {
1031 clearSpellAutoRepeat(casting);
1032 continue;
1033 }
1034
1035 const sessionId = entity.networkIdentity.sessionId;
1036 if (!sessionId)
1037 { continue; }
1038
1039 let target = null;
1040 let minStandDist = 0;
1041 if (casting.repeatTargetEntityId != null)
1042 {
1043 const resolved = resolveCombatTarget(world, casting.repeatTargetEntityId);
1044 if (!resolved || (resolved.health && resolved.health.current <= 0))
1045 {
1046 clearSpellAutoRepeat(casting);
1047 continue;
1048 }
1049 target = {
1050 tileX: resolved.pos.tileX,
1051 tileY: resolved.pos.tileY,
1052 targetEntityId: casting.repeatTargetEntityId
1053 };
1054 minStandDist = casting.repeatTargetEntityId === entity.entityId ? 0 : 1;
1055 }
1056 else if (casting.repeatTileX != null && casting.repeatTileY != null)
1057 {
1058 if (!tileAutoCastStillValid(world, casting.repeatSpellId, casting.repeatTileX, casting.repeatTileY))
1059 {
1060 clearSpellAutoRepeat(casting);
1061 continue;
1062 }
1063 target = {
1064 tileX: casting.repeatTileX | 0,
1065 tileY: casting.repeatTileY | 0,
1066 targetEntityId: null
1067 };
1068 minStandDist = 0;
1069 }
1070 else
1071 {
1072 clearSpellAutoRepeat(casting);
1073 continue;
1074 }
1075
1076 const range = validateCastRange(world, entity.handle, target.tileX, target.tileY, now);
1077 if (!range.ok)
1078 {
1079 queueSpellApproach(world, entity.handle, entity.entityId, target, minStandDist);
1080 continue;
1081 }
1082
1083 const result = executeCast(
1084 world,
1085 sessionId,
1086 entity.character.characterId,
1087 casting.repeatSpellId,
1088 target,
1089 now
1090 );
1091 events.push(...(result.events ?? []));
1092 }
1093 return events;
1094}
1095
1096function tileAutoCastStillValid (world, spellId, tileX, tileY)
1097{
1098 const def = spellDefinition(spellId);
1099 if (!def)
1100 { return false; }
1101 if (def.effect === "tinders")
1102 { return tindersTileStillNeedsCast(world, tileX, tileY); }
1103 return true;
1104}
1105
1106export function tickSpellLights (world, now = Date.now())
1107{
1108 if (!world.spellLights)
1109 { return []; }
1110 return world.spellLights.tick(world, now);
1111}
1112
1113function readSpellbook (world, sessionId, command, now)
1114{
1115 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
1116 ensureSpellComponents(world.ecs, handle);
1117 const inventory = world.ecs.get(handle, Component.inventory);
1118 const slotIndex = command.slotIndex | 0;
1119 const slot = inventory?.slots?.[slotIndex];
1120 const itemDef = itemDefinition(slot?.itemId);
1121 const spellId = spellIdFromSpellbookStack(slot, itemDef);
1122 if (!spellId)
1123 {
1124 const error = new Error("That is not a spellbook.");
1125 error.userFacing = true;
1126 throw error;
1127 }
1128 const spells = world.ecs.get(handle, Component.spells);
1129 const skills = world.ecs.get(handle, Component.skills);
1130 const learned = learnSpell(spells, spellId);
1131 if (!learned.changed)
1132 {
1133 const error = new Error("You already know that spell.");
1134 error.userFacing = true;
1135 throw error;
1136 }
1137 Object.assign(spells, learned.spells);
1138 inventory.slots[slotIndex] = null;
1139 const events = [
1140 spellsUpdatedEvent(entityId, character.characterId, spells, skills)
1141 ];
1142 return {
1143 events,
1144 private: bagView(world.ecs, handle)
1145 };
1146}
1147
1148export function createSpellbookStack (spellId)
1149{
1150 const instance = spellbookInstance(spellId);
1151 const itemId = spellbookItemIdForSpell(spellId);
1152 if (!instance || itemId == null)
1153 { return null; }
1154 return { itemId, quantity: 1, instance };
1155}