| 1 | import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js"; |
| 2 | import { |
| 3 | deriveCompletedStepIds, |
| 4 | isActiveQuestState, |
| 5 | rememberCompletedStep, |
| 6 | resolveQuestStepId |
| 7 | } from "../../../shared/quests/questProgress.js"; |
| 8 | import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js"; |
| 9 | import { |
| 10 | countableObjectiveProgress, |
| 11 | objectiveProgressFingerprint |
| 12 | } from "../../../shared/quests/objectiveProgress.js"; |
| 13 | import { countItemInSlots, insertStack, takeMatchingFromSlots, takeMatchingUpToFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js"; |
| 14 | import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js"; |
| 15 | import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js"; |
| 16 | import { applySkillXp, publicSkillsPayload } from "../../../shared/skills/state.js"; |
| 17 | import { SKILL_DEFINITIONS } from "../../../shared/definitions/skills.js"; |
| 18 | import { resolveSkillRequirementLevel } from "../../../shared/combat/combatLevel.js"; |
| 19 | import { |
| 20 | formatDialogueRewardMessage, |
| 21 | formatDialogueQuestRewardMessage, |
| 22 | formatDialogueTakeMessage |
| 23 | } from "../../../shared/quests/dialogueRewards.js"; |
| 24 | import { applyDialogueTextReplacements } from "../../../shared/speech/dialogueText.js"; |
| 25 | import { |
| 26 | formatQuestBankRewardLetterBody, |
| 27 | QUESTWARD_GIFT_AUTHOR, |
| 28 | QUESTWARD_GIFT_ORG |
| 29 | } from "../../../shared/courier/questRewardLetters.js"; |
| 30 | import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; |
| 31 | import { floorDiv } from "../world/coordinates.js"; |
| 32 | import { WorkerMessage } from "../simulation/protocol.js"; |
| 33 | |
| 34 | /** |
| 35 | * Quest progress + dialogue sessions (main simulation thread). |
| 36 | */ |
| 37 | export class QuestRuntime |
| 38 | { |
| 39 | constructor ({ stateDb, content, simulation }) |
| 40 | { |
| 41 | this.stateDb = stateDb; |
| 42 | this.content = content; |
| 43 | this.simulation = simulation; |
| 44 | /** @type {Map<number, { entityId: number, dialogueId: string, stepId: string }>} */ |
| 45 | this.sessions = new Map(); |
| 46 | } |
| 47 | |
| 48 | reloadContent () |
| 49 | { |
| 50 | this.content.reload(); |
| 51 | } |
| 52 | |
| 53 | closeAllSessions () |
| 54 | { |
| 55 | for (const characterId of [...this.sessions.keys()]) |
| 56 | { this.closeDialogue(characterId, "revision"); } |
| 57 | } |
| 58 | |
| 59 | questSnapshot (characterId) |
| 60 | { |
| 61 | const states = this.stateDb.listQuestStates(characterId) |
| 62 | .filter((row) => row.state !== "not-started"); |
| 63 | const quests = []; |
| 64 | const playerView = this.playerViewFor(characterId); |
| 65 | for (const row of states) |
| 66 | { |
| 67 | const def = this.content.quest(row.questId); |
| 68 | if (!def) |
| 69 | { |
| 70 | quests.push({ |
| 71 | questId: row.questId, |
| 72 | title: "Quest unavailable", |
| 73 | orphaned: true, |
| 74 | state: row.state, |
| 75 | description: "", |
| 76 | step: null, |
| 77 | journal: this.stateDb.listQuestJournal(characterId, row.questId).map(journalPublic) |
| 78 | }); |
| 79 | continue; |
| 80 | } |
| 81 | const stepDef = isActiveQuestState(row.state) |
| 82 | ? activeQuestStep(def, row.state) |
| 83 | : null; |
| 84 | const resolvedState = isActiveQuestState(row.state) |
| 85 | ? (resolveQuestStepId(def, row.state) ?? row.state) |
| 86 | : row.state; |
| 87 | const completedObjectiveIds = row.progress?.completedObjectiveIds ?? []; |
| 88 | const ctx = stepDef |
| 89 | ? this.buildConditionContext(characterId, playerView, row.questId) |
| 90 | : null; |
| 91 | quests.push({ |
| 92 | questId: def.questId, |
| 93 | title: def.title, |
| 94 | orphaned: false, |
| 95 | state: resolvedState, |
| 96 | description: def.description, |
| 97 | step: stepDef |
| 98 | ? { |
| 99 | stepId: stepDef.stepId, |
| 100 | title: stepDef.title, |
| 101 | description: stepDef.description, |
| 102 | objectives: publicStepLines(stepDef, completedObjectiveIds, ctx) |
| 103 | } |
| 104 | : null, |
| 105 | journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic) |
| 106 | }); |
| 107 | } |
| 108 | quests.sort((a, b) => |
| 109 | { |
| 110 | const aDone = a.state === "completed" ? 1 : 0; |
| 111 | const bDone = b.state === "completed" ? 1 : 0; |
| 112 | if (aDone !== bDone) |
| 113 | { return aDone - bDone; } |
| 114 | return String(a.title).localeCompare(String(b.title)); |
| 115 | }); |
| 116 | return { quests }; |
| 117 | } |
| 118 | |
| 119 | playerViewFor (characterId) |
| 120 | { |
| 121 | const entityId = this.simulation.characterEntities.get(characterId | 0); |
| 122 | const record = entityId != null ? this.simulation.directory.get(entityId) : null; |
| 123 | const skills = this.stateDb.getSkills(characterId) ?? {}; |
| 124 | let hp = 1; |
| 125 | let maxHp = 1; |
| 126 | let stamina = 1; |
| 127 | let maxStamina = 1; |
| 128 | if (entityId != null && record) |
| 129 | { |
| 130 | const staminaComp = this.simulation.staminaOf(entityId); |
| 131 | if (staminaComp) |
| 132 | { |
| 133 | stamina = Number(staminaComp.current) || 0; |
| 134 | maxStamina = Math.max(1, Number(staminaComp.max) || 1); |
| 135 | } |
| 136 | const worker = this.simulation.workers[record.workerId]; |
| 137 | const view = worker?.call?.({ |
| 138 | type: WorkerMessage.inspect, |
| 139 | entityId |
| 140 | }); |
| 141 | if (view && view.health != null) |
| 142 | { |
| 143 | hp = Number(view.health) || 0; |
| 144 | maxHp = Math.max(1, Number(view.maxHealth) || 1); |
| 145 | } |
| 146 | } |
| 147 | return { |
| 148 | tileX: record?.tileX | 0, |
| 149 | tileY: record?.tileY | 0, |
| 150 | dimensionId: record?.dimensionId ?? "overworld", |
| 151 | skills, |
| 152 | hp, |
| 153 | maxHp, |
| 154 | stamina, |
| 155 | maxStamina |
| 156 | }; |
| 157 | } |
| 158 | |
| 159 | buildConditionContext (characterId, playerView, activeQuestId = null) |
| 160 | { |
| 161 | const bag = this.#loadBag(characterId); |
| 162 | const inventory = bag?.inventory ?? []; |
| 163 | const tileX = playerView?.tileX | 0; |
| 164 | const tileY = playerView?.tileY | 0; |
| 165 | const dimensionId = playerView?.dimensionId ?? "overworld"; |
| 166 | const chunkX = floorDiv(tileX, CHUNK_SIZE); |
| 167 | const chunkY = floorDiv(tileY, CHUNK_SIZE); |
| 168 | const questRow = activeQuestId ? this.stateDb.getQuestState(characterId, activeQuestId) : null; |
| 169 | return { |
| 170 | tileX, |
| 171 | tileY, |
| 172 | chunkX, |
| 173 | chunkY, |
| 174 | dimensionId, |
| 175 | hp: playerView?.hp ?? 0, |
| 176 | maxHp: playerView?.maxHp ?? 1, |
| 177 | stamina: playerView?.stamina ?? 0, |
| 178 | maxStamina: playerView?.maxStamina ?? 1, |
| 179 | countItem: (itemId) => countItemInSlots(inventory, itemId | 0), |
| 180 | questState: (questId) => |
| 181 | { |
| 182 | const row = this.stateDb.getQuestState(characterId, questId); |
| 183 | return resolveQuestStepId(this.content.quest(questId), row.state); |
| 184 | }, |
| 185 | questSteps: (questId) => |
| 186 | { |
| 187 | const def = this.content.quest(questId); |
| 188 | return def ? def.steps.map((step) => step.stepId) : null; |
| 189 | }, |
| 190 | hasCompletedStep: (questId, stepId) => |
| 191 | { |
| 192 | const row = this.stateDb.getQuestState(characterId, questId); |
| 193 | const ids = deriveCompletedStepIds( |
| 194 | this.content.quest(questId), |
| 195 | row.state, |
| 196 | row.progress |
| 197 | ); |
| 198 | return ids.includes(String(stepId ?? "")); |
| 199 | }, |
| 200 | dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId), |
| 201 | dialogueTriggerLatched: (dialogueId, trigger) => |
| 202 | this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger), |
| 203 | skillLevel: (skillId) => resolveSkillRequirementLevel(playerView?.skills ?? {}, skillId), |
| 204 | hasVisitedDimension: (dimId) => this.stateDb.hasVisitedDimension(characterId, dimId), |
| 205 | killCount: (condition) => |
| 206 | { |
| 207 | if (!questRow) |
| 208 | { return 0; } |
| 209 | return questRow.progress?.counters?.[killKey(condition)] | 0; |
| 210 | }, |
| 211 | interactBlockDone: (condition) => |
| 212 | { |
| 213 | if (!questRow) |
| 214 | { return false; } |
| 215 | return !!questRow.progress?.interacts?.[interactKey(condition)]; |
| 216 | } |
| 217 | }; |
| 218 | } |
| 219 | |
| 220 | tryOpenDialogue (characterId, entityId, dialogueId) |
| 221 | { |
| 222 | const tree = this.content.dialogue(dialogueId); |
| 223 | if (!tree) |
| 224 | { return { ok: false, error: "Nothing to say." }; } |
| 225 | this.closeDialogue(characterId, "replace"); |
| 226 | const playerView = this.playerViewFor(characterId); |
| 227 | return this.#enterStep(characterId, entityId, tree, tree.entryStepId, playerView); |
| 228 | } |
| 229 | |
| 230 | chooseDialogue (characterId, triggerId) |
| 231 | { |
| 232 | const session = this.sessions.get(characterId | 0); |
| 233 | if (!session) |
| 234 | { return { ok: false, error: "No dialogue open." }; } |
| 235 | if (session.phase === "lines") |
| 236 | { return { ok: false, error: "Finish reading first." }; } |
| 237 | if (session.phase === "rewards") |
| 238 | { return { ok: false, error: "Finish reading first." }; } |
| 239 | const tree = this.content.dialogue(session.dialogueId); |
| 240 | if (!tree) |
| 241 | { |
| 242 | this.closeDialogue(characterId, "missing"); |
| 243 | return { ok: false, error: "Dialogue missing." }; |
| 244 | } |
| 245 | const step = tree.steps.find((s) => s.stepId === session.stepId); |
| 246 | if (!step || step.exit?.kind !== "triggers") |
| 247 | { return { ok: false, error: "Cannot choose now." }; } |
| 248 | const trigger = step.exit.triggers.find((t) => t.trigger === String(triggerId)); |
| 249 | if (!trigger) |
| 250 | { return { ok: false, error: "Unknown choice." }; } |
| 251 | const playerView = this.playerViewFor(characterId); |
| 252 | const ctx = this.buildConditionContext(characterId, playerView); |
| 253 | if (!evaluateConditionSet(trigger.when, ctx)) |
| 254 | { return { ok: false, error: "That choice is unavailable." }; } |
| 255 | this.stateDb.latchDialogueTrigger(characterId, tree.dialogueId, trigger.trigger); |
| 256 | const events = []; |
| 257 | this.#applyEffects(characterId, trigger.effects, playerView, events); |
| 258 | this.#reevaluateQuests(characterId, playerView, events); |
| 259 | if (!trigger.nextStepId) |
| 260 | { |
| 261 | const npcEntityId = session.entityId; |
| 262 | this.sessions.delete(characterId | 0); |
| 263 | events.push({ type: "dialogueClose", reason: "end", npcEntityId }); |
| 264 | return { ok: true, events }; |
| 265 | } |
| 266 | return this.#enterStep(characterId, session.entityId, tree, trigger.nextStepId, playerView, events); |
| 267 | } |
| 268 | |
| 269 | closeDialogue (characterId, reason = "close") |
| 270 | { |
| 271 | const id = characterId | 0; |
| 272 | const session = this.sessions.get(id); |
| 273 | if (!session) |
| 274 | { return { events: [] }; } |
| 275 | this.sessions.delete(id); |
| 276 | return { |
| 277 | events: [{ |
| 278 | type: "dialogueClose", |
| 279 | reason, |
| 280 | npcEntityId: session.entityId |
| 281 | }] |
| 282 | }; |
| 283 | } |
| 284 | |
| 285 | interruptDialogueForEntity (entityId) |
| 286 | { |
| 287 | const events = []; |
| 288 | for (const [characterId, session] of [...this.sessions]) |
| 289 | { |
| 290 | if (session.entityId === (entityId | 0)) |
| 291 | { |
| 292 | const closed = this.closeDialogue(characterId, "attacked"); |
| 293 | events.push(...closed.events.map((e) => ({ ...e, characterId }))); |
| 294 | } |
| 295 | } |
| 296 | return events; |
| 297 | } |
| 298 | |
| 299 | #enterStep (characterId, entityId, tree, stepId, playerView, priorEvents = []) |
| 300 | { |
| 301 | const step = tree.steps.find((s) => s.stepId === stepId); |
| 302 | if (!step) |
| 303 | { |
| 304 | this.sessions.delete(characterId | 0); |
| 305 | priorEvents.push({ type: "dialogueClose", reason: "missing-step" }); |
| 306 | return { ok: false, error: "Broken dialogue.", events: priorEvents }; |
| 307 | } |
| 308 | const events = [...priorEvents]; |
| 309 | const identity = this.#playerDialogueIdentity(characterId); |
| 310 | const linePayloads = []; |
| 311 | for (const line of step.lines) |
| 312 | { |
| 313 | this.#applyEffects(characterId, line.effects, playerView, events); |
| 314 | linePayloads.push({ |
| 315 | speaker: line.speaker, |
| 316 | text: applyDialogueTextReplacements(line.text, identity) |
| 317 | }); |
| 318 | } |
| 319 | // Stay open while the client pages lines; resolve exit only on dialogueAdvance. |
| 320 | // dialogueHeard is marked only when the step fully completes (after rewards). |
| 321 | this.sessions.set(characterId | 0, { |
| 322 | entityId: entityId | 0, |
| 323 | dialogueId: tree.dialogueId, |
| 324 | stepId: step.stepId, |
| 325 | phase: "lines", |
| 326 | pendingExit: step.exit ?? { kind: "end" } |
| 327 | }); |
| 328 | events.push({ |
| 329 | type: "dialogueStep", |
| 330 | dialogueId: tree.dialogueId, |
| 331 | stepId: step.stepId, |
| 332 | label: step.label, |
| 333 | npcEntityId: entityId | 0, |
| 334 | lines: linePayloads |
| 335 | }); |
| 336 | this.#reevaluateQuests(characterId, playerView, events); |
| 337 | return { ok: true, events }; |
| 338 | } |
| 339 | |
| 340 | /** Client finished reading all lines (or reward notices) of the current step. */ |
| 341 | advanceDialogue (characterId) |
| 342 | { |
| 343 | const session = this.sessions.get(characterId | 0); |
| 344 | if (!session || (session.phase !== "lines" && session.phase !== "rewards")) |
| 345 | { return { ok: false, error: "No dialogue lines to advance." }; } |
| 346 | const tree = this.content.dialogue(session.dialogueId); |
| 347 | if (!tree) |
| 348 | { |
| 349 | this.sessions.delete(characterId | 0); |
| 350 | return { ok: true, events: [{ type: "dialogueClose", reason: "missing" }] }; |
| 351 | } |
| 352 | const playerView = this.playerViewFor(characterId); |
| 353 | const events = []; |
| 354 | |
| 355 | if (session.phase === "lines") |
| 356 | { |
| 357 | const step = tree.steps.find((s) => s.stepId === session.stepId); |
| 358 | const rewardMessages = [ |
| 359 | ...this.#takeStepItems(characterId, step, events), |
| 360 | ...this.#grantStepItemRewards(characterId, step, events), |
| 361 | ...this.#grantStepQuestRewards(characterId, step, playerView, events) |
| 362 | ]; |
| 363 | this.#reevaluateQuests(characterId, playerView, events); |
| 364 | if (rewardMessages.length > 0) |
| 365 | { |
| 366 | session.phase = "rewards"; |
| 367 | events.push({ |
| 368 | type: "dialogueItemRewards", |
| 369 | dialogueId: session.dialogueId, |
| 370 | stepId: session.stepId, |
| 371 | npcEntityId: session.entityId, |
| 372 | messages: rewardMessages |
| 373 | }); |
| 374 | return { ok: true, events }; |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | return this.#resolveDialogueExit(characterId, session, tree, playerView, events); |
| 379 | } |
| 380 | |
| 381 | #resolveDialogueExit (characterId, session, tree, playerView, events) |
| 382 | { |
| 383 | // Step is fully finished: lines read + takes/rewards/quest notices acknowledged. |
| 384 | this.stateDb.markDialogueHeard(characterId, tree.dialogueId, session.stepId); |
| 385 | this.#reevaluateQuests(characterId, playerView, events); |
| 386 | |
| 387 | const exit = session.pendingExit ?? { kind: "end" }; |
| 388 | |
| 389 | if (exit.kind === "branches") |
| 390 | { |
| 391 | const ctx = this.buildConditionContext(characterId, playerView); |
| 392 | let matched = null; |
| 393 | for (const branch of exit.branches ?? []) |
| 394 | { |
| 395 | if (evaluateConditionSet(branch.when, ctx)) |
| 396 | { |
| 397 | matched = branch; |
| 398 | break; |
| 399 | } |
| 400 | } |
| 401 | if (!matched || !matched.nextStepId) |
| 402 | { |
| 403 | this.#applyEffects(characterId, matched?.effects, playerView, events); |
| 404 | const npcEntityId = session.entityId; |
| 405 | this.sessions.delete(characterId | 0); |
| 406 | events.push({ type: "dialogueClose", reason: "branch-end", npcEntityId }); |
| 407 | return { ok: true, events }; |
| 408 | } |
| 409 | this.#applyEffects(characterId, matched.effects, playerView, events); |
| 410 | return this.#enterStep(characterId, session.entityId, tree, matched.nextStepId, playerView, events); |
| 411 | } |
| 412 | |
| 413 | if (exit.kind === "triggers") |
| 414 | { |
| 415 | const ctx = this.buildConditionContext(characterId, playerView); |
| 416 | const identity = this.#playerDialogueIdentity(characterId); |
| 417 | const triggers = (exit.triggers ?? []) |
| 418 | .filter((t) => evaluateConditionSet(t.when, ctx)) |
| 419 | .map((t) => ({ |
| 420 | trigger: t.trigger, |
| 421 | text: applyDialogueTextReplacements(t.text, identity) |
| 422 | })); |
| 423 | if (triggers.length === 0) |
| 424 | { |
| 425 | const npcEntityId = session.entityId; |
| 426 | this.sessions.delete(characterId | 0); |
| 427 | events.push({ type: "dialogueClose", reason: "no-triggers", npcEntityId }); |
| 428 | return { ok: true, events }; |
| 429 | } |
| 430 | session.phase = "choices"; |
| 431 | session.pendingExit = null; |
| 432 | events.push({ |
| 433 | type: "dialogueChoices", |
| 434 | dialogueId: session.dialogueId, |
| 435 | stepId: session.stepId, |
| 436 | npcEntityId: session.entityId, |
| 437 | triggers |
| 438 | }); |
| 439 | return { ok: true, events }; |
| 440 | } |
| 441 | |
| 442 | if (exit.kind === "continue") |
| 443 | { |
| 444 | if (!exit.nextStepId) |
| 445 | { |
| 446 | const npcEntityId = session.entityId; |
| 447 | this.sessions.delete(characterId | 0); |
| 448 | events.push({ type: "dialogueClose", reason: "continue-end", npcEntityId }); |
| 449 | return { ok: true, events }; |
| 450 | } |
| 451 | return this.#enterStep(characterId, session.entityId, tree, exit.nextStepId, playerView, events); |
| 452 | } |
| 453 | |
| 454 | const npcEntityId = session.entityId; |
| 455 | this.sessions.delete(characterId | 0); |
| 456 | events.push({ type: "dialogueClose", reason: "end", npcEntityId }); |
| 457 | return { ok: true, events }; |
| 458 | } |
| 459 | |
| 460 | /** |
| 461 | * Soft-take step.itemTakes from the bag (min(have, required)). Returns player-facing notices. |
| 462 | */ |
| 463 | #takeStepItems (characterId, step, events) |
| 464 | { |
| 465 | const takes = step?.itemTakes ?? []; |
| 466 | if (!takes.length) |
| 467 | { return []; } |
| 468 | const parts = []; |
| 469 | for (const take of takes) |
| 470 | { |
| 471 | const bag = this.#loadBag(characterId); |
| 472 | if (!bag) |
| 473 | { continue; } |
| 474 | const itemId = take.itemId | 0; |
| 475 | const want = Math.max(1, Number(take.quantity) || 1); |
| 476 | const def = itemDefinition(itemId); |
| 477 | const displayName = def?.displayName ?? `Item ${itemId}`; |
| 478 | const result = takeMatchingUpToFromSlots(bag.inventory, { |
| 479 | itemId, |
| 480 | quantity: want, |
| 481 | compact: false |
| 482 | }); |
| 483 | if (!result.ok || result.takenQuantity <= 0) |
| 484 | { continue; } |
| 485 | bag.inventory = result.slots; |
| 486 | this.#persistBag(characterId, bag); |
| 487 | events.push({ type: "inventoryDirty" }); |
| 488 | parts.push({ displayName, quantity: result.takenQuantity }); |
| 489 | } |
| 490 | const message = formatDialogueTakeMessage(parts); |
| 491 | return message ? [message] : []; |
| 492 | } |
| 493 | |
| 494 | /** |
| 495 | * Grant step.itemRewards into bag (overflow → bank/vault). Returns player-facing notices. |
| 496 | */ |
| 497 | #grantStepItemRewards (characterId, step, events) |
| 498 | { |
| 499 | const rewards = step?.itemRewards ?? []; |
| 500 | if (!rewards.length) |
| 501 | { return []; } |
| 502 | const bagParts = []; |
| 503 | const bankParts = []; |
| 504 | for (const reward of rewards) |
| 505 | { |
| 506 | const bag = this.#loadBag(characterId); |
| 507 | if (!bag) |
| 508 | { continue; } |
| 509 | const itemId = reward.itemId | 0; |
| 510 | const def = itemDefinition(itemId); |
| 511 | const quantity = Math.max(1, Number(reward.quantity) || 1); |
| 512 | const displayName = def?.displayName ?? `Item ${itemId}`; |
| 513 | const stack = attachOrigins({ |
| 514 | itemId, |
| 515 | quantity, |
| 516 | origins: [{ origin: godsOrigin(), quantity }] |
| 517 | }); |
| 518 | const result = insertStack(bag.inventory, stack, def); |
| 519 | bag.inventory = result.slots; |
| 520 | const intoBag = quantity - Math.max(0, result.remainder | 0); |
| 521 | let intoBank = 0; |
| 522 | if (result.remainder > 0) |
| 523 | { |
| 524 | const vaultResult = insertStackGrowable( |
| 525 | bag.vault, |
| 526 | attachOrigins({ |
| 527 | itemId, |
| 528 | quantity: result.remainder, |
| 529 | origins: [{ origin: godsOrigin(), quantity: result.remainder }] |
| 530 | }), |
| 531 | def |
| 532 | ); |
| 533 | bag.vault = vaultResult.slots; |
| 534 | intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0); |
| 535 | } |
| 536 | this.#persistBag(characterId, bag); |
| 537 | events.push({ type: "inventoryDirty" }); |
| 538 | if (intoBag > 0) |
| 539 | { bagParts.push({ displayName, quantity: intoBag }); } |
| 540 | if (intoBank > 0) |
| 541 | { bankParts.push({ displayName, quantity: intoBank }); } |
| 542 | } |
| 543 | const messages = []; |
| 544 | const bagMsg = formatDialogueRewardMessage(bagParts, "bag"); |
| 545 | const bankMsg = formatDialogueRewardMessage(bankParts, "bank"); |
| 546 | if (bagMsg) |
| 547 | { messages.push(bagMsg); } |
| 548 | if (bankMsg) |
| 549 | { messages.push(bankMsg); } |
| 550 | return messages; |
| 551 | } |
| 552 | |
| 553 | /** Start step.questRewards; returns player-facing notices for newly started quests. */ |
| 554 | #grantStepQuestRewards (characterId, step, playerView, events) |
| 555 | { |
| 556 | const rewards = step?.questRewards ?? []; |
| 557 | if (!rewards.length) |
| 558 | { return []; } |
| 559 | const titles = []; |
| 560 | for (const questId of rewards) |
| 561 | { |
| 562 | const current = this.stateDb.getQuestState(characterId, questId); |
| 563 | if (current.state !== "not-started") |
| 564 | { continue; } |
| 565 | const def = this.content.quest(questId); |
| 566 | if (!def) |
| 567 | { continue; } |
| 568 | this.startQuest(characterId, questId, playerView, events); |
| 569 | titles.push(def.title || def.questId); |
| 570 | } |
| 571 | const message = formatDialogueQuestRewardMessage(titles); |
| 572 | return message ? [message] : []; |
| 573 | } |
| 574 | |
| 575 | #loadBag (characterId) |
| 576 | { |
| 577 | const onlineId = this.simulation.characterEntities.get(characterId | 0); |
| 578 | const bag = onlineId |
| 579 | ? this.simulation.bagOf(onlineId) |
| 580 | : this.stateDb.getBag(characterId); |
| 581 | return bag; |
| 582 | } |
| 583 | |
| 584 | #playerDialogueIdentity (characterId) |
| 585 | { |
| 586 | const row = this.stateDb.getCharacter(characterId | 0); |
| 587 | return { |
| 588 | firstName: String(row?.first_name ?? "").trim(), |
| 589 | lastName: String(row?.last_name ?? "").trim(), |
| 590 | sex: row?.sex === "female" ? "female" : "male" |
| 591 | }; |
| 592 | } |
| 593 | |
| 594 | #persistBag (characterId, bag) |
| 595 | { |
| 596 | this.stateDb.saveBag(characterId, bag); |
| 597 | const onlineId = this.simulation.characterEntities.get(characterId | 0); |
| 598 | if (onlineId) |
| 599 | { |
| 600 | this.simulation.applyBag?.(onlineId, bag); |
| 601 | this.simulation.pushInventory?.(characterId, bag); |
| 602 | } |
| 603 | } |
| 604 | |
| 605 | #applyEffects (characterId, effects, playerView, events) |
| 606 | { |
| 607 | if (!Array.isArray(effects) || effects.length === 0) |
| 608 | { return; } |
| 609 | for (const effect of effects) |
| 610 | { |
| 611 | if (effect.kind === EffectKind.giveItem) |
| 612 | { |
| 613 | const bag = this.#loadBag(characterId); |
| 614 | if (!bag) |
| 615 | { continue; } |
| 616 | const def = itemDefinition(effect.itemId | 0); |
| 617 | const quantity = Math.max(1, Number(effect.quantity) || 1); |
| 618 | const stack = attachOrigins({ |
| 619 | itemId: effect.itemId | 0, |
| 620 | quantity, |
| 621 | origins: [{ origin: godsOrigin(), quantity }] |
| 622 | }); |
| 623 | if (effect.toBank) |
| 624 | { |
| 625 | const vaultResult = insertStackGrowable(bag.vault ?? [], stack, def); |
| 626 | bag.vault = vaultResult.slots; |
| 627 | } |
| 628 | else |
| 629 | { |
| 630 | const result = insertStack(bag.inventory, stack, def); |
| 631 | bag.inventory = result.slots; |
| 632 | if (result.remainder > 0) |
| 633 | { |
| 634 | const vaultResult = insertStackGrowable( |
| 635 | bag.vault ?? [], |
| 636 | attachOrigins({ |
| 637 | itemId: effect.itemId | 0, |
| 638 | quantity: result.remainder, |
| 639 | origins: [{ origin: godsOrigin(), quantity: result.remainder }] |
| 640 | }), |
| 641 | def |
| 642 | ); |
| 643 | bag.vault = vaultResult.slots; |
| 644 | } |
| 645 | } |
| 646 | this.#persistBag(characterId, bag); |
| 647 | events.push({ type: "inventoryDirty" }); |
| 648 | } |
| 649 | else if (effect.kind === EffectKind.takeItem) |
| 650 | { |
| 651 | const bag = this.#loadBag(characterId); |
| 652 | if (!bag) |
| 653 | { continue; } |
| 654 | const taken = takeMatchingFromSlots(bag.inventory, { |
| 655 | itemId: effect.itemId | 0, |
| 656 | quantity: Math.max(1, Number(effect.quantity) || 1), |
| 657 | compact: false |
| 658 | }); |
| 659 | if (taken.ok) |
| 660 | { |
| 661 | bag.inventory = taken.slots; |
| 662 | this.#persistBag(characterId, bag); |
| 663 | events.push({ type: "inventoryDirty" }); |
| 664 | } |
| 665 | } |
| 666 | else if (effect.kind === EffectKind.giveXp) |
| 667 | { |
| 668 | const skills = this.stateDb.getSkills(characterId); |
| 669 | if (skills) |
| 670 | { |
| 671 | applySkillXp(skills, effect.skillId, Math.max(0, Number(effect.amount) || 0)); |
| 672 | this.stateDb.saveSkills(characterId, skills); |
| 673 | if (playerView) |
| 674 | { playerView.skills = skills; } |
| 675 | events.push({ type: "skillsDirty" }); |
| 676 | } |
| 677 | } |
| 678 | else if (effect.kind === EffectKind.startQuest) |
| 679 | { this.startQuest(characterId, effect.questId, playerView, events); } |
| 680 | } |
| 681 | } |
| 682 | |
| 683 | startQuest (characterId, questId, playerView, events = []) |
| 684 | { |
| 685 | const def = this.content.quest(questId); |
| 686 | if (!def) |
| 687 | { return; } |
| 688 | const current = this.stateDb.getQuestState(characterId, questId); |
| 689 | if (current.state !== "not-started") |
| 690 | { return; } |
| 691 | const first = def.steps[0]; |
| 692 | this.stateDb.saveQuestState(characterId, questId, first.stepId, { |
| 693 | completedObjectiveIds: [], |
| 694 | counters: {}, |
| 695 | interacts: {}, |
| 696 | completedStepIds: [], |
| 697 | progressFingerprint: "" |
| 698 | }, Date.now(), null); |
| 699 | this.#applyEffects(characterId, first.onEnter, playerView, events); |
| 700 | events.push({ type: "questsDirty", characterId }); |
| 701 | this.#reevaluateQuests(characterId, playerView, events); |
| 702 | } |
| 703 | |
| 704 | /** |
| 705 | * Grant world-settings initial quests when the character has not started or completed them. |
| 706 | */ |
| 707 | ensureInitialQuests (characterId, playerView = null, events = []) |
| 708 | { |
| 709 | const list = normalizeInitialQuests(this.simulation?.settings?.initialQuests); |
| 710 | for (const questId of list) |
| 711 | { this.startQuest(characterId, questId, playerView, events); } |
| 712 | return events; |
| 713 | } |
| 714 | |
| 715 | /** |
| 716 | * Re-check active quest objectives against live bag/position/etc. |
| 717 | * Used when opening the quest log (and wherever progress may have changed offline of dialogue/kills). |
| 718 | */ |
| 719 | reevaluateQuests (characterId, playerView = null, events = []) |
| 720 | { |
| 721 | const view = playerView ?? this.playerViewFor(characterId); |
| 722 | this.#reevaluateQuests(characterId, view, events); |
| 723 | return events; |
| 724 | } |
| 725 | |
| 726 | /** Apply initial quests to every character in state (settings save / apply). */ |
| 727 | grantInitialQuestsToAllCharacters () |
| 728 | { |
| 729 | const events = []; |
| 730 | for (const characterId of this.stateDb.listAllCharacterIds()) |
| 731 | { this.ensureInitialQuests(characterId, null, events); } |
| 732 | return events; |
| 733 | } |
| 734 | |
| 735 | /** |
| 736 | * Final quest rewards: XP + items (bag or bank). Banked items get a Questward letter. |
| 737 | * @returns {{ xp: { skillId: string, displayName: string, amount: number }[], bagItems: { displayName: string, quantity: number }[] }} |
| 738 | */ |
| 739 | #grantQuestCompletionRewards (characterId, def, playerView, events) |
| 740 | { |
| 741 | const xp = []; |
| 742 | const bagItems = []; |
| 743 | const bankItems = []; |
| 744 | const rewards = def?.rewards ?? []; |
| 745 | for (const effect of rewards) |
| 746 | { |
| 747 | if (effect.kind === EffectKind.giveXp) |
| 748 | { |
| 749 | const amount = Math.max(0, Number(effect.amount) || 0) | 0; |
| 750 | if (amount <= 0) |
| 751 | { continue; } |
| 752 | const skillId = String(effect.skillId ?? "").trim(); |
| 753 | if (!skillId) |
| 754 | { continue; } |
| 755 | const onlineId = this.simulation.characterEntities.get(characterId | 0); |
| 756 | let skills = onlineId |
| 757 | ? this.simulation.skillsOf(onlineId) |
| 758 | : this.stateDb.getSkills(characterId); |
| 759 | if (!skills) |
| 760 | { skills = this.stateDb.getSkills(characterId); } |
| 761 | if (!skills) |
| 762 | { continue; } |
| 763 | applySkillXp(skills, skillId, amount); |
| 764 | this.stateDb.saveSkills(characterId, skills); |
| 765 | if (playerView) |
| 766 | { playerView.skills = skills; } |
| 767 | if (onlineId) |
| 768 | { this.simulation.applySkills?.(onlineId, skills); } |
| 769 | const payload = publicSkillsPayload(skills); |
| 770 | this.simulation.pushSkills?.(characterId, payload.skills, payload.combatLevel); |
| 771 | xp.push({ |
| 772 | skillId, |
| 773 | displayName: SKILL_DEFINITIONS[skillId]?.displayName ?? skillId, |
| 774 | amount |
| 775 | }); |
| 776 | continue; |
| 777 | } |
| 778 | if (effect.kind !== EffectKind.giveItem) |
| 779 | { continue; } |
| 780 | const bag = this.#loadBag(characterId); |
| 781 | if (!bag) |
| 782 | { continue; } |
| 783 | const itemId = effect.itemId | 0; |
| 784 | const defItem = itemDefinition(itemId); |
| 785 | const quantity = Math.max(1, Number(effect.quantity) || 1) | 0; |
| 786 | const displayName = defItem |
| 787 | ? itemDisplayName({ itemId, quantity }, defItem) |
| 788 | : `Item ${itemId}`; |
| 789 | const stack = attachOrigins({ |
| 790 | itemId, |
| 791 | quantity, |
| 792 | origins: [{ origin: godsOrigin(), quantity }] |
| 793 | }); |
| 794 | let intoBag = 0; |
| 795 | let intoBank = 0; |
| 796 | if (effect.toBank) |
| 797 | { |
| 798 | const vaultResult = insertStackGrowable(bag.vault ?? [], stack, defItem); |
| 799 | bag.vault = vaultResult.slots; |
| 800 | intoBank = quantity - Math.max(0, vaultResult.remainder | 0); |
| 801 | } |
| 802 | else |
| 803 | { |
| 804 | const result = insertStack(bag.inventory, stack, defItem); |
| 805 | bag.inventory = result.slots; |
| 806 | intoBag = quantity - Math.max(0, result.remainder | 0); |
| 807 | if (result.remainder > 0) |
| 808 | { |
| 809 | const vaultResult = insertStackGrowable( |
| 810 | bag.vault ?? [], |
| 811 | attachOrigins({ |
| 812 | itemId, |
| 813 | quantity: result.remainder, |
| 814 | origins: [{ origin: godsOrigin(), quantity: result.remainder }] |
| 815 | }), |
| 816 | defItem |
| 817 | ); |
| 818 | bag.vault = vaultResult.slots; |
| 819 | intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0); |
| 820 | } |
| 821 | } |
| 822 | this.#persistBag(characterId, bag); |
| 823 | events.push({ type: "inventoryDirty" }); |
| 824 | if (intoBag > 0) |
| 825 | { bagItems.push({ displayName, quantity: intoBag, itemId }); } |
| 826 | if (intoBank > 0) |
| 827 | { bankItems.push({ displayName, quantity: intoBank, itemId }); } |
| 828 | } |
| 829 | |
| 830 | if (bankItems.length) |
| 831 | { this.#dispatchQuestBankRewardLetter(characterId, def, bankItems); } |
| 832 | |
| 833 | return { xp, bagItems }; |
| 834 | } |
| 835 | |
| 836 | #dispatchQuestBankRewardLetter (characterId, def, bankItems) |
| 837 | { |
| 838 | const courier = this.simulation.courier; |
| 839 | if (!courier?.enqueueSystemLetter) |
| 840 | { return; } |
| 841 | const row = this.stateDb.getCharacter?.(characterId); |
| 842 | const characterDisplayName = row |
| 843 | ? `${row.first_name ?? ""} ${row.last_name ?? ""}`.trim() |
| 844 | : "Adventurer"; |
| 845 | const originTileX = row?.tile_x | 0; |
| 846 | const originTileY = row?.tile_y | 0; |
| 847 | const originDim = row?.dimension_id ?? undefined; |
| 848 | const bank = courier.nearestBank?.(originTileX, originTileY, originDim); |
| 849 | courier.enqueueSystemLetter({ |
| 850 | characterId: characterId | 0, |
| 851 | originTileX: bank?.tileX ?? originTileX, |
| 852 | originTileY: bank?.tileY ?? originTileY, |
| 853 | originDimensionId: bank?.dimensionId ?? originDim, |
| 854 | authorDisplayName: QUESTWARD_GIFT_AUTHOR, |
| 855 | authorOrganization: QUESTWARD_GIFT_ORG, |
| 856 | body: formatQuestBankRewardLetterBody({ |
| 857 | characterDisplayName, |
| 858 | questTitle: def?.title ?? def?.questId, |
| 859 | items: bankItems |
| 860 | }) |
| 861 | }); |
| 862 | } |
| 863 | |
| 864 | #reevaluateQuests (characterId, playerView, events) |
| 865 | { |
| 866 | const outer = this._transitionedQuestIds == null; |
| 867 | if (outer) |
| 868 | { this._transitionedQuestIds = new Set(); } |
| 869 | try |
| 870 | { |
| 871 | const states = this.stateDb.listQuestStates(characterId) |
| 872 | .filter((row) => isActiveQuestState(row.state)); |
| 873 | for (const row of states) |
| 874 | { |
| 875 | if (this._transitionedQuestIds.has(row.questId)) |
| 876 | { continue; } |
| 877 | const def = this.content.quest(row.questId); |
| 878 | if (!def) |
| 879 | { continue; } |
| 880 | const stepDef = activeQuestStep(def, row.state); |
| 881 | if (!stepDef) |
| 882 | { continue; } |
| 883 | const ctx = this.buildConditionContext(characterId, playerView, row.questId); |
| 884 | if (stepDef.exit?.kind === "branches") |
| 885 | { this.#advanceBranchStep(characterId, def, row, stepDef, ctx, playerView, events); } |
| 886 | else |
| 887 | { this.#advanceLinearStep(characterId, def, row, stepDef, ctx, playerView, events); } |
| 888 | } |
| 889 | } |
| 890 | finally |
| 891 | { |
| 892 | if (outer) |
| 893 | { this._transitionedQuestIds = null; } |
| 894 | } |
| 895 | } |
| 896 | |
| 897 | #advanceLinearStep (characterId, def, row, stepDef, ctx, playerView, events) |
| 898 | { |
| 899 | const completed = new Set(row.progress?.completedObjectiveIds ?? []); |
| 900 | const newlyDone = []; |
| 901 | let changed = false; |
| 902 | for (const obj of stepDef.objectives) |
| 903 | { |
| 904 | if (completed.has(obj.objectiveId)) |
| 905 | { continue; } |
| 906 | if (evaluateConditionSet(obj.when, ctx)) |
| 907 | { |
| 908 | completed.add(obj.objectiveId); |
| 909 | newlyDone.push(obj); |
| 910 | changed = true; |
| 911 | } |
| 912 | } |
| 913 | const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx); |
| 914 | const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? ""); |
| 915 | const progress = { |
| 916 | ...row.progress, |
| 917 | completedObjectiveIds: [...completed], |
| 918 | progressFingerprint: fingerprint, |
| 919 | completedStepIds: deriveCompletedStepIds(def, row.state, row.progress) |
| 920 | }; |
| 921 | const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId)); |
| 922 | for (const obj of newlyDone) |
| 923 | { |
| 924 | events.push({ |
| 925 | type: "questObjectiveComplete", |
| 926 | questId: row.questId, |
| 927 | objectiveId: obj.objectiveId, |
| 928 | text: obj.text || "Objective" |
| 929 | }); |
| 930 | } |
| 931 | if (allDone && this.#leaveStep(characterId, def, row, stepDef, null, playerView, events)) |
| 932 | { return; } |
| 933 | if (!changed && !progressChanged) |
| 934 | { return; } |
| 935 | this.#saveActiveProgress(characterId, def, row, progress); |
| 936 | events.push({ type: "questsDirty", characterId }); |
| 937 | } |
| 938 | |
| 939 | #advanceBranchStep (characterId, def, row, stepDef, ctx, playerView, events) |
| 940 | { |
| 941 | const branches = stepDef.exit?.branches ?? []; |
| 942 | let matched = null; |
| 943 | for (const branch of branches) |
| 944 | { |
| 945 | if (evaluateConditionSet(branch.when, ctx)) |
| 946 | { |
| 947 | matched = branch; |
| 948 | break; |
| 949 | } |
| 950 | } |
| 951 | const fingerprint = objectiveProgressFingerprint(branchProgressRows(branches), ctx); |
| 952 | const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? ""); |
| 953 | if (!matched) |
| 954 | { |
| 955 | if (!progressChanged) |
| 956 | { return; } |
| 957 | this.#saveActiveProgress(characterId, def, row, { |
| 958 | ...row.progress, |
| 959 | progressFingerprint: fingerprint, |
| 960 | completedStepIds: deriveCompletedStepIds(def, row.state, row.progress) |
| 961 | }); |
| 962 | events.push({ type: "questsDirty", characterId }); |
| 963 | return; |
| 964 | } |
| 965 | this.#leaveStep(characterId, def, row, stepDef, matched, playerView, events); |
| 966 | } |
| 967 | |
| 968 | /** |
| 969 | * One hop away from the current step. Returns false when a continue/branch |
| 970 | * names a step that does not exist (stay put; retry next evaluation). |
| 971 | * Empty nextStepId completes the quest. Quest-wide rewards fire only here. |
| 972 | */ |
| 973 | #leaveStep (characterId, def, row, stepDef, branch, playerView, events) |
| 974 | { |
| 975 | const exit = stepDef.exit ?? { kind: "complete" }; |
| 976 | let destination = null; |
| 977 | if (branch) |
| 978 | { |
| 979 | if (branch.nextStepId) |
| 980 | { |
| 981 | destination = def.steps.find((step) => step.stepId === branch.nextStepId) ?? null; |
| 982 | if (!destination) |
| 983 | { return false; } |
| 984 | } |
| 985 | } |
| 986 | else if (exit.kind === "continue" && exit.nextStepId) |
| 987 | { |
| 988 | destination = def.steps.find((step) => step.stepId === exit.nextStepId) ?? null; |
| 989 | if (!destination) |
| 990 | { return false; } |
| 991 | } |
| 992 | this._transitionedQuestIds?.add(row.questId); |
| 993 | const completedStepIds = rememberCompletedStep( |
| 994 | deriveCompletedStepIds(def, row.state, row.progress), |
| 995 | stepDef.stepId |
| 996 | ); |
| 997 | this.#applyEffects(characterId, stepDef.onComplete, playerView, events); |
| 998 | if (branch) |
| 999 | { this.#applyEffects(characterId, branch.effects, playerView, events); } |
| 1000 | const journal = this.stateDb.appendQuestJournal( |
| 1001 | characterId, |
| 1002 | row.questId, |
| 1003 | stepDef.stepId, |
| 1004 | stepDef.completionJournalText |
| 1005 | ); |
| 1006 | if (!destination) |
| 1007 | { |
| 1008 | const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events); |
| 1009 | this.stateDb.saveQuestState(characterId, row.questId, "completed", { |
| 1010 | ...row.progress, |
| 1011 | completedStepIds |
| 1012 | }, row.startedAt, Date.now()); |
| 1013 | events.push({ |
| 1014 | type: "questComplete", |
| 1015 | questId: row.questId, |
| 1016 | title: def.title, |
| 1017 | xp: summary.xp, |
| 1018 | items: summary.bagItems |
| 1019 | }); |
| 1020 | } |
| 1021 | else |
| 1022 | { |
| 1023 | this.stateDb.saveQuestState(characterId, row.questId, destination.stepId, { |
| 1024 | completedObjectiveIds: [], |
| 1025 | counters: {}, |
| 1026 | interacts: {}, |
| 1027 | progressFingerprint: "", |
| 1028 | completedStepIds |
| 1029 | }, row.startedAt, null); |
| 1030 | this.#applyEffects(characterId, destination.onEnter, playerView, events); |
| 1031 | events.push({ |
| 1032 | type: "questStepComplete", |
| 1033 | questId: row.questId, |
| 1034 | title: def.title, |
| 1035 | journalText: journal?.text ?? null |
| 1036 | }); |
| 1037 | } |
| 1038 | events.push({ type: "questsDirty", characterId }); |
| 1039 | return true; |
| 1040 | } |
| 1041 | |
| 1042 | #saveActiveProgress (characterId, def, row, progress) |
| 1043 | { |
| 1044 | const stepId = resolveQuestStepId(def, row.state) ?? row.state; |
| 1045 | const completedStepIds = Array.isArray(progress?.completedStepIds) |
| 1046 | ? progress.completedStepIds |
| 1047 | : deriveCompletedStepIds(def, row.state, row.progress); |
| 1048 | this.stateDb.saveQuestState(characterId, row.questId, stepId, { |
| 1049 | ...progress, |
| 1050 | completedStepIds |
| 1051 | }, row.startedAt, row.completedAt); |
| 1052 | } |
| 1053 | |
| 1054 | noteKill (characterId, { mobTypeId, spawnerId }) |
| 1055 | { |
| 1056 | const events = []; |
| 1057 | const playerView = this.playerViewFor(characterId); |
| 1058 | const states = this.stateDb.listQuestStates(characterId) |
| 1059 | .filter((row) => isActiveQuestState(row.state)); |
| 1060 | for (const row of states) |
| 1061 | { |
| 1062 | const def = this.content.quest(row.questId); |
| 1063 | const stepDef = def ? activeQuestStep(def, row.state) : null; |
| 1064 | if (!stepDef) |
| 1065 | { continue; } |
| 1066 | let changed = false; |
| 1067 | const counters = { ...(row.progress?.counters ?? {}) }; |
| 1068 | for (const set of stepConditionSets(stepDef)) |
| 1069 | { |
| 1070 | for (const clause of set?.all ?? []) |
| 1071 | { |
| 1072 | const c = clause.condition; |
| 1073 | if (!matchesKillCondition(c, mobTypeId, spawnerId)) |
| 1074 | { continue; } |
| 1075 | const key = killKey(c); |
| 1076 | counters[key] = (counters[key] | 0) + 1; |
| 1077 | changed = true; |
| 1078 | } |
| 1079 | } |
| 1080 | if (!changed) |
| 1081 | { continue; } |
| 1082 | this.#saveActiveProgress(characterId, def, row, { |
| 1083 | ...row.progress, |
| 1084 | counters, |
| 1085 | completedStepIds: deriveCompletedStepIds(def, row.state, row.progress) |
| 1086 | }); |
| 1087 | } |
| 1088 | this.#reevaluateQuests(characterId, playerView, events); |
| 1089 | return events; |
| 1090 | } |
| 1091 | } |
| 1092 | |
| 1093 | function activeQuestStep (def, state) |
| 1094 | { |
| 1095 | const stepId = resolveQuestStepId(def, state); |
| 1096 | if (!stepId || stepId === "not-started" || stepId === "completed") |
| 1097 | { return null; } |
| 1098 | return def.steps.find((step) => step.stepId === stepId) ?? null; |
| 1099 | } |
| 1100 | |
| 1101 | function stepConditionSets (stepDef) |
| 1102 | { |
| 1103 | if (stepDef?.exit?.kind === "branches") |
| 1104 | { return (stepDef.exit.branches ?? []).map((branch) => branch.when); } |
| 1105 | return (stepDef?.objectives ?? []).map((obj) => obj.when); |
| 1106 | } |
| 1107 | |
| 1108 | function branchProgressRows (branches) |
| 1109 | { |
| 1110 | return (branches ?? []).map((branch, index) => ({ |
| 1111 | objectiveId: `branch-${index}`, |
| 1112 | when: branch.when |
| 1113 | })); |
| 1114 | } |
| 1115 | |
| 1116 | function publicStepLines (stepDef, completedObjectiveIds, ctx) |
| 1117 | { |
| 1118 | if (stepDef.exit?.kind === "branches") |
| 1119 | { |
| 1120 | return (stepDef.exit.branches ?? []).map((branch, index) => |
| 1121 | { |
| 1122 | const progress = countableObjectiveProgress(branch.when, ctx); |
| 1123 | return { |
| 1124 | objectiveId: `branch-${index}`, |
| 1125 | text: branch.text || branch.label || `Path ${index + 1}`, |
| 1126 | done: false, |
| 1127 | current: progress?.current ?? null, |
| 1128 | required: progress?.required ?? null |
| 1129 | }; |
| 1130 | }); |
| 1131 | } |
| 1132 | return (stepDef.objectives ?? []).map((obj) => |
| 1133 | { |
| 1134 | const done = completedObjectiveIds.includes(obj.objectiveId); |
| 1135 | const progress = countableObjectiveProgress(obj.when, ctx); |
| 1136 | return { |
| 1137 | objectiveId: obj.objectiveId, |
| 1138 | text: obj.text, |
| 1139 | done, |
| 1140 | current: progress?.current ?? null, |
| 1141 | required: progress?.required ?? null |
| 1142 | }; |
| 1143 | }); |
| 1144 | } |
| 1145 | |
| 1146 | function journalPublic (row) |
| 1147 | { |
| 1148 | return { |
| 1149 | entryId: row.entry_id ?? row.entryId, |
| 1150 | questId: row.quest_id ?? row.questId, |
| 1151 | stepId: row.step_id ?? row.stepId, |
| 1152 | text: row.text, |
| 1153 | writtenAt: row.written_at ?? row.writtenAt |
| 1154 | }; |
| 1155 | } |
| 1156 | |
| 1157 | |
| 1158 | function matchesKillCondition (condition, mobTypeId, spawnerId) |
| 1159 | { |
| 1160 | if (!condition || typeof condition !== "object") |
| 1161 | { return false; } |
| 1162 | if (condition.kind === "killMobFromSpawner") |
| 1163 | { |
| 1164 | if (condition.mobTypeId == null || condition.spawnerId == null || spawnerId == null) |
| 1165 | { return false; } |
| 1166 | return String(condition.mobTypeId) === String(mobTypeId) |
| 1167 | && String(condition.spawnerId) === String(spawnerId); |
| 1168 | } |
| 1169 | if (condition.kind === "killCount") |
| 1170 | { |
| 1171 | // Mob-type kills: match type. Legacy JSON may also use spawnerId alone. |
| 1172 | const matchMob = condition.mobTypeId != null && String(condition.mobTypeId) === String(mobTypeId); |
| 1173 | const matchSpawner = condition.spawnerId != null && String(condition.spawnerId) === String(spawnerId); |
| 1174 | return matchMob || matchSpawner; |
| 1175 | } |
| 1176 | return false; |
| 1177 | } |
| 1178 | |
| 1179 | function killKey (condition) |
| 1180 | { |
| 1181 | if (condition.spawnerId) |
| 1182 | { return `spawner:${condition.spawnerId}`; } |
| 1183 | return `mob:${condition.mobTypeId}`; |
| 1184 | } |
| 1185 | |
| 1186 | function interactKey (condition) |
| 1187 | { |
| 1188 | if (condition.tileX != null) |
| 1189 | { return `tile:${condition.tileX},${condition.tileY}`; } |
| 1190 | return `block:${condition.blockTypeId}`; |
| 1191 | } |