import { Component } from "../ecs/components.js"; import { SkillId, skillLevel } from "../../../shared/definitions/skills.js"; import { SpellId, spellDefinition, spellDifficulty } from "../../../shared/definitions/spells.js"; import { canCastSpell, defaultPlayerSpells, normalizePlayerSpells, publicSpellsView, storedPlayerSpells, toggleFavorite, learnSpell } from "../../../shared/spells/state.js"; import { CAST_FLASH_MS, COMBAT_RANGE_TILES, LIGHT_DURATION_MS_PER_MIND, SPELL_COOLDOWN_MS, SPELL_PROJECTILE_MS, castFlashRadiusTiles } from "../../../shared/spells/constants.js"; import { mobElementAffinities, ElementMultiplier, resolveMagicAttack, resolveSpellCast, resolveSpellPotency } from "../../../shared/combat/magic.js"; import { mobDefinition } from "../../../shared/definitions/mobs.js"; import { awardCombatHitXp, awardDamageHealthXp, awardSpellCastXp, syncPlayerHealth } from "../skills/service.js"; import { equipmentBonusesFromSlots, effectiveSkillLevel } from "../../../shared/equipment/stats.js"; import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js"; import { chebyshev, hasCombatLineOfSight, queueStandInRangeApproach, resolveCombatTarget, applyDamageAndKill } from "../combat/service.js"; import { publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js"; import { spellCastXpFromDifficulty } from "../../../shared/skills/progression.js"; import { publicSpellLight, SpellLightRegistry } from "./lights.js"; import { SpellbookItemId, spellbookInstance } from "../../../shared/definitions/spellItems.js"; import { bagView } from "../items/bags.js"; const MAGIC_ATTACK_PROFILE = Object.freeze({ hitSkillId: SkillId.magic, damageSkillId: SkillId.mind }); export function ensureSpellComponents (ecs, handle, storedSpells = null) { if (!ecs.get(handle, Component.spells)) { ecs.add(handle, Component.spells, normalizePlayerSpells(storedSpells ?? defaultPlayerSpells())); } if (!ecs.get(handle, Component.spellcasting)) { ecs.add(handle, Component.spellcasting, { armedSpellId: null, repeatSpellId: null, repeatTargetEntityId: null, nextCastAt: 0 }); } } export function handleSpellCommand (world, sessionId, command, now = Date.now()) { switch (command.type) { case "set-spell-favorite": return setSpellFavorite(world, sessionId, command, now); case "set-spell-autocast": return setSpellAutoCast(world, sessionId, command, now); case "arm-spell": return armSpell(world, sessionId, command, now); case "cancel-arm-spell": return cancelArmSpell(world, sessionId, command, now); case "cast-spell-tile": return castSpellAtTile(world, sessionId, command, now); case "cast-spell-entity": return castSpellAtEntity(world, sessionId, command, now); case "read-spellbook": return readSpellbook(world, sessionId, command, now); default: return null; } } function requirePlayer (world, sessionId, characterId) { for (const entity of world.ecs.query(Component.networkIdentity, Component.character)) { if (entity.networkIdentity.sessionId !== sessionId) { continue; } if (entity.character.characterId !== characterId) { continue; } return { handle: entity.handle, entityId: entity.entityId, character: entity.character }; } const error = new Error("Character not found."); error.userFacing = true; throw error; } function spellsUpdatedEvent (entityId, characterId, spells, skills, levelUps = []) { return { type: "spells-updated", entityId, characterId, spells: publicSpellsView(spells, skills), stored: storedPlayerSpells(spells), autoCast: !!spells.autoCast, levelUps }; } function setSpellFavorite (world, sessionId, command, now) { const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId); ensureSpellComponents(world.ecs, handle); const skills = world.ecs.get(handle, Component.skills); const spells = world.ecs.get(handle, Component.spells); const result = toggleFavorite(spells, command.spellId, skills); if (result.error) { const error = new Error(result.error); error.userFacing = true; throw error; } Object.assign(spells, result.spells); const events = []; if (result.changed) { events.push(spellsUpdatedEvent(entityId, character.characterId, spells, skills)); } return { events }; } function setSpellAutoCast (world, sessionId, command, now) { const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId); ensureSpellComponents(world.ecs, handle); const skills = world.ecs.get(handle, Component.skills); const spells = world.ecs.get(handle, Component.spells); spells.autoCast = !!command.enabled; const casting = world.ecs.get(handle, Component.spellcasting); if (!spells.autoCast) { casting.repeatSpellId = null; casting.repeatTargetEntityId = null; } return { events: [spellsUpdatedEvent(entityId, character.characterId, spells, skills)] }; } function armSpell (world, sessionId, command, now) { const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId); ensureSpellComponents(world.ecs, handle); const skills = world.ecs.get(handle, Component.skills); const spells = world.ecs.get(handle, Component.spells); const check = canCastSpell(skills, spells, command.spellId); if (!check.ok) { const error = new Error(check.reason); error.userFacing = true; throw error; } const casting = world.ecs.get(handle, Component.spellcasting); casting.armedSpellId = command.spellId; casting.repeatSpellId = null; casting.repeatTargetEntityId = null; casting.pendingCast = null; return { events: [{ type: "spell-armed", entityId, characterId: character.characterId, spellId: command.spellId }] }; } function cancelArmSpell (world, sessionId, command) { const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId); const casting = world.ecs.get(handle, Component.spellcasting); if (!casting) { return { events: [] }; } casting.armedSpellId = null; casting.repeatSpellId = null; casting.repeatTargetEntityId = null; casting.pendingCast = null; return { events: [{ type: "spell-disarmed", entityId, characterId: character.characterId }] }; } function casterMagicLevels (ecs, handle, settings = null) { const skills = ecs.get(handle, Component.skills); const equipment = ecs.get(handle, Component.equipment); const bonuses = equipmentBonusesFromSlots(equipment?.slots, settings); const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now()); bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0); return { magic: effectiveSkillLevel(skills, SkillId.magic, bonuses), mind: effectiveSkillLevel(skills, SkillId.mind, bonuses) }; } function validateCastRange (world, handle, tileX, tileY, now) { const pos = world.ecs.get(handle, Component.position); if (!pos) { return { ok: false, reason: "You are not in the world." }; } const dist = chebyshev(pos.tileX, pos.tileY, tileX, tileY); if (dist > COMBAT_RANGE_TILES) { return { ok: false, reason: "That is out of range." }; } if (!hasCombatLineOfSight(world, pos.tileX, pos.tileY, tileX, tileY)) { return { ok: false, reason: "You cannot see that spot." }; } return { ok: true }; } function resolvePendingCastTarget (world, pending) { if (pending.targetEntityId == null) { return { tileX: pending.tileX | 0, tileY: pending.tileY | 0, targetEntityId: null }; } const target = resolveCombatTarget(world, pending.targetEntityId); if (!target) { return null; } return { tileX: target.pos.tileX, tileY: target.pos.tileY, targetEntityId: pending.targetEntityId }; } function queueSpellApproach (world, handle, entityId, target, minStandDist) { const position = world.ecs.get(handle, Component.position); if (!position) { return; } queueStandInRangeApproach( world, entityId, handle, position, target.tileX, target.tileY, COMBAT_RANGE_TILES, minStandDist ); } function beginCastOrApproach (world, sessionId, characterId, spellId, target, now, minStandDist = 0) { const { handle, entityId } = requirePlayer(world, sessionId, characterId); ensureSpellComponents(world.ecs, handle); const casting = world.ecs.get(handle, Component.spellcasting); const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now); if (!rangeCheck.ok) { casting.pendingCast = { spellId, tileX: target.tileX, tileY: target.tileY, targetEntityId: target.targetEntityId ?? null }; queueSpellApproach(world, handle, entityId, target, minStandDist); return { events: [] }; } casting.pendingCast = null; return executeCast(world, sessionId, characterId, spellId, target, now); } function castSpellAtTile (world, sessionId, command, now) { const spellId = command.spellId; const def = spellDefinition(spellId); if (!def || def.target !== "tile") { const error = new Error("That spell needs a different target."); error.userFacing = true; throw error; } return beginCastOrApproach(world, sessionId, command.characterId, spellId, { tileX: command.tileX | 0, tileY: command.tileY | 0, targetEntityId: null }, now, 0); } function castSpellAtEntity (world, sessionId, command, now) { const spellId = command.spellId; const def = spellDefinition(spellId); if (!def || def.target !== "entity") { const error = new Error("That spell needs a tile target."); error.userFacing = true; throw error; } const target = resolveCombatTarget(world, command.targetEntityId); if (!target) { const error = new Error("Target is not here."); error.userFacing = true; throw error; } return beginCastOrApproach(world, sessionId, command.characterId, spellId, { tileX: target.pos.tileX, tileY: target.pos.tileY, targetEntityId: command.targetEntityId }, now, 1); } function executeCast (world, sessionId, characterId, spellId, target, now) { const { handle, entityId, character } = requirePlayer(world, sessionId, characterId); ensureSpellComponents(world.ecs, handle); const skills = world.ecs.get(handle, Component.skills); const spells = world.ecs.get(handle, Component.spells); const casting = world.ecs.get(handle, Component.spellcasting); const def = spellDefinition(spellId); const check = canCastSpell(skills, spells, spellId); if (!check.ok) { const error = new Error(check.reason); error.userFacing = true; throw error; } if (now < (casting.nextCastAt || 0)) { const error = new Error("You are not ready to cast yet."); error.userFacing = true; throw error; } const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now); if (!rangeCheck.ok) { const error = new Error(rangeCheck.reason); error.userFacing = true; throw error; } const levels = casterMagicLevels(world.ecs, handle, world.settings); const difficulty = spellDifficulty(def); const cast = resolveSpellCast({ magicSkillLevel: levels.magic, spellDifficulty: difficulty }); const events = []; const from = world.ecs.get(handle, Component.position); casting.armedSpellId = null; casting.repeatSpellId = null; casting.repeatTargetEntityId = null; casting.nextCastAt = now + SPELL_COOLDOWN_MS; events.push({ type: "spell-disarmed", entityId, characterId: character.characterId }); if (!cast.success) { events.push({ type: "spell-fizzle", casterId: entityId, spellId, fromTileX: from.tileX, fromTileY: from.tileY, tileX: target.tileX, tileY: target.tileY }); return { events }; } const xpAward = awardSpellCastXp(world.ecs, handle, difficulty); if (xpAward) { events.push({ type: "skills-updated", entityId, characterId: character.characterId, skills: xpAward.view, stored: xpAward.stored, levelUps: xpAward.levelUps ?? [] }); } const flashRadius = castFlashRadiusTiles(def.tier); events.push({ type: "spell-cast-flash", casterId: entityId, tileX: from.tileX, tileY: from.tileY, radiusTiles: flashRadius, durationMs: CAST_FLASH_MS, tier: def.tier }); world.pendingSpellImpacts.push({ executeAt: now + SPELL_PROJECTILE_MS, casterEntityId: entityId, casterCharacterId: character.characterId, spellId, targetTileX: target.tileX, targetTileY: target.tileY, targetEntityId: target.targetEntityId, levels }); events.push({ type: "spell-projectile", casterId: entityId, spellId, targetId: target.targetEntityId ?? null, fromTileX: from.tileX, fromTileY: from.tileY, tileX: target.tileX, tileY: target.tileY, durationMs: SPELL_PROJECTILE_MS, sprite: def.projectileSprite }); if (def.autoRepeat && spells.autoCast && target.targetEntityId != null) { casting.repeatSpellId = spellId; casting.repeatTargetEntityId = target.targetEntityId; } else { casting.repeatSpellId = null; casting.repeatTargetEntityId = null; } return { events }; } function targetAffinitiesForEntity (world, entityId) { if (entityId == null) { return {}; } const handle = world.ecs.handleOf(entityId); if (handle == null) { return {}; } const creature = world.ecs.get(handle, Component.creature); if (!creature) { return {}; } return mobElementAffinities(mobDefinition(creature.mobTypeId)); } export function processSpellImpacts (world, now = Date.now()) { const queue = world.pendingSpellImpacts ?? []; if (!queue.length) { return []; } const events = []; const keep = []; for (const impact of queue) { if (impact.executeAt > now) { keep.push(impact); continue; } events.push(...applySpellImpact(world, impact, now)); } world.pendingSpellImpacts = keep; return events; } function applySpellImpact (world, impact, now) { const def = spellDefinition(impact.spellId); if (!def) { return []; } const events = []; events.push({ type: "spell-cast-flash", casterId: impact.casterEntityId, tileX: impact.targetTileX, tileY: impact.targetTileY, radiusTiles: castFlashRadiusTiles(def.tier), durationMs: CAST_FLASH_MS, tier: def.tier }); if (impact.spellId === SpellId.light) { world.spellLights = world.spellLights ?? new SpellLightRegistry(); const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll; const durationMs = mindRoll * LIGHT_DURATION_MS_PER_MIND; const { light, extended } = world.spellLights.placeOrExtend({ tileX: impact.targetTileX, tileY: impact.targetTileY, ownerEntityId: impact.casterEntityId, durationMs, now }); events.push({ type: extended ? "spell-light-update" : "spell-light-appear", ...publicSpellLight(light, now) }); return events; } if (impact.spellId === SpellId.spark && impact.targetEntityId != null) { const affinities = targetAffinitiesForEntity(world, impact.targetEntityId); const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll; let multiplier = ElementMultiplier.neutral; const affinity = affinities[def.element ?? "fire"]; if (affinity === "weak") { multiplier = ElementMultiplier.weak; } else if (affinity === "resistant") { multiplier = ElementMultiplier.resistant; } const damage = Math.max(1, Math.floor(mindRoll * multiplier)); events.push(...applyDamageAndKill( world, impact.casterEntityId, impact.targetEntityId, damage, now )); const casterHandle = world.ecs.handleOf(impact.casterEntityId); if (casterHandle != null && impact.casterCharacterId) { const xp = awardCombatHitXp(world.ecs, casterHandle, MAGIC_ATTACK_PROFILE, damage); if (xp) { events.push({ type: "skills-updated", entityId: impact.casterEntityId, characterId: impact.casterCharacterId, skills: xp.view, stored: xp.stored, levelUps: xp.levelUps ?? [] }); } } } return events; } export function stepPendingSpellCast (world, now = Date.now()) { const events = []; for (const entity of world.ecs.query(Component.spellcasting, Component.character, Component.networkIdentity)) { const casting = entity.spellcasting; if (!casting?.pendingCast) { continue; } const pending = casting.pendingCast; const target = resolvePendingCastTarget(world, pending); if (!target) { casting.pendingCast = null; continue; } const rangeCheck = validateCastRange(world, entity.handle, target.tileX, target.tileY, now); if (!rangeCheck.ok) { const minStandDist = target.targetEntityId != null ? 1 : 0; queueSpellApproach(world, entity.handle, entity.entityId, target, minStandDist); continue; } casting.pendingCast = null; const result = executeCast( world, entity.networkIdentity.sessionId, entity.character.characterId, pending.spellId, target, now ); events.push(...(result.events ?? [])); } return events; } export function stepSpellAutoCast (world, now = Date.now()) { const events = []; for (const entity of world.ecs.query(Component.spellcasting, Component.spells, Component.character)) { const casting = entity.spellcasting; const spells = entity.spells; if (!spells.autoCast || !casting.repeatSpellId || casting.repeatTargetEntityId == null) { continue; } if (now < (casting.nextCastAt || 0)) { continue; } const def = spellDefinition(casting.repeatSpellId); if (!def?.autoRepeat) { continue; } const target = resolveCombatTarget(world, casting.repeatTargetEntityId); if (!target || (target.health && target.health.current <= 0)) { casting.repeatSpellId = null; casting.repeatTargetEntityId = null; continue; } const range = validateCastRange(world, entity.handle, target.pos.tileX, target.pos.tileY, now); if (!range.ok) { continue; } const sessionId = entity.networkIdentity?.sessionId; if (!sessionId) { continue; } const result = executeCast( world, sessionId, entity.character.characterId, casting.repeatSpellId, { tileX: target.pos.tileX, tileY: target.pos.tileY, targetEntityId: casting.repeatTargetEntityId }, now ); events.push(...(result.events ?? [])); } return events; } export function tickSpellLights (world, now = Date.now()) { if (!world.spellLights) { return []; } return world.spellLights.tick(world, now); } function readSpellbook (world, sessionId, command, now) { const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId); ensureSpellComponents(world.ecs, handle); const inventory = world.ecs.get(handle, Component.inventory); const slotIndex = command.slotIndex | 0; const slot = inventory?.slots?.[slotIndex]; if (!slot?.instance || slot.instance.kind !== "spellbook") { const error = new Error("That is not a spellbook."); error.userFacing = true; throw error; } const spellId = slot.instance.spellId; const spells = world.ecs.get(handle, Component.spells); const skills = world.ecs.get(handle, Component.skills); const learned = learnSpell(spells, spellId); if (!learned.changed) { const error = new Error("You already know that spell."); error.userFacing = true; throw error; } Object.assign(spells, learned.spells); inventory.slots[slotIndex] = null; const events = [ spellsUpdatedEvent(entityId, character.characterId, spells, skills) ]; return { events, private: bagView(world.ecs, handle) }; } export function createSpellbookStack (spellId) { const instance = spellbookInstance(spellId); if (!instance) { return null; } const itemId = spellId === SpellId.spark ? SpellbookItemId.sparkSpellbook : null; if (itemId == null) { return null; } return { itemId, quantity: 1, instance }; }