BlueGit

timfa questward

Merge branch 'feature/quest-objective-progress-events'

timfa Tim Falken · pushed by timfa

Authored 2026-09-06 · 2 months ago

Hash
f2031cc92f1d17d2d1e9f76c3b926b38fecd63dd
9 files changed +330 −10
client/src/play/main.js +3 −0
@@ -2526,6 +2526,9 @@ async function main ()
2526 2526 case MessageType.questStepComplete:
2527 2527 questsUi?.handleStepComplete(message);
2528 2528 break;
2529 case MessageType.questObjectiveComplete:
2530 questsUi?.handleObjectiveComplete?.(message);
2531 break;
2529 2532 case MessageType.questComplete:
2530 2533 questsUi?.handleComplete?.(message);
2531 2534 break;
@@ -2526,6 +2526,9 @@ async function main ()
2526 case MessageType.questStepComplete:
2526 case MessageType.questStepComplete:
2527 questsUi?.handleStepComplete(message);
2527 questsUi?.handleStepComplete(message);
2528 break;
2528 break;
2529 case MessageType.questObjectiveComplete:
2530 questsUi?.handleObjectiveComplete?.(message);
2531 break;
2529 case MessageType.questComplete:
2532 case MessageType.questComplete:
2530 questsUi?.handleComplete?.(message);
2533 questsUi?.handleComplete?.(message);
2531 break;
2534 break;
client/src/play/quests.js +19 −1
@@ -1,6 +1,8 @@
1 1 /**
2 2 * Play HUD Quests list + detail modals + completion popup.
3 3 */
4 import { formatObjectiveDisplayText } from "/shared/quests/objectiveProgress.js";
5
4 6 export function initQuests ({ socket, MessageType, toasts })
5 7 {
6 8 const listBackdrop = document.getElementById("quests-list-backdrop");
@@ -177,7 +179,10 @@ export function initQuests ({ socket, MessageType, toasts })
177 179 for (const obj of quest.step.objectives ?? [])
178 180 {
179 181 const li = document.createElement("li");
180 li.textContent = obj.text || "";
182 const progress = (obj.current != null && obj.required != null)
183 ? { current: obj.current, required: obj.required }
184 : null;
185 li.textContent = formatObjectiveDisplayText(obj.text, progress);
181 186 if (obj.done)
182 187 { li.classList.add("done"); }
183 188 ul.append(li);
@@ -233,6 +238,19 @@ export function initQuests ({ socket, MessageType, toasts })
233 238 }
234 239 });
235 240 },
241 handleObjectiveComplete (message)
242 {
243 const questId = message?.questId;
244 const label = String(message?.text ?? "").trim() || "Objective";
245 toasts?.show(`Objective completed:\n${label}`, {
246 onClick: () =>
247 {
248 showList(false);
249 if (questId)
250 { showDetail(true, questId); }
251 }
252 });
253 },
236 254 handleComplete (message)
237 255 {
238 256 showComplete(true, message);
@@ -1,6 +1,8 @@
1/**
1/**
2 * Play HUD Quests list + detail modals + completion popup.
2 * Play HUD Quests list + detail modals + completion popup.
3 */
3 */
4import { formatObjectiveDisplayText } from "/shared/quests/objectiveProgress.js";
5
4export function initQuests ({ socket, MessageType, toasts })
6export function initQuests ({ socket, MessageType, toasts })
5{
7{
6 const listBackdrop = document.getElementById("quests-list-backdrop");
8 const listBackdrop = document.getElementById("quests-list-backdrop");
@@ -177,7 +179,10 @@ export function initQuests ({ socket, MessageType, toasts })
177 for (const obj of quest.step.objectives ?? [])
179 for (const obj of quest.step.objectives ?? [])
178 {
180 {
179 const li = document.createElement("li");
181 const li = document.createElement("li");
180 li.textContent = obj.text || "";
182 const progress = (obj.current != null && obj.required != null)
183 ? { current: obj.current, required: obj.required }
184 : null;
185 li.textContent = formatObjectiveDisplayText(obj.text, progress);
181 if (obj.done)
186 if (obj.done)
182 { li.classList.add("done"); }
187 { li.classList.add("done"); }
183 ul.append(li);
188 ul.append(li);
@@ -233,6 +238,19 @@ export function initQuests ({ socket, MessageType, toasts })
233 }
238 }
234 });
239 });
235 },
240 },
241 handleObjectiveComplete (message)
242 {
243 const questId = message?.questId;
244 const label = String(message?.text ?? "").trim() || "Objective";
245 toasts?.show(`Objective completed:\n${label}`, {
246 onClick: () =>
247 {
248 showList(false);
249 if (questId)
250 { showDetail(true, questId); }
251 }
252 });
253 },
236 handleComplete (message)
254 handleComplete (message)
237 {
255 {
238 showComplete(true, message);
256 showComplete(true, message);
server/src/gateway/websocket.js +16 −0
@@ -1783,6 +1783,22 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1783 1783 }
1784 1784 continue;
1785 1785 }
1786 if (event.type === "quest-objective-complete")
1787 {
1788 const session = event.sessionId != null
1789 ? sessions.get(event.sessionId)
1790 : [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1791 if (session)
1792 {
1793 send(session, {
1794 type: MessageType.questObjectiveComplete,
1795 questId: event.questId,
1796 objectiveId: event.objectiveId,
1797 text: event.text
1798 });
1799 }
1800 continue;
1801 }
1786 1802 if (event.type === "quest-complete")
1787 1803 {
1788 1804 const session = event.sessionId != null
@@ -1783,6 +1783,22 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1783 }
1783 }
1784 continue;
1784 continue;
1785 }
1785 }
1786 if (event.type === "quest-objective-complete")
1787 {
1788 const session = event.sessionId != null
1789 ? sessions.get(event.sessionId)
1790 : [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1791 if (session)
1792 {
1793 send(session, {
1794 type: MessageType.questObjectiveComplete,
1795 questId: event.questId,
1796 objectiveId: event.objectiveId,
1797 text: event.text
1798 });
1799 }
1800 continue;
1801 }
1786 if (event.type === "quest-complete")
1802 if (event.type === "quest-complete")
1787 {
1803 {
1788 const session = event.sessionId != null
1804 const session = event.sessionId != null
server/src/quests/runtime.js +45 −8
@@ -1,5 +1,9 @@
1 1 import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
2 2 import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
3 import {
4 countableObjectiveProgress,
5 objectiveProgressFingerprint
6 } from "../../../shared/quests/objectiveProgress.js";
3 7 import { countItemInSlots, insertStack, takeMatchingFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
4 8 import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
5 9 import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
@@ -45,6 +49,7 @@ export class QuestRuntime
45 49 const states = this.stateDb.listQuestStates(characterId)
46 50 .filter((row) => row.state !== "not-started");
47 51 const quests = [];
52 const playerView = this.playerViewFor(characterId);
48 53 for (const row of states)
49 54 {
50 55 const def = this.content.quest(row.questId);
@@ -64,6 +69,9 @@ export class QuestRuntime
64 69 const stepIndex = typeof row.state === "number" ? row.state : null;
65 70 const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null;
66 71 const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];
72 const ctx = stepDef
73 ? this.buildConditionContext(characterId, playerView, row.questId)
74 : null;
67 75 quests.push({
68 76 questId: def.questId,
69 77 title: def.title,
@@ -75,11 +83,18 @@ export class QuestRuntime
75 83 stepId: stepDef.stepId,
76 84 title: stepDef.title,
77 85 description: stepDef.description,
78 objectives: stepDef.objectives.map((obj) => ({
79 objectiveId: obj.objectiveId,
80 text: obj.text,
81 done: completedObjectiveIds.includes(obj.objectiveId)
82 }))
86 objectives: stepDef.objectives.map((obj) =>
87 {
88 const done = completedObjectiveIds.includes(obj.objectiveId);
89 const progress = countableObjectiveProgress(obj.when, ctx);
90 return {
91 objectiveId: obj.objectiveId,
92 text: obj.text,
93 done,
94 current: progress?.current ?? null,
95 required: progress?.required ?? null
96 };
97 })
83 98 }
84 99 : null,
85 100 journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)
@@ -762,6 +777,7 @@ export class QuestRuntime
762 777 { continue; }
763 778 const ctx = this.buildConditionContext(characterId, playerView, row.questId);
764 779 const completed = new Set(row.progress?.completedObjectiveIds ?? []);
780 const newlyDone = [];
765 781 let changed = false;
766 782 for (const obj of stepDef.objectives)
767 783 {
@@ -770,14 +786,27 @@ export class QuestRuntime
770 786 if (evaluateConditionSet(obj.when, ctx))
771 787 {
772 788 completed.add(obj.objectiveId);
789 newlyDone.push(obj);
773 790 changed = true;
774 791 }
775 792 }
776 if (!changed)
793 const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);
794 const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
795 if (!changed && !progressChanged)
777 796 { continue; }
797 for (const obj of newlyDone)
798 {
799 events.push({
800 type: "questObjectiveComplete",
801 questId: row.questId,
802 objectiveId: obj.objectiveId,
803 text: obj.text || "Objective"
804 });
805 }
778 806 const progress = {
779 807 ...row.progress,
780 completedObjectiveIds: [...completed]
808 completedObjectiveIds: [...completed],
809 progressFingerprint: fingerprint
781 810 };
782 811 const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
783 812 if (!allDone)
@@ -786,6 +815,13 @@ export class QuestRuntime
786 815 events.push({ type: "questsDirty" });
787 816 continue;
788 817 }
818 if (!changed)
819 {
820 // Progress-only update while already fully complete (should not happen).
821 this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
822 events.push({ type: "questsDirty" });
823 continue;
824 }
789 825 this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
790 826 const journal = this.stateDb.appendQuestJournal(
791 827 characterId,
@@ -812,7 +848,8 @@ export class QuestRuntime
812 848 this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {
813 849 completedObjectiveIds: [],
814 850 counters: {},
815 interacts: {}
851 interacts: {},
852 progressFingerprint: ""
816 853 }, row.startedAt, null);
817 854 this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
818 855 events.push({
@@ -1,5 +1,9 @@
1import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
1import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
2import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
2import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
3import {
4 countableObjectiveProgress,
5 objectiveProgressFingerprint
6} from "../../../shared/quests/objectiveProgress.js";
3import { countItemInSlots, insertStack, takeMatchingFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
7import { countItemInSlots, insertStack, takeMatchingFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
4import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
8import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
5import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
9import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
@@ -45,6 +49,7 @@ export class QuestRuntime
45 const states = this.stateDb.listQuestStates(characterId)
49 const states = this.stateDb.listQuestStates(characterId)
46 .filter((row) => row.state !== "not-started");
50 .filter((row) => row.state !== "not-started");
47 const quests = [];
51 const quests = [];
52 const playerView = this.playerViewFor(characterId);
48 for (const row of states)
53 for (const row of states)
49 {
54 {
50 const def = this.content.quest(row.questId);
55 const def = this.content.quest(row.questId);
@@ -64,6 +69,9 @@ export class QuestRuntime
64 const stepIndex = typeof row.state === "number" ? row.state : null;
69 const stepIndex = typeof row.state === "number" ? row.state : null;
65 const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null;
70 const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null;
66 const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];
71 const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];
72 const ctx = stepDef
73 ? this.buildConditionContext(characterId, playerView, row.questId)
74 : null;
67 quests.push({
75 quests.push({
68 questId: def.questId,
76 questId: def.questId,
69 title: def.title,
77 title: def.title,
@@ -75,11 +83,18 @@ export class QuestRuntime
75 stepId: stepDef.stepId,
83 stepId: stepDef.stepId,
76 title: stepDef.title,
84 title: stepDef.title,
77 description: stepDef.description,
85 description: stepDef.description,
78 objectives: stepDef.objectives.map((obj) => ({
86 objectives: stepDef.objectives.map((obj) =>
79 objectiveId: obj.objectiveId,
87 {
80 text: obj.text,
88 const done = completedObjectiveIds.includes(obj.objectiveId);
81 done: completedObjectiveIds.includes(obj.objectiveId)
89 const progress = countableObjectiveProgress(obj.when, ctx);
82 }))
90 return {
91 objectiveId: obj.objectiveId,
92 text: obj.text,
93 done,
94 current: progress?.current ?? null,
95 required: progress?.required ?? null
96 };
97 })
83 }
98 }
84 : null,
99 : null,
85 journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)
100 journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)
@@ -762,6 +777,7 @@ export class QuestRuntime
762 { continue; }
777 { continue; }
763 const ctx = this.buildConditionContext(characterId, playerView, row.questId);
778 const ctx = this.buildConditionContext(characterId, playerView, row.questId);
764 const completed = new Set(row.progress?.completedObjectiveIds ?? []);
779 const completed = new Set(row.progress?.completedObjectiveIds ?? []);
780 const newlyDone = [];
765 let changed = false;
781 let changed = false;
766 for (const obj of stepDef.objectives)
782 for (const obj of stepDef.objectives)
767 {
783 {
@@ -770,14 +786,27 @@ export class QuestRuntime
770 if (evaluateConditionSet(obj.when, ctx))
786 if (evaluateConditionSet(obj.when, ctx))
771 {
787 {
772 completed.add(obj.objectiveId);
788 completed.add(obj.objectiveId);
789 newlyDone.push(obj);
773 changed = true;
790 changed = true;
774 }
791 }
775 }
792 }
776 if (!changed)
793 const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);
794 const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
795 if (!changed && !progressChanged)
777 { continue; }
796 { continue; }
797 for (const obj of newlyDone)
798 {
799 events.push({
800 type: "questObjectiveComplete",
801 questId: row.questId,
802 objectiveId: obj.objectiveId,
803 text: obj.text || "Objective"
804 });
805 }
778 const progress = {
806 const progress = {
779 ...row.progress,
807 ...row.progress,
780 completedObjectiveIds: [...completed]
808 completedObjectiveIds: [...completed],
809 progressFingerprint: fingerprint
781 };
810 };
782 const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
811 const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
783 if (!allDone)
812 if (!allDone)
@@ -786,6 +815,13 @@ export class QuestRuntime
786 events.push({ type: "questsDirty" });
815 events.push({ type: "questsDirty" });
787 continue;
816 continue;
788 }
817 }
818 if (!changed)
819 {
820 // Progress-only update while already fully complete (should not happen).
821 this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
822 events.push({ type: "questsDirty" });
823 continue;
824 }
789 this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
825 this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
790 const journal = this.stateDb.appendQuestJournal(
826 const journal = this.stateDb.appendQuestJournal(
791 characterId,
827 characterId,
@@ -812,7 +848,8 @@ export class QuestRuntime
812 this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {
848 this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {
813 completedObjectiveIds: [],
849 completedObjectiveIds: [],
814 counters: {},
850 counters: {},
815 interacts: {}
851 interacts: {},
852 progressFingerprint: ""
816 }, row.startedAt, null);
853 }, row.startedAt, null);
817 this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
854 this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
818 events.push({
855 events.push({
server/src/simulation/simulation.js +51 −1
@@ -85,6 +85,8 @@ export class Simulation
85 85 this.commandQueue = [];
86 86 this.replication = [];
87 87 this.pendingPrivate = [];
88 /** @type {Set<number>} */
89 this.questReevalCharacterIds = new Set();
88 90 this.courier = null;
89 91 this.market = null;
90 92 this.altarTiles = [];
@@ -417,6 +419,7 @@ export class Simulation
417 419 { events.push(...this.trade.step(now)); }
418 420
419 421 this.#syncGhosts();
422 events.push(...this.#flushQuestReevaluations());
420 423 events.push(...this.pendingPrivate.splice(0));
421 424 return { now, events, replication: this.drainReplication() };
422 425 }
@@ -1084,11 +1087,14 @@ export class Simulation
1084 1087 const record = this.directory.get(entityId);
1085 1088 if (!record)
1086 1089 { return null; }
1087 return this.workers[record.workerId].call({
1090 const result = this.workers[record.workerId].call({
1088 1091 type: WorkerMessage.applyBag,
1089 1092 entityId,
1090 1093 bag
1091 1094 });
1095 if (record.characterId)
1096 { this.#markQuestReeval(record.characterId); }
1097 return result;
1092 1098 }
1093 1099
1094 1100 applySkills (entityId, skills)
@@ -2058,6 +2064,17 @@ export class Simulation
2058 2064 });
2059 2065 needSnapshot = true;
2060 2066 }
2067 else if (event.type === "questObjectiveComplete")
2068 {
2069 out.push({
2070 type: "quest-objective-complete",
2071 sessionId: sid,
2072 characterId: cid,
2073 questId: event.questId,
2074 objectiveId: event.objectiveId,
2075 text: event.text
2076 });
2077 }
2061 2078 else if (event.type === "questsDirty")
2062 2079 { needSnapshot = true; }
2063 2080 else if (event.type === "inventoryDirty" && cid != null)
@@ -3241,6 +3258,38 @@ export class Simulation
3241 3258 { return; }
3242 3259 this.stateDb.saveSkills(event.characterId, { xp: event.stored });
3243 3260 this.pushSkills(event.characterId, event.skills ?? [], event.combatLevel ?? 0);
3261 this.#markQuestReeval(event.characterId);
3262 }
3263
3264 #markQuestReeval (characterId)
3265 {
3266 const id = characterId | 0;
3267 if (!id || !this.quests)
3268 { return; }
3269 this.questReevalCharacterIds.add(id);
3270 }
3271
3272 #flushQuestReevaluations ()
3273 {
3274 if (!this.quests || this.questReevalCharacterIds.size === 0)
3275 { return []; }
3276 const out = [];
3277 // Effects from completions (e.g. giveItem) can mark again; iterate a few times.
3278 for (let pass = 0; pass < 8 && this.questReevalCharacterIds.size > 0; pass++)
3279 {
3280 const batch = [...this.questReevalCharacterIds];
3281 this.questReevalCharacterIds.clear();
3282 for (const characterId of batch)
3283 {
3284 out.push(...this.#mapQuestPrivateEvents(
3285 this.quests.reevaluateQuests(characterId),
3286 null,
3287 characterId
3288 ));
3289 }
3290 }
3291 this.questReevalCharacterIds.clear();
3292 return out;
3244 3293 }
3245 3294
3246 3295 #applySpellsUpdated (event)
@@ -3419,6 +3468,7 @@ export class Simulation
3419 3468 vault: bag.vault,
3420 3469 vaultReserved: bag.vaultReserved
3421 3470 });
3471 this.#markQuestReeval(characterId);
3422 3472 }
3423 3473
3424 3474 releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null)
@@ -85,6 +85,8 @@ export class Simulation
85 this.commandQueue = [];
85 this.commandQueue = [];
86 this.replication = [];
86 this.replication = [];
87 this.pendingPrivate = [];
87 this.pendingPrivate = [];
88 /** @type {Set<number>} */
89 this.questReevalCharacterIds = new Set();
88 this.courier = null;
90 this.courier = null;
89 this.market = null;
91 this.market = null;
90 this.altarTiles = [];
92 this.altarTiles = [];
@@ -417,6 +419,7 @@ export class Simulation
417 { events.push(...this.trade.step(now)); }
419 { events.push(...this.trade.step(now)); }
418
420
419 this.#syncGhosts();
421 this.#syncGhosts();
422 events.push(...this.#flushQuestReevaluations());
420 events.push(...this.pendingPrivate.splice(0));
423 events.push(...this.pendingPrivate.splice(0));
421 return { now, events, replication: this.drainReplication() };
424 return { now, events, replication: this.drainReplication() };
422 }
425 }
@@ -1084,11 +1087,14 @@ export class Simulation
1084 const record = this.directory.get(entityId);
1087 const record = this.directory.get(entityId);
1085 if (!record)
1088 if (!record)
1086 { return null; }
1089 { return null; }
1087 return this.workers[record.workerId].call({
1090 const result = this.workers[record.workerId].call({
1088 type: WorkerMessage.applyBag,
1091 type: WorkerMessage.applyBag,
1089 entityId,
1092 entityId,
1090 bag
1093 bag
1091 });
1094 });
1095 if (record.characterId)
1096 { this.#markQuestReeval(record.characterId); }
1097 return result;
1092 }
1098 }
1093
1099
1094 applySkills (entityId, skills)
1100 applySkills (entityId, skills)
@@ -2058,6 +2064,17 @@ export class Simulation
2058 });
2064 });
2059 needSnapshot = true;
2065 needSnapshot = true;
2060 }
2066 }
2067 else if (event.type === "questObjectiveComplete")
2068 {
2069 out.push({
2070 type: "quest-objective-complete",
2071 sessionId: sid,
2072 characterId: cid,
2073 questId: event.questId,
2074 objectiveId: event.objectiveId,
2075 text: event.text
2076 });
2077 }
2061 else if (event.type === "questsDirty")
2078 else if (event.type === "questsDirty")
2062 { needSnapshot = true; }
2079 { needSnapshot = true; }
2063 else if (event.type === "inventoryDirty" && cid != null)
2080 else if (event.type === "inventoryDirty" && cid != null)
@@ -3241,6 +3258,38 @@ export class Simulation
3241 { return; }
3258 { return; }
3242 this.stateDb.saveSkills(event.characterId, { xp: event.stored });
3259 this.stateDb.saveSkills(event.characterId, { xp: event.stored });
3243 this.pushSkills(event.characterId, event.skills ?? [], event.combatLevel ?? 0);
3260 this.pushSkills(event.characterId, event.skills ?? [], event.combatLevel ?? 0);
3261 this.#markQuestReeval(event.characterId);
3262 }
3263
3264 #markQuestReeval (characterId)
3265 {
3266 const id = characterId | 0;
3267 if (!id || !this.quests)
3268 { return; }
3269 this.questReevalCharacterIds.add(id);
3270 }
3271
3272 #flushQuestReevaluations ()
3273 {
3274 if (!this.quests || this.questReevalCharacterIds.size === 0)
3275 { return []; }
3276 const out = [];
3277 // Effects from completions (e.g. giveItem) can mark again; iterate a few times.
3278 for (let pass = 0; pass < 8 && this.questReevalCharacterIds.size > 0; pass++)
3279 {
3280 const batch = [...this.questReevalCharacterIds];
3281 this.questReevalCharacterIds.clear();
3282 for (const characterId of batch)
3283 {
3284 out.push(...this.#mapQuestPrivateEvents(
3285 this.quests.reevaluateQuests(characterId),
3286 null,
3287 characterId
3288 ));
3289 }
3290 }
3291 this.questReevalCharacterIds.clear();
3292 return out;
3244 }
3293 }
3245
3294
3246 #applySpellsUpdated (event)
3295 #applySpellsUpdated (event)
@@ -3419,6 +3468,7 @@ export class Simulation
3419 vault: bag.vault,
3468 vault: bag.vault,
3420 vaultReserved: bag.vaultReserved
3469 vaultReserved: bag.vaultReserved
3421 });
3470 });
3471 this.#markQuestReeval(characterId);
3422 }
3472 }
3423
3473
3424 releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null)
3474 releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null)
server/tests/initial-quests.test.js +84 −0
@@ -176,3 +176,87 @@ test("request-quests re-checks hasItem objectives against the live bag", () =>
176 176 finally
177 177 { harness.close(); }
178 178 });
179
180 test("quest snapshot shows partial hasItem counts and bag changes complete objectives", () =>
181 {
182 const harness = makeSimulation({ workerCount: 1 });
183 try
184 {
185 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
186 const playerId = harness.simulation.spawnCharacter(1, character);
187 harness.simulation.step();
188
189 const quest = saveLiveQuest(harness, {
190 questId: "pine-logs",
191 title: "Pine Logs",
192 steps: [{
193 stepId: "step-1",
194 title: "Chop",
195 objectives: [
196 {
197 objectiveId: "obj-logs",
198 text: "Collect Pine Logs",
199 when: { all: [{ condition: { kind: "hasItem", itemId: 5555, quantity: 30 } }] }
200 },
201 {
202 objectiveId: "obj-extra",
203 text: "Keep going",
204 when: { all: [{ condition: { kind: "hasItem", itemId: 5556, quantity: 1 } }] }
205 }
206 ],
207 completionJournalText: "Done."
208 }]
209 });
210 harness.simulation.quests.startQuest(
211 character.character_id,
212 quest.questId,
213 harness.simulation.quests.playerViewFor(character.character_id),
214 []
215 );
216
217 const inventory = emptySlots(INVENTORY_SLOTS);
218 inventory[0] = { itemId: 5555, quantity: 5 };
219 harness.simulation.applyBag(playerId, {
220 inventory,
221 equipment: emptyEquipment(),
222 vault: [],
223 vaultReserved: []
224 });
225 const afterPartial = harness.simulation.step();
226 const partialSnap = (afterPartial.events ?? []).find((e) => e.type === "quests-snapshot");
227 assert.ok(partialSnap, "bag change should refresh quest snapshot");
228 const partialObj = partialSnap.quests
229 .find((q) => q.questId === "pine-logs")
230 ?.step?.objectives?.find((o) => o.objectiveId === "obj-logs");
231 assert.equal(partialObj?.current, 5);
232 assert.equal(partialObj?.required, 30);
233 assert.equal(partialObj?.done, false);
234
235 inventory[0] = { itemId: 5555, quantity: 30 };
236 harness.simulation.applyBag(playerId, {
237 inventory,
238 equipment: emptyEquipment(),
239 vault: [],
240 vaultReserved: []
241 });
242 const afterDone = harness.simulation.step();
243 assert.ok(
244 (afterDone.events ?? []).some((e) =>
245 e.type === "quest-objective-complete"
246 && e.questId === "pine-logs"
247 && e.objectiveId === "obj-logs"
248 && e.text === "Collect Pine Logs"
249 ),
250 "completing an objective emits quest-objective-complete"
251 );
252 const doneSnap = (afterDone.events ?? []).find((e) => e.type === "quests-snapshot");
253 const doneObj = doneSnap?.quests
254 .find((q) => q.questId === "pine-logs")
255 ?.step?.objectives?.find((o) => o.objectiveId === "obj-logs");
256 assert.equal(doneObj?.done, true);
257 assert.equal(doneObj?.current, 30);
258 assert.equal(doneObj?.required, 30);
259 }
260 finally
261 { harness.close(); }
262 });
@@ -176,3 +176,87 @@ test("request-quests re-checks hasItem objectives against the live bag", () =>
176 finally
176 finally
177 { harness.close(); }
177 { harness.close(); }
178});
178});
179
180test("quest snapshot shows partial hasItem counts and bag changes complete objectives", () =>
181{
182 const harness = makeSimulation({ workerCount: 1 });
183 try
184 {
185 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
186 const playerId = harness.simulation.spawnCharacter(1, character);
187 harness.simulation.step();
188
189 const quest = saveLiveQuest(harness, {
190 questId: "pine-logs",
191 title: "Pine Logs",
192 steps: [{
193 stepId: "step-1",
194 title: "Chop",
195 objectives: [
196 {
197 objectiveId: "obj-logs",
198 text: "Collect Pine Logs",
199 when: { all: [{ condition: { kind: "hasItem", itemId: 5555, quantity: 30 } }] }
200 },
201 {
202 objectiveId: "obj-extra",
203 text: "Keep going",
204 when: { all: [{ condition: { kind: "hasItem", itemId: 5556, quantity: 1 } }] }
205 }
206 ],
207 completionJournalText: "Done."
208 }]
209 });
210 harness.simulation.quests.startQuest(
211 character.character_id,
212 quest.questId,
213 harness.simulation.quests.playerViewFor(character.character_id),
214 []
215 );
216
217 const inventory = emptySlots(INVENTORY_SLOTS);
218 inventory[0] = { itemId: 5555, quantity: 5 };
219 harness.simulation.applyBag(playerId, {
220 inventory,
221 equipment: emptyEquipment(),
222 vault: [],
223 vaultReserved: []
224 });
225 const afterPartial = harness.simulation.step();
226 const partialSnap = (afterPartial.events ?? []).find((e) => e.type === "quests-snapshot");
227 assert.ok(partialSnap, "bag change should refresh quest snapshot");
228 const partialObj = partialSnap.quests
229 .find((q) => q.questId === "pine-logs")
230 ?.step?.objectives?.find((o) => o.objectiveId === "obj-logs");
231 assert.equal(partialObj?.current, 5);
232 assert.equal(partialObj?.required, 30);
233 assert.equal(partialObj?.done, false);
234
235 inventory[0] = { itemId: 5555, quantity: 30 };
236 harness.simulation.applyBag(playerId, {
237 inventory,
238 equipment: emptyEquipment(),
239 vault: [],
240 vaultReserved: []
241 });
242 const afterDone = harness.simulation.step();
243 assert.ok(
244 (afterDone.events ?? []).some((e) =>
245 e.type === "quest-objective-complete"
246 && e.questId === "pine-logs"
247 && e.objectiveId === "obj-logs"
248 && e.text === "Collect Pine Logs"
249 ),
250 "completing an objective emits quest-objective-complete"
251 );
252 const doneSnap = (afterDone.events ?? []).find((e) => e.type === "quests-snapshot");
253 const doneObj = doneSnap?.quests
254 .find((q) => q.questId === "pine-logs")
255 ?.step?.objectives?.find((o) => o.objectiveId === "obj-logs");
256 assert.equal(doneObj?.done, true);
257 assert.equal(doneObj?.current, 30);
258 assert.equal(doneObj?.required, 30);
259 }
260 finally
261 { harness.close(); }
262});
server/tests/quests-conditions.test.js +37 −0
@@ -5,6 +5,10 @@ import {
5 5 normalizeConditionSet,
6 6 ConditionKind
7 7 } from "../../shared/quests/conditions.js";
8 import {
9 countableObjectiveProgress,
10 formatObjectiveDisplayText
11 } from "../../shared/quests/objectiveProgress.js";
8 12 import { normalizeQuestDef, normalizeDialogueTree } from "../../shared/quests/normalize.js";
9 13 import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage } from "../../shared/quests/dialogueRewards.js";
10 14
@@ -93,3 +97,36 @@ test("dialogue reward messages bag vs bank and lists", () =>
93 97 "The Alpha and Beta quests have been added to your journal."
94 98 );
95 99 });
100
101 test("countable objective progress for hasItem killCount and skillLevelAtLeast", () =>
102 {
103 const hasItem = normalizeConditionSet({
104 all: [{ condition: { kind: ConditionKind.hasItem, itemId: 10, quantity: 30 } }]
105 });
106 assert.deepEqual(
107 countableObjectiveProgress(hasItem, { countItem: (id) => (id === 10 ? 5 : 0) }),
108 { current: 5, required: 30 }
109 );
110 assert.equal(
111 formatObjectiveDisplayText("Collect Pine Logs", { current: 5, required: 30 }),
112 "Collect Pine Logs (5 / 30)"
113 );
114
115 const kills = normalizeConditionSet({
116 all: [{ condition: { kind: ConditionKind.killCount, mobTypeId: "rat", count: 3 } }]
117 });
118 assert.deepEqual(
119 countableObjectiveProgress(kills, {
120 killCount: (c) => (c.mobTypeId === "rat" ? 2 : 0)
121 }),
122 { current: 2, required: 3 }
123 );
124
125 const skill = normalizeConditionSet({
126 all: [{ condition: { kind: ConditionKind.skillLevelAtLeast, skillId: "woodcutting", level: 20 } }]
127 });
128 assert.deepEqual(
129 countableObjectiveProgress(skill, { skillLevel: (id) => (id === "woodcutting" ? 12 : 1) }),
130 { current: 12, required: 20 }
131 );
132 });
@@ -5,6 +5,10 @@ import {
5 normalizeConditionSet,
5 normalizeConditionSet,
6 ConditionKind
6 ConditionKind
7} from "../../shared/quests/conditions.js";
7} from "../../shared/quests/conditions.js";
8import {
9 countableObjectiveProgress,
10 formatObjectiveDisplayText
11} from "../../shared/quests/objectiveProgress.js";
8import { normalizeQuestDef, normalizeDialogueTree } from "../../shared/quests/normalize.js";
12import { normalizeQuestDef, normalizeDialogueTree } from "../../shared/quests/normalize.js";
9import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage } from "../../shared/quests/dialogueRewards.js";
13import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage } from "../../shared/quests/dialogueRewards.js";
10
14
@@ -93,3 +97,36 @@ test("dialogue reward messages bag vs bank and lists", () =>
93 "The Alpha and Beta quests have been added to your journal."
97 "The Alpha and Beta quests have been added to your journal."
94 );
98 );
95});
99});
100
101test("countable objective progress for hasItem killCount and skillLevelAtLeast", () =>
102{
103 const hasItem = normalizeConditionSet({
104 all: [{ condition: { kind: ConditionKind.hasItem, itemId: 10, quantity: 30 } }]
105 });
106 assert.deepEqual(
107 countableObjectiveProgress(hasItem, { countItem: (id) => (id === 10 ? 5 : 0) }),
108 { current: 5, required: 30 }
109 );
110 assert.equal(
111 formatObjectiveDisplayText("Collect Pine Logs", { current: 5, required: 30 }),
112 "Collect Pine Logs (5 / 30)"
113 );
114
115 const kills = normalizeConditionSet({
116 all: [{ condition: { kind: ConditionKind.killCount, mobTypeId: "rat", count: 3 } }]
117 });
118 assert.deepEqual(
119 countableObjectiveProgress(kills, {
120 killCount: (c) => (c.mobTypeId === "rat" ? 2 : 0)
121 }),
122 { current: 2, required: 3 }
123 );
124
125 const skill = normalizeConditionSet({
126 all: [{ condition: { kind: ConditionKind.skillLevelAtLeast, skillId: "woodcutting", level: 20 } }]
127 });
128 assert.deepEqual(
129 countableObjectiveProgress(skill, { skillLevel: (id) => (id === "woodcutting" ? 12 : 1) }),
130 { current: 12, required: 20 }
131 );
132});
shared/protocol/constants.js +1 −0
@@ -292,6 +292,7 @@ export const MessageType = Object.freeze({
292 292 requestQuests: "REQUEST_QUESTS",
293 293 questsSnapshot: "QUESTS_SNAPSHOT",
294 294 questStepComplete: "QUEST_STEP_COMPLETE",
295 questObjectiveComplete: "QUEST_OBJECTIVE_COMPLETE",
295 296 questComplete: "QUEST_COMPLETE",
296 297 jewelryTeleport: "JEWELRY_TELEPORT",
297 298 tradeRequest: "TRADE_REQUEST",
@@ -292,6 +292,7 @@ export const MessageType = Object.freeze({
292 requestQuests: "REQUEST_QUESTS",
292 requestQuests: "REQUEST_QUESTS",
293 questsSnapshot: "QUESTS_SNAPSHOT",
293 questsSnapshot: "QUESTS_SNAPSHOT",
294 questStepComplete: "QUEST_STEP_COMPLETE",
294 questStepComplete: "QUEST_STEP_COMPLETE",
295 questObjectiveComplete: "QUEST_OBJECTIVE_COMPLETE",
295 questComplete: "QUEST_COMPLETE",
296 questComplete: "QUEST_COMPLETE",
296 jewelryTeleport: "JEWELRY_TELEPORT",
297 jewelryTeleport: "JEWELRY_TELEPORT",
297 tradeRequest: "TRADE_REQUEST",
298 tradeRequest: "TRADE_REQUEST",
shared/quests/objectiveProgress.js added +74 −0
@@ -0,0 +1,74 @@
1 import { ConditionKind } from "./conditions.js";
2
3 /**
4 * Progress for countable objective conditions (hasItem, killCount, skillLevelAtLeast).
5 * Uses the first non-negated countable clause in the ConditionSet.
6 * @returns {{ current: number, required: number } | null}
7 */
8 export function countableObjectiveProgress (when, ctx)
9 {
10 for (const clause of when?.all ?? [])
11 {
12 if (clause?.not)
13 { continue; }
14 const condition = clause?.condition;
15 if (!condition || typeof condition !== "object")
16 { continue; }
17 const progress = countableConditionProgress(condition, ctx);
18 if (progress)
19 { return progress; }
20 }
21 return null;
22 }
23
24 /**
25 * @returns {{ current: number, required: number } | null}
26 */
27 export function countableConditionProgress (condition, ctx)
28 {
29 const kind = condition?.kind;
30 if (kind === ConditionKind.hasItem)
31 {
32 const required = Math.max(1, Number(condition.quantity) || 1);
33 const current = Math.max(0, ctx.countItem?.(condition.itemId) ?? 0);
34 return { current: Math.min(current, required), required };
35 }
36 if (kind === ConditionKind.killCount)
37 {
38 const required = Math.max(1, Number(condition.count) || 1);
39 const current = Math.max(0, ctx.killCount?.(condition) ?? 0);
40 return { current: Math.min(current, required), required };
41 }
42 if (kind === ConditionKind.skillLevelAtLeast)
43 {
44 const required = Math.max(1, Math.min(99, Number(condition.level) || 1));
45 const current = Math.max(1, ctx.skillLevel?.(condition.skillId) ?? 1);
46 return { current: Math.min(current, required), required };
47 }
48 return null;
49 }
50
51 /** Player-facing label: "Collect Logs (5 / 30)" when countable. */
52 export function formatObjectiveDisplayText (text, progress)
53 {
54 const base = String(text ?? "").trim() || "Objective";
55 if (!progress || !(progress.required > 0))
56 { return base; }
57 const current = Math.max(0, progress.current | 0);
58 const required = Math.max(1, progress.required | 0);
59 return `${base} (${current} / ${required})`;
60 }
61
62 /** Fingerprint for detecting progress-only changes without new completions. */
63 export function objectiveProgressFingerprint (objectives, ctx)
64 {
65 const parts = [];
66 for (const obj of objectives ?? [])
67 {
68 const progress = countableObjectiveProgress(obj.when, ctx);
69 if (!progress)
70 { continue; }
71 parts.push(`${obj.objectiveId}:${progress.current}/${progress.required}`);
72 }
73 return parts.join("|");
74 }
@@ -0,0 +1,74 @@
1import { ConditionKind } from "./conditions.js";
2
3/**
4 * Progress for countable objective conditions (hasItem, killCount, skillLevelAtLeast).
5 * Uses the first non-negated countable clause in the ConditionSet.
6 * @returns {{ current: number, required: number } | null}
7 */
8export function countableObjectiveProgress (when, ctx)
9{
10 for (const clause of when?.all ?? [])
11 {
12 if (clause?.not)
13 { continue; }
14 const condition = clause?.condition;
15 if (!condition || typeof condition !== "object")
16 { continue; }
17 const progress = countableConditionProgress(condition, ctx);
18 if (progress)
19 { return progress; }
20 }
21 return null;
22}
23
24/**
25 * @returns {{ current: number, required: number } | null}
26 */
27export function countableConditionProgress (condition, ctx)
28{
29 const kind = condition?.kind;
30 if (kind === ConditionKind.hasItem)
31 {
32 const required = Math.max(1, Number(condition.quantity) || 1);
33 const current = Math.max(0, ctx.countItem?.(condition.itemId) ?? 0);
34 return { current: Math.min(current, required), required };
35 }
36 if (kind === ConditionKind.killCount)
37 {
38 const required = Math.max(1, Number(condition.count) || 1);
39 const current = Math.max(0, ctx.killCount?.(condition) ?? 0);
40 return { current: Math.min(current, required), required };
41 }
42 if (kind === ConditionKind.skillLevelAtLeast)
43 {
44 const required = Math.max(1, Math.min(99, Number(condition.level) || 1));
45 const current = Math.max(1, ctx.skillLevel?.(condition.skillId) ?? 1);
46 return { current: Math.min(current, required), required };
47 }
48 return null;
49}
50
51/** Player-facing label: "Collect Logs (5 / 30)" when countable. */
52export function formatObjectiveDisplayText (text, progress)
53{
54 const base = String(text ?? "").trim() || "Objective";
55 if (!progress || !(progress.required > 0))
56 { return base; }
57 const current = Math.max(0, progress.current | 0);
58 const required = Math.max(1, progress.required | 0);
59 return `${base} (${current} / ${required})`;
60}
61
62/** Fingerprint for detecting progress-only changes without new completions. */
63export function objectiveProgressFingerprint (objectives, ctx)
64{
65 const parts = [];
66 for (const obj of objectives ?? [])
67 {
68 const progress = countableObjectiveProgress(obj.when, ctx);
69 if (!progress)
70 { continue; }
71 parts.push(`${obj.objectiveId}:${progress.current}/${progress.required}`);
72 }
73 return parts.join("|");
74}