BlueGit

timfa questward

Files

questward / server / src / quests / runtime.js

runtime.js

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