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