BlueGit

timfa questward

Files

questward / server / src / spells / service.js

service.js

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