import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js"; import { deriveCompletedStepIds, isActiveQuestState, rememberCompletedStep, resolveQuestStepId } from "../../../shared/quests/questProgress.js"; import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js"; import { countableObjectiveProgress, objectiveProgressFingerprint } from "../../../shared/quests/objectiveProgress.js"; import { countItemInSlots, insertStack, takeMatchingFromSlots, takeMatchingUpToFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js"; import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js"; import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js"; import { applySkillXp, publicSkillsPayload } from "../../../shared/skills/state.js"; import { SKILL_DEFINITIONS } from "../../../shared/definitions/skills.js"; import { resolveSkillRequirementLevel } from "../../../shared/combat/combatLevel.js"; import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage, formatDialogueTakeMessage } from "../../../shared/quests/dialogueRewards.js"; import { applyDialogueTextReplacements } from "../../../shared/speech/dialogueText.js"; import { formatQuestBankRewardLetterBody, QUESTWARD_GIFT_AUTHOR, QUESTWARD_GIFT_ORG } from "../../../shared/courier/questRewardLetters.js"; import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; import { floorDiv } from "../world/coordinates.js"; import { WorkerMessage } from "../simulation/protocol.js"; /** * Quest progress + dialogue sessions (main simulation thread). */ export class QuestRuntime { constructor ({ stateDb, content, simulation }) { this.stateDb = stateDb; this.content = content; this.simulation = simulation; /** @type {Map} */ this.sessions = new Map(); } reloadContent () { this.content.reload(); } closeAllSessions () { for (const characterId of [...this.sessions.keys()]) { this.closeDialogue(characterId, "revision"); } } questSnapshot (characterId) { const states = this.stateDb.listQuestStates(characterId) .filter((row) => row.state !== "not-started"); const quests = []; const playerView = this.playerViewFor(characterId); for (const row of states) { const def = this.content.quest(row.questId); if (!def) { quests.push({ questId: row.questId, title: "Quest unavailable", orphaned: true, state: row.state, description: "", step: null, journal: this.stateDb.listQuestJournal(characterId, row.questId).map(journalPublic) }); continue; } const stepDef = isActiveQuestState(row.state) ? activeQuestStep(def, row.state) : null; const resolvedState = isActiveQuestState(row.state) ? (resolveQuestStepId(def, row.state) ?? row.state) : row.state; const completedObjectiveIds = row.progress?.completedObjectiveIds ?? []; const ctx = stepDef ? this.buildConditionContext(characterId, playerView, row.questId) : null; quests.push({ questId: def.questId, title: def.title, orphaned: false, state: resolvedState, description: def.description, step: stepDef ? { stepId: stepDef.stepId, title: stepDef.title, description: stepDef.description, objectives: publicStepLines(stepDef, completedObjectiveIds, ctx) } : null, journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic) }); } quests.sort((a, b) => { const aDone = a.state === "completed" ? 1 : 0; const bDone = b.state === "completed" ? 1 : 0; if (aDone !== bDone) { return aDone - bDone; } return String(a.title).localeCompare(String(b.title)); }); return { quests }; } playerViewFor (characterId) { const entityId = this.simulation.characterEntities.get(characterId | 0); const record = entityId != null ? this.simulation.directory.get(entityId) : null; const skills = this.stateDb.getSkills(characterId) ?? {}; let hp = 1; let maxHp = 1; let stamina = 1; let maxStamina = 1; if (entityId != null && record) { const staminaComp = this.simulation.staminaOf(entityId); if (staminaComp) { stamina = Number(staminaComp.current) || 0; maxStamina = Math.max(1, Number(staminaComp.max) || 1); } const worker = this.simulation.workers[record.workerId]; const view = worker?.call?.({ type: WorkerMessage.inspect, entityId }); if (view && view.health != null) { hp = Number(view.health) || 0; maxHp = Math.max(1, Number(view.maxHealth) || 1); } } return { tileX: record?.tileX | 0, tileY: record?.tileY | 0, dimensionId: record?.dimensionId ?? "overworld", skills, hp, maxHp, stamina, maxStamina }; } buildConditionContext (characterId, playerView, activeQuestId = null) { const bag = this.#loadBag(characterId); const inventory = bag?.inventory ?? []; const tileX = playerView?.tileX | 0; const tileY = playerView?.tileY | 0; const dimensionId = playerView?.dimensionId ?? "overworld"; const chunkX = floorDiv(tileX, CHUNK_SIZE); const chunkY = floorDiv(tileY, CHUNK_SIZE); const questRow = activeQuestId ? this.stateDb.getQuestState(characterId, activeQuestId) : null; return { tileX, tileY, chunkX, chunkY, dimensionId, hp: playerView?.hp ?? 0, maxHp: playerView?.maxHp ?? 1, stamina: playerView?.stamina ?? 0, maxStamina: playerView?.maxStamina ?? 1, countItem: (itemId) => countItemInSlots(inventory, itemId | 0), questState: (questId) => { const row = this.stateDb.getQuestState(characterId, questId); return resolveQuestStepId(this.content.quest(questId), row.state); }, questSteps: (questId) => { const def = this.content.quest(questId); return def ? def.steps.map((step) => step.stepId) : null; }, hasCompletedStep: (questId, stepId) => { const row = this.stateDb.getQuestState(characterId, questId); const ids = deriveCompletedStepIds( this.content.quest(questId), row.state, row.progress ); return ids.includes(String(stepId ?? "")); }, dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId), dialogueTriggerLatched: (dialogueId, trigger) => this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger), skillLevel: (skillId) => resolveSkillRequirementLevel(playerView?.skills ?? {}, skillId), hasVisitedDimension: (dimId) => this.stateDb.hasVisitedDimension(characterId, dimId), killCount: (condition) => { if (!questRow) { return 0; } return questRow.progress?.counters?.[killKey(condition)] | 0; }, interactBlockDone: (condition) => { if (!questRow) { return false; } return !!questRow.progress?.interacts?.[interactKey(condition)]; } }; } tryOpenDialogue (characterId, entityId, dialogueId) { const tree = this.content.dialogue(dialogueId); if (!tree) { return { ok: false, error: "Nothing to say." }; } this.closeDialogue(characterId, "replace"); const playerView = this.playerViewFor(characterId); return this.#enterStep(characterId, entityId, tree, tree.entryStepId, playerView); } chooseDialogue (characterId, triggerId) { const session = this.sessions.get(characterId | 0); if (!session) { return { ok: false, error: "No dialogue open." }; } if (session.phase === "lines") { return { ok: false, error: "Finish reading first." }; } if (session.phase === "rewards") { return { ok: false, error: "Finish reading first." }; } const tree = this.content.dialogue(session.dialogueId); if (!tree) { this.closeDialogue(characterId, "missing"); return { ok: false, error: "Dialogue missing." }; } const step = tree.steps.find((s) => s.stepId === session.stepId); if (!step || step.exit?.kind !== "triggers") { return { ok: false, error: "Cannot choose now." }; } const trigger = step.exit.triggers.find((t) => t.trigger === String(triggerId)); if (!trigger) { return { ok: false, error: "Unknown choice." }; } const playerView = this.playerViewFor(characterId); const ctx = this.buildConditionContext(characterId, playerView); if (!evaluateConditionSet(trigger.when, ctx)) { return { ok: false, error: "That choice is unavailable." }; } this.stateDb.latchDialogueTrigger(characterId, tree.dialogueId, trigger.trigger); const events = []; this.#applyEffects(characterId, trigger.effects, playerView, events); this.#reevaluateQuests(characterId, playerView, events); if (!trigger.nextStepId) { const npcEntityId = session.entityId; this.sessions.delete(characterId | 0); events.push({ type: "dialogueClose", reason: "end", npcEntityId }); return { ok: true, events }; } return this.#enterStep(characterId, session.entityId, tree, trigger.nextStepId, playerView, events); } closeDialogue (characterId, reason = "close") { const id = characterId | 0; const session = this.sessions.get(id); if (!session) { return { events: [] }; } this.sessions.delete(id); return { events: [{ type: "dialogueClose", reason, npcEntityId: session.entityId }] }; } interruptDialogueForEntity (entityId) { const events = []; for (const [characterId, session] of [...this.sessions]) { if (session.entityId === (entityId | 0)) { const closed = this.closeDialogue(characterId, "attacked"); events.push(...closed.events.map((e) => ({ ...e, characterId }))); } } return events; } #enterStep (characterId, entityId, tree, stepId, playerView, priorEvents = []) { const step = tree.steps.find((s) => s.stepId === stepId); if (!step) { this.sessions.delete(characterId | 0); priorEvents.push({ type: "dialogueClose", reason: "missing-step" }); return { ok: false, error: "Broken dialogue.", events: priorEvents }; } const events = [...priorEvents]; const identity = this.#playerDialogueIdentity(characterId); const linePayloads = []; for (const line of step.lines) { this.#applyEffects(characterId, line.effects, playerView, events); linePayloads.push({ speaker: line.speaker, text: applyDialogueTextReplacements(line.text, identity) }); } // Stay open while the client pages lines; resolve exit only on dialogueAdvance. // dialogueHeard is marked only when the step fully completes (after rewards). this.sessions.set(characterId | 0, { entityId: entityId | 0, dialogueId: tree.dialogueId, stepId: step.stepId, phase: "lines", pendingExit: step.exit ?? { kind: "end" } }); events.push({ type: "dialogueStep", dialogueId: tree.dialogueId, stepId: step.stepId, label: step.label, npcEntityId: entityId | 0, lines: linePayloads }); this.#reevaluateQuests(characterId, playerView, events); return { ok: true, events }; } /** Client finished reading all lines (or reward notices) of the current step. */ advanceDialogue (characterId) { const session = this.sessions.get(characterId | 0); if (!session || (session.phase !== "lines" && session.phase !== "rewards")) { return { ok: false, error: "No dialogue lines to advance." }; } const tree = this.content.dialogue(session.dialogueId); if (!tree) { this.sessions.delete(characterId | 0); return { ok: true, events: [{ type: "dialogueClose", reason: "missing" }] }; } const playerView = this.playerViewFor(characterId); const events = []; if (session.phase === "lines") { const step = tree.steps.find((s) => s.stepId === session.stepId); const rewardMessages = [ ...this.#takeStepItems(characterId, step, events), ...this.#grantStepItemRewards(characterId, step, events), ...this.#grantStepQuestRewards(characterId, step, playerView, events) ]; this.#reevaluateQuests(characterId, playerView, events); if (rewardMessages.length > 0) { session.phase = "rewards"; events.push({ type: "dialogueItemRewards", dialogueId: session.dialogueId, stepId: session.stepId, npcEntityId: session.entityId, messages: rewardMessages }); return { ok: true, events }; } } return this.#resolveDialogueExit(characterId, session, tree, playerView, events); } #resolveDialogueExit (characterId, session, tree, playerView, events) { // Step is fully finished: lines read + takes/rewards/quest notices acknowledged. this.stateDb.markDialogueHeard(characterId, tree.dialogueId, session.stepId); this.#reevaluateQuests(characterId, playerView, events); const exit = session.pendingExit ?? { kind: "end" }; if (exit.kind === "branches") { const ctx = this.buildConditionContext(characterId, playerView); let matched = null; for (const branch of exit.branches ?? []) { if (evaluateConditionSet(branch.when, ctx)) { matched = branch; break; } } if (!matched || !matched.nextStepId) { this.#applyEffects(characterId, matched?.effects, playerView, events); const npcEntityId = session.entityId; this.sessions.delete(characterId | 0); events.push({ type: "dialogueClose", reason: "branch-end", npcEntityId }); return { ok: true, events }; } this.#applyEffects(characterId, matched.effects, playerView, events); return this.#enterStep(characterId, session.entityId, tree, matched.nextStepId, playerView, events); } if (exit.kind === "triggers") { const ctx = this.buildConditionContext(characterId, playerView); const identity = this.#playerDialogueIdentity(characterId); const triggers = (exit.triggers ?? []) .filter((t) => evaluateConditionSet(t.when, ctx)) .map((t) => ({ trigger: t.trigger, text: applyDialogueTextReplacements(t.text, identity) })); if (triggers.length === 0) { const npcEntityId = session.entityId; this.sessions.delete(characterId | 0); events.push({ type: "dialogueClose", reason: "no-triggers", npcEntityId }); return { ok: true, events }; } session.phase = "choices"; session.pendingExit = null; events.push({ type: "dialogueChoices", dialogueId: session.dialogueId, stepId: session.stepId, npcEntityId: session.entityId, triggers }); return { ok: true, events }; } if (exit.kind === "continue") { if (!exit.nextStepId) { const npcEntityId = session.entityId; this.sessions.delete(characterId | 0); events.push({ type: "dialogueClose", reason: "continue-end", npcEntityId }); return { ok: true, events }; } return this.#enterStep(characterId, session.entityId, tree, exit.nextStepId, playerView, events); } const npcEntityId = session.entityId; this.sessions.delete(characterId | 0); events.push({ type: "dialogueClose", reason: "end", npcEntityId }); return { ok: true, events }; } /** * Soft-take step.itemTakes from the bag (min(have, required)). Returns player-facing notices. */ #takeStepItems (characterId, step, events) { const takes = step?.itemTakes ?? []; if (!takes.length) { return []; } const parts = []; for (const take of takes) { const bag = this.#loadBag(characterId); if (!bag) { continue; } const itemId = take.itemId | 0; const want = Math.max(1, Number(take.quantity) || 1); const def = itemDefinition(itemId); const displayName = def?.displayName ?? `Item ${itemId}`; const result = takeMatchingUpToFromSlots(bag.inventory, { itemId, quantity: want, compact: false }); if (!result.ok || result.takenQuantity <= 0) { continue; } bag.inventory = result.slots; this.#persistBag(characterId, bag); events.push({ type: "inventoryDirty" }); parts.push({ displayName, quantity: result.takenQuantity }); } const message = formatDialogueTakeMessage(parts); return message ? [message] : []; } /** * Grant step.itemRewards into bag (overflow → bank/vault). Returns player-facing notices. */ #grantStepItemRewards (characterId, step, events) { const rewards = step?.itemRewards ?? []; if (!rewards.length) { return []; } const bagParts = []; const bankParts = []; for (const reward of rewards) { const bag = this.#loadBag(characterId); if (!bag) { continue; } const itemId = reward.itemId | 0; const def = itemDefinition(itemId); const quantity = Math.max(1, Number(reward.quantity) || 1); const displayName = def?.displayName ?? `Item ${itemId}`; const stack = attachOrigins({ itemId, quantity, origins: [{ origin: godsOrigin(), quantity }] }); const result = insertStack(bag.inventory, stack, def); bag.inventory = result.slots; const intoBag = quantity - Math.max(0, result.remainder | 0); let intoBank = 0; if (result.remainder > 0) { const vaultResult = insertStackGrowable( bag.vault, attachOrigins({ itemId, quantity: result.remainder, origins: [{ origin: godsOrigin(), quantity: result.remainder }] }), def ); bag.vault = vaultResult.slots; intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0); } this.#persistBag(characterId, bag); events.push({ type: "inventoryDirty" }); if (intoBag > 0) { bagParts.push({ displayName, quantity: intoBag }); } if (intoBank > 0) { bankParts.push({ displayName, quantity: intoBank }); } } const messages = []; const bagMsg = formatDialogueRewardMessage(bagParts, "bag"); const bankMsg = formatDialogueRewardMessage(bankParts, "bank"); if (bagMsg) { messages.push(bagMsg); } if (bankMsg) { messages.push(bankMsg); } return messages; } /** Start step.questRewards; returns player-facing notices for newly started quests. */ #grantStepQuestRewards (characterId, step, playerView, events) { const rewards = step?.questRewards ?? []; if (!rewards.length) { return []; } const titles = []; for (const questId of rewards) { const current = this.stateDb.getQuestState(characterId, questId); if (current.state !== "not-started") { continue; } const def = this.content.quest(questId); if (!def) { continue; } this.startQuest(characterId, questId, playerView, events); titles.push(def.title || def.questId); } const message = formatDialogueQuestRewardMessage(titles); return message ? [message] : []; } #loadBag (characterId) { const onlineId = this.simulation.characterEntities.get(characterId | 0); const bag = onlineId ? this.simulation.bagOf(onlineId) : this.stateDb.getBag(characterId); return bag; } #playerDialogueIdentity (characterId) { const row = this.stateDb.getCharacter(characterId | 0); return { firstName: String(row?.first_name ?? "").trim(), lastName: String(row?.last_name ?? "").trim(), sex: row?.sex === "female" ? "female" : "male" }; } #persistBag (characterId, bag) { this.stateDb.saveBag(characterId, bag); const onlineId = this.simulation.characterEntities.get(characterId | 0); if (onlineId) { this.simulation.applyBag?.(onlineId, bag); this.simulation.pushInventory?.(characterId, bag); } } #applyEffects (characterId, effects, playerView, events) { if (!Array.isArray(effects) || effects.length === 0) { return; } for (const effect of effects) { if (effect.kind === EffectKind.giveItem) { const bag = this.#loadBag(characterId); if (!bag) { continue; } const def = itemDefinition(effect.itemId | 0); const quantity = Math.max(1, Number(effect.quantity) || 1); const stack = attachOrigins({ itemId: effect.itemId | 0, quantity, origins: [{ origin: godsOrigin(), quantity }] }); if (effect.toBank) { const vaultResult = insertStackGrowable(bag.vault ?? [], stack, def); bag.vault = vaultResult.slots; } else { const result = insertStack(bag.inventory, stack, def); bag.inventory = result.slots; if (result.remainder > 0) { const vaultResult = insertStackGrowable( bag.vault ?? [], attachOrigins({ itemId: effect.itemId | 0, quantity: result.remainder, origins: [{ origin: godsOrigin(), quantity: result.remainder }] }), def ); bag.vault = vaultResult.slots; } } this.#persistBag(characterId, bag); events.push({ type: "inventoryDirty" }); } else if (effect.kind === EffectKind.takeItem) { const bag = this.#loadBag(characterId); if (!bag) { continue; } const taken = takeMatchingFromSlots(bag.inventory, { itemId: effect.itemId | 0, quantity: Math.max(1, Number(effect.quantity) || 1), compact: false }); if (taken.ok) { bag.inventory = taken.slots; this.#persistBag(characterId, bag); events.push({ type: "inventoryDirty" }); } } else if (effect.kind === EffectKind.giveXp) { const skills = this.stateDb.getSkills(characterId); if (skills) { applySkillXp(skills, effect.skillId, Math.max(0, Number(effect.amount) || 0)); this.stateDb.saveSkills(characterId, skills); if (playerView) { playerView.skills = skills; } events.push({ type: "skillsDirty" }); } } else if (effect.kind === EffectKind.startQuest) { this.startQuest(characterId, effect.questId, playerView, events); } } } startQuest (characterId, questId, playerView, events = []) { const def = this.content.quest(questId); if (!def) { return; } const current = this.stateDb.getQuestState(characterId, questId); if (current.state !== "not-started") { return; } const first = def.steps[0]; this.stateDb.saveQuestState(characterId, questId, first.stepId, { completedObjectiveIds: [], counters: {}, interacts: {}, completedStepIds: [], progressFingerprint: "" }, Date.now(), null); this.#applyEffects(characterId, first.onEnter, playerView, events); events.push({ type: "questsDirty", characterId }); this.#reevaluateQuests(characterId, playerView, events); } /** * Grant world-settings initial quests when the character has not started or completed them. */ ensureInitialQuests (characterId, playerView = null, events = []) { const list = normalizeInitialQuests(this.simulation?.settings?.initialQuests); for (const questId of list) { this.startQuest(characterId, questId, playerView, events); } return events; } /** * Re-check active quest objectives against live bag/position/etc. * Used when opening the quest log (and wherever progress may have changed offline of dialogue/kills). */ reevaluateQuests (characterId, playerView = null, events = []) { const view = playerView ?? this.playerViewFor(characterId); this.#reevaluateQuests(characterId, view, events); return events; } /** Apply initial quests to every character in state (settings save / apply). */ grantInitialQuestsToAllCharacters () { const events = []; for (const characterId of this.stateDb.listAllCharacterIds()) { this.ensureInitialQuests(characterId, null, events); } return events; } /** * Final quest rewards: XP + items (bag or bank). Banked items get a Questward letter. * @returns {{ xp: { skillId: string, displayName: string, amount: number }[], bagItems: { displayName: string, quantity: number }[] }} */ #grantQuestCompletionRewards (characterId, def, playerView, events) { const xp = []; const bagItems = []; const bankItems = []; const rewards = def?.rewards ?? []; for (const effect of rewards) { if (effect.kind === EffectKind.giveXp) { const amount = Math.max(0, Number(effect.amount) || 0) | 0; if (amount <= 0) { continue; } const skillId = String(effect.skillId ?? "").trim(); if (!skillId) { continue; } const onlineId = this.simulation.characterEntities.get(characterId | 0); let skills = onlineId ? this.simulation.skillsOf(onlineId) : this.stateDb.getSkills(characterId); if (!skills) { skills = this.stateDb.getSkills(characterId); } if (!skills) { continue; } applySkillXp(skills, skillId, amount); this.stateDb.saveSkills(characterId, skills); if (playerView) { playerView.skills = skills; } if (onlineId) { this.simulation.applySkills?.(onlineId, skills); } const payload = publicSkillsPayload(skills); this.simulation.pushSkills?.(characterId, payload.skills, payload.combatLevel); xp.push({ skillId, displayName: SKILL_DEFINITIONS[skillId]?.displayName ?? skillId, amount }); continue; } if (effect.kind !== EffectKind.giveItem) { continue; } const bag = this.#loadBag(characterId); if (!bag) { continue; } const itemId = effect.itemId | 0; const defItem = itemDefinition(itemId); const quantity = Math.max(1, Number(effect.quantity) || 1) | 0; const displayName = defItem ? itemDisplayName({ itemId, quantity }, defItem) : `Item ${itemId}`; const stack = attachOrigins({ itemId, quantity, origins: [{ origin: godsOrigin(), quantity }] }); let intoBag = 0; let intoBank = 0; if (effect.toBank) { const vaultResult = insertStackGrowable(bag.vault ?? [], stack, defItem); bag.vault = vaultResult.slots; intoBank = quantity - Math.max(0, vaultResult.remainder | 0); } else { const result = insertStack(bag.inventory, stack, defItem); bag.inventory = result.slots; intoBag = quantity - Math.max(0, result.remainder | 0); if (result.remainder > 0) { const vaultResult = insertStackGrowable( bag.vault ?? [], attachOrigins({ itemId, quantity: result.remainder, origins: [{ origin: godsOrigin(), quantity: result.remainder }] }), defItem ); bag.vault = vaultResult.slots; intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0); } } this.#persistBag(characterId, bag); events.push({ type: "inventoryDirty" }); if (intoBag > 0) { bagItems.push({ displayName, quantity: intoBag, itemId }); } if (intoBank > 0) { bankItems.push({ displayName, quantity: intoBank, itemId }); } } if (bankItems.length) { this.#dispatchQuestBankRewardLetter(characterId, def, bankItems); } return { xp, bagItems }; } #dispatchQuestBankRewardLetter (characterId, def, bankItems) { const courier = this.simulation.courier; if (!courier?.enqueueSystemLetter) { return; } const row = this.stateDb.getCharacter?.(characterId); const characterDisplayName = row ? `${row.first_name ?? ""} ${row.last_name ?? ""}`.trim() : "Adventurer"; const originTileX = row?.tile_x | 0; const originTileY = row?.tile_y | 0; const originDim = row?.dimension_id ?? undefined; const bank = courier.nearestBank?.(originTileX, originTileY, originDim); courier.enqueueSystemLetter({ characterId: characterId | 0, originTileX: bank?.tileX ?? originTileX, originTileY: bank?.tileY ?? originTileY, originDimensionId: bank?.dimensionId ?? originDim, authorDisplayName: QUESTWARD_GIFT_AUTHOR, authorOrganization: QUESTWARD_GIFT_ORG, body: formatQuestBankRewardLetterBody({ characterDisplayName, questTitle: def?.title ?? def?.questId, items: bankItems }) }); } #reevaluateQuests (characterId, playerView, events) { const outer = this._transitionedQuestIds == null; if (outer) { this._transitionedQuestIds = new Set(); } try { const states = this.stateDb.listQuestStates(characterId) .filter((row) => isActiveQuestState(row.state)); for (const row of states) { if (this._transitionedQuestIds.has(row.questId)) { continue; } const def = this.content.quest(row.questId); if (!def) { continue; } const stepDef = activeQuestStep(def, row.state); if (!stepDef) { continue; } const ctx = this.buildConditionContext(characterId, playerView, row.questId); if (stepDef.exit?.kind === "branches") { this.#advanceBranchStep(characterId, def, row, stepDef, ctx, playerView, events); } else { this.#advanceLinearStep(characterId, def, row, stepDef, ctx, playerView, events); } } } finally { if (outer) { this._transitionedQuestIds = null; } } } #advanceLinearStep (characterId, def, row, stepDef, ctx, playerView, events) { const completed = new Set(row.progress?.completedObjectiveIds ?? []); const newlyDone = []; let changed = false; for (const obj of stepDef.objectives) { if (completed.has(obj.objectiveId)) { continue; } if (evaluateConditionSet(obj.when, ctx)) { completed.add(obj.objectiveId); newlyDone.push(obj); changed = true; } } const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx); const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? ""); const progress = { ...row.progress, completedObjectiveIds: [...completed], progressFingerprint: fingerprint, completedStepIds: deriveCompletedStepIds(def, row.state, row.progress) }; const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId)); for (const obj of newlyDone) { events.push({ type: "questObjectiveComplete", questId: row.questId, objectiveId: obj.objectiveId, text: obj.text || "Objective" }); } if (allDone && this.#leaveStep(characterId, def, row, stepDef, null, playerView, events)) { return; } if (!changed && !progressChanged) { return; } this.#saveActiveProgress(characterId, def, row, progress); events.push({ type: "questsDirty", characterId }); } #advanceBranchStep (characterId, def, row, stepDef, ctx, playerView, events) { const branches = stepDef.exit?.branches ?? []; let matched = null; for (const branch of branches) { if (evaluateConditionSet(branch.when, ctx)) { matched = branch; break; } } const fingerprint = objectiveProgressFingerprint(branchProgressRows(branches), ctx); const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? ""); if (!matched) { if (!progressChanged) { return; } this.#saveActiveProgress(characterId, def, row, { ...row.progress, progressFingerprint: fingerprint, completedStepIds: deriveCompletedStepIds(def, row.state, row.progress) }); events.push({ type: "questsDirty", characterId }); return; } this.#leaveStep(characterId, def, row, stepDef, matched, playerView, events); } /** * One hop away from the current step. Returns false when a continue/branch * names a step that does not exist (stay put; retry next evaluation). * Empty nextStepId completes the quest. Quest-wide rewards fire only here. */ #leaveStep (characterId, def, row, stepDef, branch, playerView, events) { const exit = stepDef.exit ?? { kind: "complete" }; let destination = null; if (branch) { if (branch.nextStepId) { destination = def.steps.find((step) => step.stepId === branch.nextStepId) ?? null; if (!destination) { return false; } } } else if (exit.kind === "continue" && exit.nextStepId) { destination = def.steps.find((step) => step.stepId === exit.nextStepId) ?? null; if (!destination) { return false; } } this._transitionedQuestIds?.add(row.questId); const completedStepIds = rememberCompletedStep( deriveCompletedStepIds(def, row.state, row.progress), stepDef.stepId ); this.#applyEffects(characterId, stepDef.onComplete, playerView, events); if (branch) { this.#applyEffects(characterId, branch.effects, playerView, events); } const journal = this.stateDb.appendQuestJournal( characterId, row.questId, stepDef.stepId, stepDef.completionJournalText ); if (!destination) { const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events); this.stateDb.saveQuestState(characterId, row.questId, "completed", { ...row.progress, completedStepIds }, row.startedAt, Date.now()); events.push({ type: "questComplete", questId: row.questId, title: def.title, xp: summary.xp, items: summary.bagItems }); } else { this.stateDb.saveQuestState(characterId, row.questId, destination.stepId, { completedObjectiveIds: [], counters: {}, interacts: {}, progressFingerprint: "", completedStepIds }, row.startedAt, null); this.#applyEffects(characterId, destination.onEnter, playerView, events); events.push({ type: "questStepComplete", questId: row.questId, title: def.title, journalText: journal?.text ?? null }); } events.push({ type: "questsDirty", characterId }); return true; } #saveActiveProgress (characterId, def, row, progress) { const stepId = resolveQuestStepId(def, row.state) ?? row.state; const completedStepIds = Array.isArray(progress?.completedStepIds) ? progress.completedStepIds : deriveCompletedStepIds(def, row.state, row.progress); this.stateDb.saveQuestState(characterId, row.questId, stepId, { ...progress, completedStepIds }, row.startedAt, row.completedAt); } noteKill (characterId, { mobTypeId, spawnerId }) { const events = []; const playerView = this.playerViewFor(characterId); const states = this.stateDb.listQuestStates(characterId) .filter((row) => isActiveQuestState(row.state)); for (const row of states) { const def = this.content.quest(row.questId); const stepDef = def ? activeQuestStep(def, row.state) : null; if (!stepDef) { continue; } let changed = false; const counters = { ...(row.progress?.counters ?? {}) }; for (const set of stepConditionSets(stepDef)) { for (const clause of set?.all ?? []) { const c = clause.condition; if (!matchesKillCondition(c, mobTypeId, spawnerId)) { continue; } const key = killKey(c); counters[key] = (counters[key] | 0) + 1; changed = true; } } if (!changed) { continue; } this.#saveActiveProgress(characterId, def, row, { ...row.progress, counters, completedStepIds: deriveCompletedStepIds(def, row.state, row.progress) }); } this.#reevaluateQuests(characterId, playerView, events); return events; } } function activeQuestStep (def, state) { const stepId = resolveQuestStepId(def, state); if (!stepId || stepId === "not-started" || stepId === "completed") { return null; } return def.steps.find((step) => step.stepId === stepId) ?? null; } function stepConditionSets (stepDef) { if (stepDef?.exit?.kind === "branches") { return (stepDef.exit.branches ?? []).map((branch) => branch.when); } return (stepDef?.objectives ?? []).map((obj) => obj.when); } function branchProgressRows (branches) { return (branches ?? []).map((branch, index) => ({ objectiveId: `branch-${index}`, when: branch.when })); } function publicStepLines (stepDef, completedObjectiveIds, ctx) { if (stepDef.exit?.kind === "branches") { return (stepDef.exit.branches ?? []).map((branch, index) => { const progress = countableObjectiveProgress(branch.when, ctx); return { objectiveId: `branch-${index}`, text: branch.text || branch.label || `Path ${index + 1}`, done: false, current: progress?.current ?? null, required: progress?.required ?? null }; }); } return (stepDef.objectives ?? []).map((obj) => { const done = completedObjectiveIds.includes(obj.objectiveId); const progress = countableObjectiveProgress(obj.when, ctx); return { objectiveId: obj.objectiveId, text: obj.text, done, current: progress?.current ?? null, required: progress?.required ?? null }; }); } function journalPublic (row) { return { entryId: row.entry_id ?? row.entryId, questId: row.quest_id ?? row.questId, stepId: row.step_id ?? row.stepId, text: row.text, writtenAt: row.written_at ?? row.writtenAt }; } function matchesKillCondition (condition, mobTypeId, spawnerId) { if (!condition || typeof condition !== "object") { return false; } if (condition.kind === "killMobFromSpawner") { if (condition.mobTypeId == null || condition.spawnerId == null || spawnerId == null) { return false; } return String(condition.mobTypeId) === String(mobTypeId) && String(condition.spawnerId) === String(spawnerId); } if (condition.kind === "killCount") { // Mob-type kills: match type. Legacy JSON may also use spawnerId alone. const matchMob = condition.mobTypeId != null && String(condition.mobTypeId) === String(mobTypeId); const matchSpawner = condition.spawnerId != null && String(condition.spawnerId) === String(spawnerId); return matchMob || matchSpawner; } return false; } function killKey (condition) { if (condition.spawnerId) { return `spawner:${condition.spawnerId}`; } return `mob:${condition.mobTypeId}`; } function interactKey (condition) { if (condition.tileX != null) { return `tile:${condition.tileX},${condition.tileY}`; } return `block:${condition.blockTypeId}`; }