feat: branch quest steps and remember which steps were finished
Quest steps gain an exit (continue, branches, or complete). Existing quests keep a linear chain via an implicit exit that is rebuilt on load. Player state stores the current step id, with numeric indexes still resolving, and completed step ids stay in the progress blob across merges and loops. questStepAtLeast becomes hasCompletedStep (or quest started) on load. Co-authored-by: tim <tim@timfalken.com>
@@ -15,8 +15,10 @@ import {
15
15
import { createDimensionCombobox } from "./dimensionCombobox.js";
16
16
import { OVERWORLD_ID } from "/shared/world/dimensions.js";
17
17
18
/** All condition kinds available in the shared editor UI. */
19
export const CONDITION_EDITOR_KINDS = Object.freeze(Object.values(ConditionKind));
18
/** All condition kinds available in the shared editor UI. questStepAtLeast is load-only. */
19
export const CONDITION_EDITOR_KINDS = Object.freeze(
20
Object.values(ConditionKind).filter((kind) => kind !== ConditionKind.questStepAtLeast)
21
);
20
22
21
23
export {
22
24
emptyConditionSet,
@@ -29,10 +31,10 @@ export {
29
31
export function renderConditionSet (when, onChange, ctx = {})
30
32
{
31
33
const wrap = document.createElement("div");
32
const set = normalizeConditionSet(when);
33
const bump = (remount = true) => onChange(set, { remount });
34
34
const questList = Array.isArray(ctx.quests) ? ctx.quests : [];
35
35
const dialogueList = Array.isArray(ctx.dialogues) ? ctx.dialogues : [];
36
const set = normalizeConditionSet(when, { quests: questList });
37
const bump = (remount = true) => onChange(set, { remount });
36
38
const header = document.createElement("div");
37
39
header.className = "content-editor-condition-set-header";
38
40
const title = document.createElement("strong");
@@ -215,17 +217,10 @@ export function renderConditionSet (when, onChange, ctx = {})
215
217
bump(false);
216
218
}));
217
219
}
218
else if (cond.kind === ConditionKind.questStepAtLeast)
220
else if (cond.kind === ConditionKind.hasCompletedStep)
219
221
{
220
row.append(miniField("questId", cond.questId ?? "", (v) =>
221
{
222
cond.questId = v;
223
set.all[index].condition = cond;
224
bump(false);
225
}));
226
row.append(miniField("step", cond.step ?? 1, (v) =>
222
row.append(hasCompletedStepConditionFields(cond, questList, () =>
227
223
{
228
cond.step = Math.max(1, Number(v) || 1);
229
224
set.all[index].condition = cond;
230
225
bump(false);
231
226
}));
@@ -706,22 +701,26 @@ function questStateConditionFields (cond, questList, onChanged)
706
701
stateSelect.replaceChildren();
707
702
const options = [
708
703
{ value: "not-started", label: "not-started" },
709
...((quest?.steps ?? []).map((step, index) => ({
710
value: String(index + 1),
711
label: `Step ${index + 1}: ${step.title || step.stepId}`
704
{ value: "started", label: "started" },
705
...((quest?.steps ?? []).map((step) => ({
706
value: step.stepId,
707
label: questStepMenuLabel(step)
712
708
}))),
713
709
{ value: "completed", label: "completed" }
714
710
];
715
711
let matched = false;
712
const current = cond.state ?? "not-started";
713
let currentKey = current === "not-started" || current === "completed" || current === "started"
714
? current
715
: String(current);
716
const asIndex = Number(currentKey);
717
if (/^\d+$/.test(currentKey) && quest?.steps?.[asIndex - 1])
718
{ currentKey = quest.steps[asIndex - 1].stepId; }
716
719
for (const entry of options)
717
720
{
718
721
const opt = document.createElement("option");
719
722
opt.value = entry.value;
720
723
opt.textContent = entry.label;
721
const current = cond.state ?? "not-started";
722
const currentKey = current === "not-started" || current === "completed"
723
? current
724
: String(Number(current) || current);
725
724
if (entry.value === currentKey)
726
725
{
727
726
opt.selected = true;
@@ -749,17 +748,112 @@ function questStateConditionFields (cond, questList, onChanged)
749
748
});
750
749
stateSelect.addEventListener("change", () =>
751
750
{
752
const raw = stateSelect.value;
753
if (raw === "not-started" || raw === "completed")
754
{ cond.state = raw; }
755
else
756
{ cond.state = Math.max(1, Number(raw) | 0); }
751
cond.state = stateSelect.value;
757
752
onChanged();
758
753
});
759
754
wrap.append(questSelect, stateSelect);
760
755
return wrap;
761
756
}
762
757
758
function questStepMenuLabel (step)
759
{
760
const id = String(step?.stepId ?? "");
761
const title = String(step?.title || step?.label || "").trim();
762
if (title && title !== id)
763
{ return `${title} (${id})`; }
764
return id || "step";
765
}
766
767
/** Quest picker + step id for hasCompletedStep. */
768
function hasCompletedStepConditionFields (cond, questList, onChanged)
769
{
770
const wrap = document.createElement("div");
771
wrap.className = "quest-condition-pair";
772
const questSelect = document.createElement("select");
773
const blank = document.createElement("option");
774
blank.value = "";
775
blank.textContent = "Select quest…";
776
questSelect.append(blank);
777
for (const quest of questList)
778
{
779
const opt = document.createElement("option");
780
opt.value = quest.questId;
781
opt.textContent = quest.title ? `${quest.title} (${quest.questId})` : quest.questId;
782
if (quest.questId === cond.questId)
783
{ opt.selected = true; }
784
questSelect.append(opt);
785
}
786
if (cond.questId && !questList.some((q) => q.questId === cond.questId))
787
{
788
const missing = document.createElement("option");
789
missing.value = cond.questId;
790
missing.textContent = `${cond.questId} (missing)`;
791
missing.selected = true;
792
questSelect.append(missing);
793
}
794
const stepSelect = document.createElement("select");
795
const fillSteps = () =>
796
{
797
const quest = questList.find((q) => q.questId === cond.questId) ?? null;
798
stepSelect.replaceChildren();
799
const steps = quest?.steps ?? [];
800
if (!steps.length)
801
{
802
const empty = document.createElement("option");
803
empty.value = cond.stepId ?? "";
804
empty.textContent = cond.stepId || "No steps";
805
empty.selected = true;
806
stepSelect.append(empty);
807
return;
808
}
809
let matched = false;
810
for (const step of steps)
811
{
812
const opt = document.createElement("option");
813
opt.value = step.stepId;
814
opt.textContent = questStepMenuLabel(step);
815
if (step.stepId === cond.stepId)
816
{
817
opt.selected = true;
818
matched = true;
819
}
820
stepSelect.append(opt);
821
}
822
if (!matched)
823
{
824
if (cond.stepId)
825
{
826
const fallback = document.createElement("option");
827
fallback.value = cond.stepId;
828
fallback.textContent = cond.stepId;
829
fallback.selected = true;
830
stepSelect.append(fallback);
831
}
832
else
833
{
834
cond.stepId = steps[0].stepId;
835
stepSelect.options[0].selected = true;
836
}
837
}
838
};
839
fillSteps();
840
questSelect.addEventListener("change", () =>
841
{
842
cond.questId = questSelect.value;
843
const quest = questList.find((q) => q.questId === cond.questId);
844
cond.stepId = quest?.steps?.[0]?.stepId ?? "";
845
fillSteps();
846
onChanged();
847
});
848
stepSelect.addEventListener("change", () =>
849
{
850
cond.stepId = stepSelect.value;
851
onChanged();
852
});
853
wrap.append(questSelect, stepSelect);
854
return wrap;
855
}
856
763
857
/** Compact searchable item picker for hasItem conditions. */
764
858
function itemConditionPicker (cond, onPicked)
765
859
{
@@ -882,8 +976,8 @@ function defaultCondition (kind)
882
976
case ConditionKind.inDimension:
883
977
case ConditionKind.hasVisitedDimension:
884
978
return { kind, dimensionId: OVERWORLD_ID };
885
case ConditionKind.questStepAtLeast:
886
return { kind, questId: "", step: 1 };
979
case ConditionKind.hasCompletedStep:
980
return { kind, questId: "", stepId: "" };
887
981
case ConditionKind.hpAtLeast:
888
982
case ConditionKind.staminaAtLeast:
889
983
return { kind, amount: 1 };
@@ -15,8 +15,10 @@ import {15
import { createDimensionCombobox } from "./dimensionCombobox.js";15
import { createDimensionCombobox } from "./dimensionCombobox.js";16
import { OVERWORLD_ID } from "/shared/world/dimensions.js";16
import { OVERWORLD_ID } from "/shared/world/dimensions.js";17
17
18
/** All condition kinds available in the shared editor UI. */18
/** All condition kinds available in the shared editor UI. questStepAtLeast is load-only. */19
export const CONDITION_EDITOR_KINDS = Object.freeze(Object.values(ConditionKind));19
export const CONDITION_EDITOR_KINDS = Object.freeze(20
Object.values(ConditionKind).filter((kind) => kind !== ConditionKind.questStepAtLeast)21
);20
22
21
export {23
export {22
emptyConditionSet,24
emptyConditionSet,@@ -29,10 +31,10 @@ export {29
export function renderConditionSet (when, onChange, ctx = {})31
export function renderConditionSet (when, onChange, ctx = {})30
{32
{31
const wrap = document.createElement("div");33
const wrap = document.createElement("div");32
const set = normalizeConditionSet(when);33
const bump = (remount = true) => onChange(set, { remount });34
const questList = Array.isArray(ctx.quests) ? ctx.quests : [];34
const questList = Array.isArray(ctx.quests) ? ctx.quests : [];35
const dialogueList = Array.isArray(ctx.dialogues) ? ctx.dialogues : [];35
const dialogueList = Array.isArray(ctx.dialogues) ? ctx.dialogues : [];36
const set = normalizeConditionSet(when, { quests: questList });37
const bump = (remount = true) => onChange(set, { remount });36
const header = document.createElement("div");38
const header = document.createElement("div");37
header.className = "content-editor-condition-set-header";39
header.className = "content-editor-condition-set-header";38
const title = document.createElement("strong");40
const title = document.createElement("strong");@@ -215,17 +217,10 @@ export function renderConditionSet (when, onChange, ctx = {})215
bump(false);217
bump(false);216
}));218
}));217
}219
}218
else if (cond.kind === ConditionKind.questStepAtLeast)220
else if (cond.kind === ConditionKind.hasCompletedStep)219
{221
{220
row.append(miniField("questId", cond.questId ?? "", (v) =>222
row.append(hasCompletedStepConditionFields(cond, questList, () =>221
{222
cond.questId = v;223
set.all[index].condition = cond;224
bump(false);225
}));226
row.append(miniField("step", cond.step ?? 1, (v) =>227
{223
{228
cond.step = Math.max(1, Number(v) || 1);229
set.all[index].condition = cond;224
set.all[index].condition = cond;230
bump(false);225
bump(false);231
}));226
}));@@ -706,22 +701,26 @@ function questStateConditionFields (cond, questList, onChanged)706
stateSelect.replaceChildren();701
stateSelect.replaceChildren();707
const options = [702
const options = [708
{ value: "not-started", label: "not-started" },703
{ value: "not-started", label: "not-started" },709
...((quest?.steps ?? []).map((step, index) => ({704
{ value: "started", label: "started" },710
value: String(index + 1),705
...((quest?.steps ?? []).map((step) => ({711
label: `Step ${index + 1}: ${step.title || step.stepId}`706
value: step.stepId,707
label: questStepMenuLabel(step)712
}))),708
}))),713
{ value: "completed", label: "completed" }709
{ value: "completed", label: "completed" }714
];710
];715
let matched = false;711
let matched = false;712
const current = cond.state ?? "not-started";713
let currentKey = current === "not-started" || current === "completed" || current === "started"714
? current715
: String(current);716
const asIndex = Number(currentKey);717
if (/^\d+$/.test(currentKey) && quest?.steps?.[asIndex - 1])718
{ currentKey = quest.steps[asIndex - 1].stepId; }716
for (const entry of options)719
for (const entry of options)717
{720
{718
const opt = document.createElement("option");721
const opt = document.createElement("option");719
opt.value = entry.value;722
opt.value = entry.value;720
opt.textContent = entry.label;723
opt.textContent = entry.label;721
const current = cond.state ?? "not-started";722
const currentKey = current === "not-started" || current === "completed"723
? current724
: String(Number(current) || current);725
if (entry.value === currentKey)724
if (entry.value === currentKey)726
{725
{727
opt.selected = true;726
opt.selected = true;@@ -749,17 +748,112 @@ function questStateConditionFields (cond, questList, onChanged)749
});748
});750
stateSelect.addEventListener("change", () =>749
stateSelect.addEventListener("change", () =>751
{750
{752
const raw = stateSelect.value;751
cond.state = stateSelect.value;753
if (raw === "not-started" || raw === "completed")754
{ cond.state = raw; }755
else756
{ cond.state = Math.max(1, Number(raw) | 0); }757
onChanged();752
onChanged();758
});753
});759
wrap.append(questSelect, stateSelect);754
wrap.append(questSelect, stateSelect);760
return wrap;755
return wrap;761
}756
}762
757
758
function questStepMenuLabel (step)759
{760
const id = String(step?.stepId ?? "");761
const title = String(step?.title || step?.label || "").trim();762
if (title && title !== id)763
{ return `${title} (${id})`; }764
return id || "step";765
}766
767
/** Quest picker + step id for hasCompletedStep. */768
function hasCompletedStepConditionFields (cond, questList, onChanged)769
{770
const wrap = document.createElement("div");771
wrap.className = "quest-condition-pair";772
const questSelect = document.createElement("select");773
const blank = document.createElement("option");774
blank.value = "";775
blank.textContent = "Select quest…";776
questSelect.append(blank);777
for (const quest of questList)778
{779
const opt = document.createElement("option");780
opt.value = quest.questId;781
opt.textContent = quest.title ? `${quest.title} (${quest.questId})` : quest.questId;782
if (quest.questId === cond.questId)783
{ opt.selected = true; }784
questSelect.append(opt);785
}786
if (cond.questId && !questList.some((q) => q.questId === cond.questId))787
{788
const missing = document.createElement("option");789
missing.value = cond.questId;790
missing.textContent = `${cond.questId} (missing)`;791
missing.selected = true;792
questSelect.append(missing);793
}794
const stepSelect = document.createElement("select");795
const fillSteps = () =>796
{797
const quest = questList.find((q) => q.questId === cond.questId) ?? null;798
stepSelect.replaceChildren();799
const steps = quest?.steps ?? [];800
if (!steps.length)801
{802
const empty = document.createElement("option");803
empty.value = cond.stepId ?? "";804
empty.textContent = cond.stepId || "No steps";805
empty.selected = true;806
stepSelect.append(empty);807
return;808
}809
let matched = false;810
for (const step of steps)811
{812
const opt = document.createElement("option");813
opt.value = step.stepId;814
opt.textContent = questStepMenuLabel(step);815
if (step.stepId === cond.stepId)816
{817
opt.selected = true;818
matched = true;819
}820
stepSelect.append(opt);821
}822
if (!matched)823
{824
if (cond.stepId)825
{826
const fallback = document.createElement("option");827
fallback.value = cond.stepId;828
fallback.textContent = cond.stepId;829
fallback.selected = true;830
stepSelect.append(fallback);831
}832
else833
{834
cond.stepId = steps[0].stepId;835
stepSelect.options[0].selected = true;836
}837
}838
};839
fillSteps();840
questSelect.addEventListener("change", () =>841
{842
cond.questId = questSelect.value;843
const quest = questList.find((q) => q.questId === cond.questId);844
cond.stepId = quest?.steps?.[0]?.stepId ?? "";845
fillSteps();846
onChanged();847
});848
stepSelect.addEventListener("change", () =>849
{850
cond.stepId = stepSelect.value;851
onChanged();852
});853
wrap.append(questSelect, stepSelect);854
return wrap;855
}856
763
/** Compact searchable item picker for hasItem conditions. */857
/** Compact searchable item picker for hasItem conditions. */764
function itemConditionPicker (cond, onPicked)858
function itemConditionPicker (cond, onPicked)765
{859
{@@ -882,8 +976,8 @@ function defaultCondition (kind)882
case ConditionKind.inDimension:976
case ConditionKind.inDimension:883
case ConditionKind.hasVisitedDimension:977
case ConditionKind.hasVisitedDimension:884
return { kind, dimensionId: OVERWORLD_ID };978
return { kind, dimensionId: OVERWORLD_ID };885
case ConditionKind.questStepAtLeast:979
case ConditionKind.hasCompletedStep:886
return { kind, questId: "", step: 1 };980
return { kind, questId: "", stepId: "" };887
case ConditionKind.hpAtLeast:981
case ConditionKind.hpAtLeast:888
case ConditionKind.staminaAtLeast:982
case ConditionKind.staminaAtLeast:889
return { kind, amount: 1 };983
return { kind, amount: 1 };@@ -1242,7 +1242,9 @@ export function initTileConfigModal ({
1242
1242
itemId: line.itemId,
1243
1243
quantity: Math.max(1, line.quantity | 0)
1244
1244
}));
1245
itemSpawnerWhenDraft = normalizeConditionSet(config.when ?? emptyConditionSet());
1245
itemSpawnerWhenDraft = normalizeConditionSet(config.when ?? emptyConditionSet(), {
1246
quests: typeof getQuests === "function" ? (getQuests() ?? []) : []
1247
});
1246
1248
title.textContent = `Item Spawner · ${ctx.tileX}, ${ctx.tileY}`;
1247
1249
if (socket && MessageType)
1248
1250
{
@@ -1438,7 +1440,9 @@ export function initTileConfigModal ({
1438
1440
{
1439
1441
context = { kind: "door", ...ctx };
1440
1442
const config = ctx.config && typeof ctx.config === "object" ? ctx.config : {};
1441
doorWhenDraft = normalizeConditionSet(config.when ?? config.requirements ?? emptyConditionSet());
1443
doorWhenDraft = normalizeConditionSet(config.when ?? config.requirements ?? emptyConditionSet(), {
1444
quests: typeof getQuests === "function" ? (getQuests() ?? []) : []
1445
});
1442
1446
doorBlockedMessageDraft = String(config.blockedMessage ?? config.denyMessage ?? "").trim();
1443
1447
title.textContent = `Door · ${ctx.tileX}, ${ctx.tileY}`;
1444
1448
if (socket && MessageType)
@@ -1242,7 +1242,9 @@ export function initTileConfigModal ({1242
itemId: line.itemId,1242
itemId: line.itemId,1243
quantity: Math.max(1, line.quantity | 0)1243
quantity: Math.max(1, line.quantity | 0)1244
}));1244
}));1245
itemSpawnerWhenDraft = normalizeConditionSet(config.when ?? emptyConditionSet());1245
itemSpawnerWhenDraft = normalizeConditionSet(config.when ?? emptyConditionSet(), {1246
quests: typeof getQuests === "function" ? (getQuests() ?? []) : []1247
});1246
title.textContent = `Item Spawner · ${ctx.tileX}, ${ctx.tileY}`;1248
title.textContent = `Item Spawner · ${ctx.tileX}, ${ctx.tileY}`;1247
if (socket && MessageType)1249
if (socket && MessageType)1248
{1250
{@@ -1438,7 +1440,9 @@ export function initTileConfigModal ({1438
{1440
{1439
context = { kind: "door", ...ctx };1441
context = { kind: "door", ...ctx };1440
const config = ctx.config && typeof ctx.config === "object" ? ctx.config : {};1442
const config = ctx.config && typeof ctx.config === "object" ? ctx.config : {};1441
doorWhenDraft = normalizeConditionSet(config.when ?? config.requirements ?? emptyConditionSet());1443
doorWhenDraft = normalizeConditionSet(config.when ?? config.requirements ?? emptyConditionSet(), {1444
quests: typeof getQuests === "function" ? (getQuests() ?? []) : []1445
});1442
doorBlockedMessageDraft = String(config.blockedMessage ?? config.denyMessage ?? "").trim();1446
doorBlockedMessageDraft = String(config.blockedMessage ?? config.denyMessage ?? "").trim();1443
title.textContent = `Door · ${ctx.tileX}, ${ctx.tileY}`;1447
title.textContent = `Door · ${ctx.tileX}, ${ctx.tileY}`;1444
if (socket && MessageType)1448
if (socket && MessageType)@@ -8,6 +8,10 @@ import { resolveSkillRequirementLevel } from "../../../shared/combat/combatLevel
8
8
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
9
9
import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
10
10
import { doorHasRequirements, doorRequirementsMet } from "../../../shared/world/doorRequirements.js";
11
import {
12
deriveCompletedStepIds,
13
resolveQuestStepId
14
} from "../../../shared/quests/questProgress.js";
11
15
import { BlockType } from "../../../shared/definitions/tiles.js";
12
16
import { tileToChunk, tileToLocal, tileKey } from "../world/coordinates.js";
13
17
@@ -34,15 +38,25 @@ function floorDiv (value, size)
34
38
* Serializable snapshot stored on Component.conditionAccess.
35
39
* @param {import("../persistence/stateDb.js").StateDb} stateDb
36
40
* @param {number} characterId
41
* @param {{ quest?: Function, allQuests?: Function } | null} [questContent]
37
42
*/
38
export function buildConditionAccessSnapshot (stateDb, characterId)
43
export function buildConditionAccessSnapshot (stateDb, characterId, questContent = null)
39
44
{
40
45
const questStates = Object.create(null);
41
46
const questProgress = Object.create(null);
47
const questSteps = Object.create(null);
48
for (const def of questContent?.allQuests?.() ?? [])
49
{
50
questSteps[def.questId] = (def.steps ?? []).map((step) => step.stepId);
51
}
42
52
for (const row of stateDb.listQuestStates(characterId))
43
53
{
44
questStates[row.questId] = row.state;
45
questProgress[row.questId] = row.progress ?? {};
54
const def = questContent?.quest?.(row.questId) ?? null;
55
questStates[row.questId] = resolveQuestStepId(def, row.state);
56
questProgress[row.questId] = {
57
...(row.progress ?? {}),
58
completedStepIds: deriveCompletedStepIds(def, row.state, row.progress)
59
};
46
60
}
47
61
const dialogueHeard = (stateDb.listDialogueHeard(characterId) ?? []).map(
48
62
(row) => `${row.dialogue_id}\0${row.step_id}`
@@ -56,6 +70,7 @@ export function buildConditionAccessSnapshot (stateDb, characterId)
56
70
return {
57
71
questStates,
58
72
questProgress,
73
questSteps,
59
74
dialogueHeard,
60
75
dialogueTriggers,
61
76
visitedDimensions
@@ -84,6 +99,7 @@ export function buildEntityConditionContext (world, entityId)
84
99
const access = world.ecs.get(handle, Component.conditionAccess) ?? {
85
100
questStates: {},
86
101
questProgress: {},
102
questSteps: {},
87
103
dialogueHeard: [],
88
104
dialogueTriggers: [],
89
105
visitedDimensions: []
@@ -93,6 +109,7 @@ export function buildEntityConditionContext (world, entityId)
93
109
const visited = new Set(access.visitedDimensions ?? []);
94
110
const questStates = access.questStates ?? {};
95
111
const questProgress = access.questProgress ?? {};
112
const questSteps = access.questSteps ?? {};
96
113
return {
97
114
tileX,
98
115
tileY,
@@ -105,6 +122,12 @@ export function buildEntityConditionContext (world, entityId)
105
122
maxStamina: stamina?.max ?? 1,
106
123
countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
107
124
questState: (questId) => questStates[String(questId)] ?? "not-started",
125
questSteps: (questId) => questSteps[String(questId)] ?? null,
126
hasCompletedStep: (questId, stepId) =>
127
{
128
const ids = questProgress[String(questId)]?.completedStepIds ?? [];
129
return ids.includes(String(stepId ?? ""));
130
},
108
131
dialogueHeard: (dialogueId, stepId) => heard.has(`${dialogueId}\0${stepId}`),
109
132
dialogueTriggerLatched: (dialogueId, trigger) => triggers.has(`${dialogueId}\0${trigger}`),
110
133
skillLevel: (skillId) => resolveSkillRequirementLevel(skills ?? {}, skillId),
@@ -8,6 +8,10 @@ import { resolveSkillRequirementLevel } from "../../../shared/combat/combatLevel8
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";8
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";9
import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";9
import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";10
import { doorHasRequirements, doorRequirementsMet } from "../../../shared/world/doorRequirements.js";10
import { doorHasRequirements, doorRequirementsMet } from "../../../shared/world/doorRequirements.js";11
import {12
deriveCompletedStepIds,13
resolveQuestStepId14
} from "../../../shared/quests/questProgress.js";11
import { BlockType } from "../../../shared/definitions/tiles.js";15
import { BlockType } from "../../../shared/definitions/tiles.js";12
import { tileToChunk, tileToLocal, tileKey } from "../world/coordinates.js";16
import { tileToChunk, tileToLocal, tileKey } from "../world/coordinates.js";13
17
@@ -34,15 +38,25 @@ function floorDiv (value, size)34
* Serializable snapshot stored on Component.conditionAccess.38
* Serializable snapshot stored on Component.conditionAccess.35
* @param {import("../persistence/stateDb.js").StateDb} stateDb39
* @param {import("../persistence/stateDb.js").StateDb} stateDb36
* @param {number} characterId40
* @param {number} characterId41
* @param {{ quest?: Function, allQuests?: Function } | null} [questContent]37
*/42
*/38
export function buildConditionAccessSnapshot (stateDb, characterId)43
export function buildConditionAccessSnapshot (stateDb, characterId, questContent = null)39
{44
{40
const questStates = Object.create(null);45
const questStates = Object.create(null);41
const questProgress = Object.create(null);46
const questProgress = Object.create(null);47
const questSteps = Object.create(null);48
for (const def of questContent?.allQuests?.() ?? [])49
{50
questSteps[def.questId] = (def.steps ?? []).map((step) => step.stepId);51
}42
for (const row of stateDb.listQuestStates(characterId))52
for (const row of stateDb.listQuestStates(characterId))43
{53
{44
questStates[row.questId] = row.state;54
const def = questContent?.quest?.(row.questId) ?? null;45
questProgress[row.questId] = row.progress ?? {};55
questStates[row.questId] = resolveQuestStepId(def, row.state);56
questProgress[row.questId] = {57
...(row.progress ?? {}),58
completedStepIds: deriveCompletedStepIds(def, row.state, row.progress)59
};46
}60
}47
const dialogueHeard = (stateDb.listDialogueHeard(characterId) ?? []).map(61
const dialogueHeard = (stateDb.listDialogueHeard(characterId) ?? []).map(48
(row) => `${row.dialogue_id}\0${row.step_id}`62
(row) => `${row.dialogue_id}\0${row.step_id}`@@ -56,6 +70,7 @@ export function buildConditionAccessSnapshot (stateDb, characterId)56
return {70
return {57
questStates,71
questStates,58
questProgress,72
questProgress,73
questSteps,59
dialogueHeard,74
dialogueHeard,60
dialogueTriggers,75
dialogueTriggers,61
visitedDimensions76
visitedDimensions@@ -84,6 +99,7 @@ export function buildEntityConditionContext (world, entityId)84
const access = world.ecs.get(handle, Component.conditionAccess) ?? {99
const access = world.ecs.get(handle, Component.conditionAccess) ?? {85
questStates: {},100
questStates: {},86
questProgress: {},101
questProgress: {},102
questSteps: {},87
dialogueHeard: [],103
dialogueHeard: [],88
dialogueTriggers: [],104
dialogueTriggers: [],89
visitedDimensions: []105
visitedDimensions: []@@ -93,6 +109,7 @@ export function buildEntityConditionContext (world, entityId)93
const visited = new Set(access.visitedDimensions ?? []);109
const visited = new Set(access.visitedDimensions ?? []);94
const questStates = access.questStates ?? {};110
const questStates = access.questStates ?? {};95
const questProgress = access.questProgress ?? {};111
const questProgress = access.questProgress ?? {};112
const questSteps = access.questSteps ?? {};96
return {113
return {97
tileX,114
tileX,98
tileY,115
tileY,@@ -105,6 +122,12 @@ export function buildEntityConditionContext (world, entityId)105
maxStamina: stamina?.max ?? 1,122
maxStamina: stamina?.max ?? 1,106
countItem: (itemId) => countItemInSlots(inventory, itemId | 0),123
countItem: (itemId) => countItemInSlots(inventory, itemId | 0),107
questState: (questId) => questStates[String(questId)] ?? "not-started",124
questState: (questId) => questStates[String(questId)] ?? "not-started",125
questSteps: (questId) => questSteps[String(questId)] ?? null,126
hasCompletedStep: (questId, stepId) =>127
{128
const ids = questProgress[String(questId)]?.completedStepIds ?? [];129
return ids.includes(String(stepId ?? ""));130
},108
dialogueHeard: (dialogueId, stepId) => heard.has(`${dialogueId}\0${stepId}`),131
dialogueHeard: (dialogueId, stepId) => heard.has(`${dialogueId}\0${stepId}`),109
dialogueTriggerLatched: (dialogueId, trigger) => triggers.has(`${dialogueId}\0${trigger}`),132
dialogueTriggerLatched: (dialogueId, trigger) => triggers.has(`${dialogueId}\0${trigger}`),110
skillLevel: (skillId) => resolveSkillRequirementLevel(skills ?? {}, skillId),133
skillLevel: (skillId) => resolveSkillRequirementLevel(skills ?? {}, skillId),@@ -24,7 +24,11 @@ import {
24
24
diffEquipmentStatBonuses,
25
25
equipmentStatBonusMapsEqual
26
26
} from "../../../shared/definitions/equipmentStatCategories.js";
27
import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js";
27
import {
28
normalizeQuestDef,
29
normalizeDialogueTree,
30
questLookupFromRawDefs
31
} from "../../../shared/quests/normalize.js";
28
32
import {
29
33
OVERWORLD_ID,
30
34
normalizeDimensionId,
@@ -533,10 +537,20 @@ export class EditorService
533
537
return out;
534
538
}
535
539
540
#questConditionLookup (extraRaw = null)
541
{
542
const revisionId = this.worldDb.getEditorRevisionId();
543
const raws = this.worldDb.listQuestDefs(revisionId);
544
if (extraRaw)
545
{ raws.push(extraRaw); }
546
return questLookupFromRawDefs(raws);
547
}
548
536
549
loadQuests ()
537
550
{
538
551
const revisionId = this.worldDb.getEditorRevisionId();
539
const quests = this.worldDb.listQuestDefs(revisionId).map((raw) => normalizeQuestDef(raw));
552
const lookup = this.#questConditionLookup();
553
const quests = this.worldDb.listQuestDefs(revisionId).map((raw) => normalizeQuestDef(raw, lookup));
540
554
return {
541
555
revisionId,
542
556
pendingRevisionId: this.worldDb.getPendingRevisionId(),
@@ -549,10 +563,11 @@ export class EditorService
549
563
550
564
saveQuest (raw, editorAdminId)
551
565
{
552
const def = normalizeQuestDef(raw);
566
const lookup = this.#questConditionLookup(raw);
567
const def = normalizeQuestDef(raw, lookup);
553
568
const revisionId = this.worldDb.getEditorRevisionId();
554
569
const previousRaw = this.worldDb.getQuestDef(revisionId, def.questId);
555
const previous = previousRaw ? normalizeQuestDef(previousRaw) : null;
570
const previous = previousRaw ? normalizeQuestDef(previousRaw, lookup) : null;
556
571
const bullets = diffQuests(previous, def);
557
572
const pendingId = this.worldDb.ensurePendingRevision(editorAdminId);
558
573
this.worldDb.saveQuestDef(pendingId, def);
@@ -570,7 +585,7 @@ export class EditorService
570
585
this.worldDb.deleteQuestDef(pendingId, id);
571
586
if (previousRaw)
572
587
{
573
const previous = normalizeQuestDef(previousRaw);
588
const previous = normalizeQuestDef(previousRaw, this.#questConditionLookup());
574
589
this.worldDb.appendQuestChangelog(id, pendingId, editorAdminId, [
575
590
`Quest "${previous.title}" (${id}) deleted.`
576
591
]);
@@ -581,7 +596,8 @@ export class EditorService
581
596
loadDialogues ()
582
597
{
583
598
const revisionId = this.worldDb.getEditorRevisionId();
584
const trees = this.worldDb.listDialogueTrees(revisionId).map((raw) => normalizeDialogueTree(raw));
599
const lookup = this.#questConditionLookup();
600
const trees = this.worldDb.listDialogueTrees(revisionId).map((raw) => normalizeDialogueTree(raw, lookup));
585
601
const assignmentCounts = this.#countDialogueAssignments(revisionId);
586
602
return {
587
603
revisionId,
@@ -597,10 +613,11 @@ export class EditorService
597
613
598
614
saveDialogue (raw, editorAdminId)
599
615
{
600
const tree = normalizeDialogueTree(raw);
616
const lookup = this.#questConditionLookup();
617
const tree = normalizeDialogueTree(raw, lookup);
601
618
const revisionId = this.worldDb.getEditorRevisionId();
602
619
const previousRaw = this.worldDb.getDialogueTree(revisionId, tree.dialogueId);
603
const previous = previousRaw ? normalizeDialogueTree(previousRaw) : null;
620
const previous = previousRaw ? normalizeDialogueTree(previousRaw, lookup) : null;
604
621
const assignmentCounts = this.#countDialogueAssignments(revisionId);
605
622
const assigned = assignmentCounts.get(tree.dialogueId) ?? 0;
606
623
if (tree.unique && assigned > 1)
@@ -643,7 +660,7 @@ export class EditorService
643
660
this.worldDb.deleteDialogueTree(pendingId, id);
644
661
if (previousRaw)
645
662
{
646
const previous = normalizeDialogueTree(previousRaw);
663
const previous = normalizeDialogueTree(previousRaw, this.#questConditionLookup());
647
664
this.worldDb.appendDialogueChangelog(id, pendingId, editorAdminId, [
648
665
`Dialogue "${previous.label}" (${id}) deleted.`
649
666
]);
@@ -659,7 +676,7 @@ export class EditorService
659
676
const trees = new Map(
660
677
this.worldDb.listDialogueTrees(revisionId).map((raw) =>
661
678
{
662
const tree = normalizeDialogueTree(raw);
679
const tree = normalizeDialogueTree(raw, this.#questConditionLookup());
663
680
return [tree.dialogueId, tree];
664
681
})
665
682
);
@@ -24,7 +24,11 @@ import {24
diffEquipmentStatBonuses,24
diffEquipmentStatBonuses,25
equipmentStatBonusMapsEqual25
equipmentStatBonusMapsEqual26
} from "../../../shared/definitions/equipmentStatCategories.js";26
} from "../../../shared/definitions/equipmentStatCategories.js";27
import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js";27
import {28
normalizeQuestDef,29
normalizeDialogueTree,30
questLookupFromRawDefs31
} from "../../../shared/quests/normalize.js";28
import {32
import {29
OVERWORLD_ID,33
OVERWORLD_ID,30
normalizeDimensionId,34
normalizeDimensionId,@@ -533,10 +537,20 @@ export class EditorService533
return out;537
return out;534
}538
}535
539
540
#questConditionLookup (extraRaw = null)541
{542
const revisionId = this.worldDb.getEditorRevisionId();543
const raws = this.worldDb.listQuestDefs(revisionId);544
if (extraRaw)545
{ raws.push(extraRaw); }546
return questLookupFromRawDefs(raws);547
}548
536
loadQuests ()549
loadQuests ()537
{550
{538
const revisionId = this.worldDb.getEditorRevisionId();551
const revisionId = this.worldDb.getEditorRevisionId();539
const quests = this.worldDb.listQuestDefs(revisionId).map((raw) => normalizeQuestDef(raw));552
const lookup = this.#questConditionLookup();553
const quests = this.worldDb.listQuestDefs(revisionId).map((raw) => normalizeQuestDef(raw, lookup));540
return {554
return {541
revisionId,555
revisionId,542
pendingRevisionId: this.worldDb.getPendingRevisionId(),556
pendingRevisionId: this.worldDb.getPendingRevisionId(),@@ -549,10 +563,11 @@ export class EditorService549
563
550
saveQuest (raw, editorAdminId)564
saveQuest (raw, editorAdminId)551
{565
{552
const def = normalizeQuestDef(raw);566
const lookup = this.#questConditionLookup(raw);567
const def = normalizeQuestDef(raw, lookup);553
const revisionId = this.worldDb.getEditorRevisionId();568
const revisionId = this.worldDb.getEditorRevisionId();554
const previousRaw = this.worldDb.getQuestDef(revisionId, def.questId);569
const previousRaw = this.worldDb.getQuestDef(revisionId, def.questId);555
const previous = previousRaw ? normalizeQuestDef(previousRaw) : null;570
const previous = previousRaw ? normalizeQuestDef(previousRaw, lookup) : null;556
const bullets = diffQuests(previous, def);571
const bullets = diffQuests(previous, def);557
const pendingId = this.worldDb.ensurePendingRevision(editorAdminId);572
const pendingId = this.worldDb.ensurePendingRevision(editorAdminId);558
this.worldDb.saveQuestDef(pendingId, def);573
this.worldDb.saveQuestDef(pendingId, def);@@ -570,7 +585,7 @@ export class EditorService570
this.worldDb.deleteQuestDef(pendingId, id);585
this.worldDb.deleteQuestDef(pendingId, id);571
if (previousRaw)586
if (previousRaw)572
{587
{573
const previous = normalizeQuestDef(previousRaw);588
const previous = normalizeQuestDef(previousRaw, this.#questConditionLookup());574
this.worldDb.appendQuestChangelog(id, pendingId, editorAdminId, [589
this.worldDb.appendQuestChangelog(id, pendingId, editorAdminId, [575
`Quest "${previous.title}" (${id}) deleted.`590
`Quest "${previous.title}" (${id}) deleted.`576
]);591
]);@@ -581,7 +596,8 @@ export class EditorService581
loadDialogues ()596
loadDialogues ()582
{597
{583
const revisionId = this.worldDb.getEditorRevisionId();598
const revisionId = this.worldDb.getEditorRevisionId();584
const trees = this.worldDb.listDialogueTrees(revisionId).map((raw) => normalizeDialogueTree(raw));599
const lookup = this.#questConditionLookup();600
const trees = this.worldDb.listDialogueTrees(revisionId).map((raw) => normalizeDialogueTree(raw, lookup));585
const assignmentCounts = this.#countDialogueAssignments(revisionId);601
const assignmentCounts = this.#countDialogueAssignments(revisionId);586
return {602
return {587
revisionId,603
revisionId,@@ -597,10 +613,11 @@ export class EditorService597
613
598
saveDialogue (raw, editorAdminId)614
saveDialogue (raw, editorAdminId)599
{615
{600
const tree = normalizeDialogueTree(raw);616
const lookup = this.#questConditionLookup();617
const tree = normalizeDialogueTree(raw, lookup);601
const revisionId = this.worldDb.getEditorRevisionId();618
const revisionId = this.worldDb.getEditorRevisionId();602
const previousRaw = this.worldDb.getDialogueTree(revisionId, tree.dialogueId);619
const previousRaw = this.worldDb.getDialogueTree(revisionId, tree.dialogueId);603
const previous = previousRaw ? normalizeDialogueTree(previousRaw) : null;620
const previous = previousRaw ? normalizeDialogueTree(previousRaw, lookup) : null;604
const assignmentCounts = this.#countDialogueAssignments(revisionId);621
const assignmentCounts = this.#countDialogueAssignments(revisionId);605
const assigned = assignmentCounts.get(tree.dialogueId) ?? 0;622
const assigned = assignmentCounts.get(tree.dialogueId) ?? 0;606
if (tree.unique && assigned > 1)623
if (tree.unique && assigned > 1)@@ -643,7 +660,7 @@ export class EditorService643
this.worldDb.deleteDialogueTree(pendingId, id);660
this.worldDb.deleteDialogueTree(pendingId, id);644
if (previousRaw)661
if (previousRaw)645
{662
{646
const previous = normalizeDialogueTree(previousRaw);663
const previous = normalizeDialogueTree(previousRaw, this.#questConditionLookup());647
this.worldDb.appendDialogueChangelog(id, pendingId, editorAdminId, [664
this.worldDb.appendDialogueChangelog(id, pendingId, editorAdminId, [648
`Dialogue "${previous.label}" (${id}) deleted.`665
`Dialogue "${previous.label}" (${id}) deleted.`649
]);666
]);@@ -659,7 +676,7 @@ export class EditorService659
const trees = new Map(676
const trees = new Map(660
this.worldDb.listDialogueTrees(revisionId).map((raw) =>677
this.worldDb.listDialogueTrees(revisionId).map((raw) =>661
{678
{662
const tree = normalizeDialogueTree(raw);679
const tree = normalizeDialogueTree(raw, this.#questConditionLookup());663
return [tree.dialogueId, tree];680
return [tree.dialogueId, tree];664
})681
})665
);682
);@@ -11,6 +11,7 @@ import {
11
11
bountyDecayDayKey,
12
12
bountyDecayDaysBetween
13
13
} from "../../../shared/bounty/pricing.js";
14
import { parseStoredQuestState, serializeQuestState } from "../../../shared/quests/questProgress.js";
14
15
15
16
const STATE_SCHEMA = `
16
17
CREATE TABLE IF NOT EXISTS accounts (
@@ -974,11 +975,8 @@ export class StateDatabase
974
975
if (!row)
975
976
{ return { state: "not-started", progress: {}, startedAt: null, completedAt: null }; }
976
977
const progress = JSON.parse(row.progress_blob || "{}");
977
let state = row.state_value;
978
if (state !== "not-started" && state !== "completed")
979
{ state = Number(state) | 0; }
980
978
return {
981
state,
979
state: parseStoredQuestState(row.state_value),
982
980
progress,
983
981
startedAt: row.started_at ?? null,
984
982
completedAt: row.completed_at ?? null
@@ -993,12 +991,9 @@ export class StateDatabase
993
991
WHERE character_id = ?
994
992
`).all(characterId | 0).map((row) =>
995
993
{
996
let state = row.state_value;
997
if (state !== "not-started" && state !== "completed")
998
{ state = Number(state) | 0; }
999
994
return {
1000
995
questId: row.quest_id,
1001
state,
996
state: parseStoredQuestState(row.state_value),
1002
997
progress: JSON.parse(row.progress_blob || "{}"),
1003
998
startedAt: row.started_at ?? null,
1004
999
completedAt: row.completed_at ?? null
@@ -1008,7 +1003,7 @@ export class StateDatabase
1008
1003
1009
1004
saveQuestState (characterId, questId, state, progress = {}, startedAt = null, completedAt = null)
1010
1005
{
1011
const stateValue = state === "not-started" || state === "completed" ? state : String(state | 0);
1006
const stateValue = serializeQuestState(state);
1012
1007
this.db.prepare(`
1013
1008
INSERT INTO character_quest_state
1014
1009
(character_id, quest_id, state_value, progress_blob, started_at, completed_at)
@@ -11,6 +11,7 @@ import {11
bountyDecayDayKey,11
bountyDecayDayKey,12
bountyDecayDaysBetween12
bountyDecayDaysBetween13
} from "../../../shared/bounty/pricing.js";13
} from "../../../shared/bounty/pricing.js";14
import { parseStoredQuestState, serializeQuestState } from "../../../shared/quests/questProgress.js";14
15
15
const STATE_SCHEMA = `16
const STATE_SCHEMA = `16
CREATE TABLE IF NOT EXISTS accounts (17
CREATE TABLE IF NOT EXISTS accounts (@@ -974,11 +975,8 @@ export class StateDatabase974
if (!row)975
if (!row)975
{ return { state: "not-started", progress: {}, startedAt: null, completedAt: null }; }976
{ return { state: "not-started", progress: {}, startedAt: null, completedAt: null }; }976
const progress = JSON.parse(row.progress_blob || "{}");977
const progress = JSON.parse(row.progress_blob || "{}");977
let state = row.state_value;978
if (state !== "not-started" && state !== "completed")979
{ state = Number(state) | 0; }980
return {978
return {981
state,979
state: parseStoredQuestState(row.state_value),982
progress,980
progress,983
startedAt: row.started_at ?? null,981
startedAt: row.started_at ?? null,984
completedAt: row.completed_at ?? null982
completedAt: row.completed_at ?? null@@ -993,12 +991,9 @@ export class StateDatabase993
WHERE character_id = ?991
WHERE character_id = ?994
`).all(characterId | 0).map((row) =>992
`).all(characterId | 0).map((row) =>995
{993
{996
let state = row.state_value;997
if (state !== "not-started" && state !== "completed")998
{ state = Number(state) | 0; }999
return {994
return {1000
questId: row.quest_id,995
questId: row.quest_id,1001
state,996
state: parseStoredQuestState(row.state_value),1002
progress: JSON.parse(row.progress_blob || "{}"),997
progress: JSON.parse(row.progress_blob || "{}"),1003
startedAt: row.started_at ?? null,998
startedAt: row.started_at ?? null,1004
completedAt: row.completed_at ?? null999
completedAt: row.completed_at ?? null@@ -1008,7 +1003,7 @@ export class StateDatabase1008
1003
1009
saveQuestState (characterId, questId, state, progress = {}, startedAt = null, completedAt = null)1004
saveQuestState (characterId, questId, state, progress = {}, startedAt = null, completedAt = null)1010
{1005
{1011
const stateValue = state === "not-started" || state === "completed" ? state : String(state | 0);1006
const stateValue = serializeQuestState(state);1012
this.db.prepare(`1007
this.db.prepare(`1013
INSERT INTO character_quest_state1008
INSERT INTO character_quest_state1014
(character_id, quest_id, state_value, progress_blob, started_at, completed_at)1009
(character_id, quest_id, state_value, progress_blob, started_at, completed_at)@@ -1,4 +1,8 @@
1
import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js";
1
import {
2
normalizeQuestDef,
3
normalizeDialogueTree,
4
questLookupFromRawDefs
5
} from "../../../shared/quests/normalize.js";
2
6
3
7
/** Active-revision quest + dialogue defs for the live sim. */
4
8
export class QuestContentCache
@@ -18,14 +22,16 @@ export class QuestContentCache
18
22
this.dialogues = new Map();
19
23
if (revisionId == null)
20
24
{ return; }
21
for (const raw of this.worldDb.listQuestDefs(revisionId))
25
const questRaws = this.worldDb.listQuestDefs(revisionId);
26
const questLookup = questLookupFromRawDefs(questRaws);
27
for (const raw of questRaws)
22
28
{
23
const def = normalizeQuestDef(raw);
29
const def = normalizeQuestDef(raw, questLookup);
24
30
this.quests.set(def.questId, def);
25
31
}
26
32
for (const raw of this.worldDb.listDialogueTrees(revisionId))
27
33
{
28
const tree = normalizeDialogueTree(raw);
34
const tree = normalizeDialogueTree(raw, questLookup);
29
35
this.dialogues.set(tree.dialogueId, tree);
30
36
}
31
37
}
@@ -1,4 +1,8 @@1
import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js";1
import {2
normalizeQuestDef,3
normalizeDialogueTree,4
questLookupFromRawDefs5
} from "../../../shared/quests/normalize.js";2
6
3
/** Active-revision quest + dialogue defs for the live sim. */7
/** Active-revision quest + dialogue defs for the live sim. */4
export class QuestContentCache8
export class QuestContentCache@@ -18,14 +22,16 @@ export class QuestContentCache18
this.dialogues = new Map();22
this.dialogues = new Map();19
if (revisionId == null)23
if (revisionId == null)20
{ return; }24
{ return; }21
for (const raw of this.worldDb.listQuestDefs(revisionId))25
const questRaws = this.worldDb.listQuestDefs(revisionId);26
const questLookup = questLookupFromRawDefs(questRaws);27
for (const raw of questRaws)22
{28
{23
const def = normalizeQuestDef(raw);29
const def = normalizeQuestDef(raw, questLookup);24
this.quests.set(def.questId, def);30
this.quests.set(def.questId, def);25
}31
}26
for (const raw of this.worldDb.listDialogueTrees(revisionId))32
for (const raw of this.worldDb.listDialogueTrees(revisionId))27
{33
{28
const tree = normalizeDialogueTree(raw);34
const tree = normalizeDialogueTree(raw, questLookup);29
this.dialogues.set(tree.dialogueId, tree);35
this.dialogues.set(tree.dialogueId, tree);30
}36
}31
}37
}@@ -1,4 +1,10 @@
1
1
import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
2
import {
3
deriveCompletedStepIds,
4
isActiveQuestState,
5
rememberCompletedStep,
6
resolveQuestStepId
7
} from "../../../shared/quests/questProgress.js";
2
8
import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
3
9
import {
4
10
countableObjectiveProgress,
@@ -72,8 +78,12 @@ export class QuestRuntime
72
78
});
73
79
continue;
74
80
}
75
const stepIndex = typeof row.state === "number" ? row.state : null;
76
const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null;
81
const stepDef = isActiveQuestState(row.state)
82
? activeQuestStep(def, row.state)
83
: null;
84
const resolvedState = isActiveQuestState(row.state)
85
? (resolveQuestStepId(def, row.state) ?? row.state)
86
: row.state;
77
87
const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];
78
88
const ctx = stepDef
79
89
? this.buildConditionContext(characterId, playerView, row.questId)
@@ -82,25 +92,14 @@ export class QuestRuntime
82
92
questId: def.questId,
83
93
title: def.title,
84
94
orphaned: false,
85
state: row.state,
95
state: resolvedState,
86
96
description: def.description,
87
97
step: stepDef
88
98
? {
89
99
stepId: stepDef.stepId,
90
100
title: stepDef.title,
91
101
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
})
102
objectives: publicStepLines(stepDef, completedObjectiveIds, ctx)
104
103
}
105
104
: null,
106
105
journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)
@@ -178,7 +177,26 @@ export class QuestRuntime
178
177
stamina: playerView?.stamina ?? 0,
179
178
maxStamina: playerView?.maxStamina ?? 1,
180
179
countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
181
questState: (questId) => this.stateDb.getQuestState(characterId, questId).state,
180
questState: (questId) =>
181
{
182
const row = this.stateDb.getQuestState(characterId, questId);
183
return resolveQuestStepId(this.content.quest(questId), row.state);
184
},
185
questSteps: (questId) =>
186
{
187
const def = this.content.quest(questId);
188
return def ? def.steps.map((step) => step.stepId) : null;
189
},
190
hasCompletedStep: (questId, stepId) =>
191
{
192
const row = this.stateDb.getQuestState(characterId, questId);
193
const ids = deriveCompletedStepIds(
194
this.content.quest(questId),
195
row.state,
196
row.progress
197
);
198
return ids.includes(String(stepId ?? ""));
199
},
182
200
dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId),
183
201
dialogueTriggerLatched: (dialogueId, trigger) =>
184
202
this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger),
@@ -670,12 +688,15 @@ export class QuestRuntime
670
688
const current = this.stateDb.getQuestState(characterId, questId);
671
689
if (current.state !== "not-started")
672
690
{ return; }
673
this.stateDb.saveQuestState(characterId, questId, 1, {
691
const first = def.steps[0];
692
this.stateDb.saveQuestState(characterId, questId, first.stepId, {
674
693
completedObjectiveIds: [],
675
694
counters: {},
676
interacts: {}
695
interacts: {},
696
completedStepIds: [],
697
progressFingerprint: ""
677
698
}, Date.now(), null);
678
this.#applyEffects(characterId, def.steps[0]?.onEnter, playerView, events);
699
this.#applyEffects(characterId, first.onEnter, playerView, events);
679
700
events.push({ type: "questsDirty", characterId });
680
701
this.#reevaluateQuests(characterId, playerView, events);
681
702
}
@@ -842,102 +863,192 @@ export class QuestRuntime
842
863
843
864
#reevaluateQuests (characterId, playerView, events)
844
865
{
845
const states = this.stateDb.listQuestStates(characterId)
846
.filter((row) => typeof row.state === "number");
847
for (const row of states)
866
const outer = this._transitionedQuestIds == null;
867
if (outer)
868
{ this._transitionedQuestIds = new Set(); }
869
try
848
870
{
849
const def = this.content.quest(row.questId);
850
if (!def)
851
{ continue; }
852
const stepDef = def.steps[row.state - 1];
853
if (!stepDef)
854
{ continue; }
855
const ctx = this.buildConditionContext(characterId, playerView, row.questId);
856
const completed = new Set(row.progress?.completedObjectiveIds ?? []);
857
const newlyDone = [];
858
let changed = false;
859
for (const obj of stepDef.objectives)
871
const states = this.stateDb.listQuestStates(characterId)
872
.filter((row) => isActiveQuestState(row.state));
873
for (const row of states)
860
874
{
861
if (completed.has(obj.objectiveId))
875
if (this._transitionedQuestIds.has(row.questId))
862
876
{ continue; }
863
if (evaluateConditionSet(obj.when, ctx))
864
{
865
completed.add(obj.objectiveId);
866
newlyDone.push(obj);
867
changed = true;
868
}
877
const def = this.content.quest(row.questId);
878
if (!def)
879
{ continue; }
880
const stepDef = activeQuestStep(def, row.state);
881
if (!stepDef)
882
{ continue; }
883
const ctx = this.buildConditionContext(characterId, playerView, row.questId);
884
if (stepDef.exit?.kind === "branches")
885
{ this.#advanceBranchStep(characterId, def, row, stepDef, ctx, playerView, events); }
886
else
887
{ this.#advanceLinearStep(characterId, def, row, stepDef, ctx, playerView, events); }
869
888
}
870
const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);
871
const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
872
if (!changed && !progressChanged)
889
}
890
finally
891
{
892
if (outer)
893
{ this._transitionedQuestIds = null; }
894
}
895
}
896
897
#advanceLinearStep (characterId, def, row, stepDef, ctx, playerView, events)
898
{
899
const completed = new Set(row.progress?.completedObjectiveIds ?? []);
900
const newlyDone = [];
901
let changed = false;
902
for (const obj of stepDef.objectives)
903
{
904
if (completed.has(obj.objectiveId))
873
905
{ continue; }
874
for (const obj of newlyDone)
875
{
876
events.push({
877
type: "questObjectiveComplete",
878
questId: row.questId,
879
objectiveId: obj.objectiveId,
880
text: obj.text || "Objective"
881
});
882
}
883
const progress = {
884
...row.progress,
885
completedObjectiveIds: [...completed],
886
progressFingerprint: fingerprint
887
};
888
const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
889
if (!allDone)
906
if (evaluateConditionSet(obj.when, ctx))
890
907
{
891
this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
892
events.push({ type: "questsDirty", characterId });
893
continue;
908
completed.add(obj.objectiveId);
909
newlyDone.push(obj);
910
changed = true;
894
911
}
895
if (!changed)
896
{
897
// Progress-only update while already fully complete (should not happen).
898
this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
899
events.push({ type: "questsDirty", characterId });
900
continue;
901
}
902
this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
903
const journal = this.stateDb.appendQuestJournal(
904
characterId,
905
row.questId,
906
stepDef.stepId,
907
stepDef.completionJournalText
908
);
909
const nextIndex = row.state + 1;
910
if (nextIndex > def.steps.length)
912
}
913
const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);
914
const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
915
const progress = {
916
...row.progress,
917
completedObjectiveIds: [...completed],
918
progressFingerprint: fingerprint,
919
completedStepIds: deriveCompletedStepIds(def, row.state, row.progress)
920
};
921
const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
922
for (const obj of newlyDone)
923
{
924
events.push({
925
type: "questObjectiveComplete",
926
questId: row.questId,
927
objectiveId: obj.objectiveId,
928
text: obj.text || "Objective"
929
});
930
}
931
if (allDone && this.#leaveStep(characterId, def, row, stepDef, null, playerView, events))
932
{ return; }
933
if (!changed && !progressChanged)
934
{ return; }
935
this.#saveActiveProgress(characterId, def, row, progress);
936
events.push({ type: "questsDirty", characterId });
937
}
938
939
#advanceBranchStep (characterId, def, row, stepDef, ctx, playerView, events)
940
{
941
const branches = stepDef.exit?.branches ?? [];
942
let matched = null;
943
for (const branch of branches)
944
{
945
if (evaluateConditionSet(branch.when, ctx))
911
946
{
912
const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);
913
this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());
914
events.push({
915
type: "questComplete",
916
questId: row.questId,
917
title: def.title,
918
xp: summary.xp,
919
items: summary.bagItems
920
});
947
matched = branch;
948
break;
921
949
}
922
else
950
}
951
const fingerprint = objectiveProgressFingerprint(branchProgressRows(branches), ctx);
952
const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
953
if (!matched)
954
{
955
if (!progressChanged)
956
{ return; }
957
this.#saveActiveProgress(characterId, def, row, {
958
...row.progress,
959
progressFingerprint: fingerprint,
960
completedStepIds: deriveCompletedStepIds(def, row.state, row.progress)
961
});
962
events.push({ type: "questsDirty", characterId });
963
return;
964
}
965
this.#leaveStep(characterId, def, row, stepDef, matched, playerView, events);
966
}
967
968
/**
969
* One hop away from the current step. Returns false when a continue/branch
970
* names a step that does not exist (stay put; retry next evaluation).
971
* Empty nextStepId completes the quest. Quest-wide rewards fire only here.
972
*/
973
#leaveStep (characterId, def, row, stepDef, branch, playerView, events)
974
{
975
const exit = stepDef.exit ?? { kind: "complete" };
976
let destination = null;
977
if (branch)
978
{
979
if (branch.nextStepId)
923
980
{
924
const nextStep = def.steps[nextIndex - 1];
925
this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {
926
completedObjectiveIds: [],
927
counters: {},
928
interacts: {},
929
progressFingerprint: ""
930
}, row.startedAt, null);
931
this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
932
events.push({
933
type: "questStepComplete",
934
questId: row.questId,
935
title: def.title,
936
journalText: journal?.text ?? null
937
});
981
destination = def.steps.find((step) => step.stepId === branch.nextStepId) ?? null;
982
if (!destination)
983
{ return false; }
938
984
}
939
events.push({ type: "questsDirty", characterId });
940
985
}
986
else if (exit.kind === "continue" && exit.nextStepId)
987
{
988
destination = def.steps.find((step) => step.stepId === exit.nextStepId) ?? null;
989
if (!destination)
990
{ return false; }
991
}
992
this._transitionedQuestIds?.add(row.questId);
993
const completedStepIds = rememberCompletedStep(
994
deriveCompletedStepIds(def, row.state, row.progress),
995
stepDef.stepId
996
);
997
this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
998
if (branch)
999
{ this.#applyEffects(characterId, branch.effects, playerView, events); }
1000
const journal = this.stateDb.appendQuestJournal(
1001
characterId,
1002
row.questId,
1003
stepDef.stepId,
1004
stepDef.completionJournalText
1005
);
1006
if (!destination)
1007
{
1008
const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);
1009
this.stateDb.saveQuestState(characterId, row.questId, "completed", {
1010
...row.progress,
1011
completedStepIds
1012
}, row.startedAt, Date.now());
1013
events.push({
1014
type: "questComplete",
1015
questId: row.questId,
1016
title: def.title,
1017
xp: summary.xp,
1018
items: summary.bagItems
1019
});
1020
}
1021
else
1022
{
1023
this.stateDb.saveQuestState(characterId, row.questId, destination.stepId, {
1024
completedObjectiveIds: [],
1025
counters: {},
1026
interacts: {},
1027
progressFingerprint: "",
1028
completedStepIds
1029
}, row.startedAt, null);
1030
this.#applyEffects(characterId, destination.onEnter, playerView, events);
1031
events.push({
1032
type: "questStepComplete",
1033
questId: row.questId,
1034
title: def.title,
1035
journalText: journal?.text ?? null
1036
});
1037
}
1038
events.push({ type: "questsDirty", characterId });
1039
return true;
1040
}
1041
1042
#saveActiveProgress (characterId, def, row, progress)
1043
{
1044
const stepId = resolveQuestStepId(def, row.state) ?? row.state;
1045
const completedStepIds = Array.isArray(progress?.completedStepIds)
1046
? progress.completedStepIds
1047
: deriveCompletedStepIds(def, row.state, row.progress);
1048
this.stateDb.saveQuestState(characterId, row.questId, stepId, {
1049
...progress,
1050
completedStepIds
1051
}, row.startedAt, row.completedAt);
941
1052
}
942
1053
943
1054
noteKill (characterId, { mobTypeId, spawnerId })
@@ -945,18 +1056,18 @@ export class QuestRuntime
945
1056
const events = [];
946
1057
const playerView = this.playerViewFor(characterId);
947
1058
const states = this.stateDb.listQuestStates(characterId)
948
.filter((row) => typeof row.state === "number");
1059
.filter((row) => isActiveQuestState(row.state));
949
1060
for (const row of states)
950
1061
{
951
1062
const def = this.content.quest(row.questId);
952
const stepDef = def?.steps[row.state - 1];
1063
const stepDef = def ? activeQuestStep(def, row.state) : null;
953
1064
if (!stepDef)
954
1065
{ continue; }
955
1066
let changed = false;
956
1067
const counters = { ...(row.progress?.counters ?? {}) };
957
for (const obj of stepDef.objectives)
1068
for (const set of stepConditionSets(stepDef))
958
1069
{
959
for (const clause of obj.when?.all ?? [])
1070
for (const clause of set?.all ?? [])
960
1071
{
961
1072
const c = clause.condition;
962
1073
if (!matchesKillCondition(c, mobTypeId, spawnerId))
@@ -968,16 +1079,70 @@ export class QuestRuntime
968
1079
}
969
1080
if (!changed)
970
1081
{ continue; }
971
this.stateDb.saveQuestState(characterId, row.questId, row.state, {
1082
this.#saveActiveProgress(characterId, def, row, {
972
1083
...row.progress,
973
counters
974
}, row.startedAt, row.completedAt);
1084
counters,
1085
completedStepIds: deriveCompletedStepIds(def, row.state, row.progress)
1086
});
975
1087
}
976
1088
this.#reevaluateQuests(characterId, playerView, events);
977
1089
return events;
978
1090
}
979
1091
}
980
1092
1093
function activeQuestStep (def, state)
1094
{
1095
const stepId = resolveQuestStepId(def, state);
1096
if (!stepId || stepId === "not-started" || stepId === "completed")
1097
{ return null; }
1098
return def.steps.find((step) => step.stepId === stepId) ?? null;
1099
}
1100
1101
function stepConditionSets (stepDef)
1102
{
1103
if (stepDef?.exit?.kind === "branches")
1104
{ return (stepDef.exit.branches ?? []).map((branch) => branch.when); }
1105
return (stepDef?.objectives ?? []).map((obj) => obj.when);
1106
}
1107
1108
function branchProgressRows (branches)
1109
{
1110
return (branches ?? []).map((branch, index) => ({
1111
objectiveId: `branch-${index}`,
1112
when: branch.when
1113
}));
1114
}
1115
1116
function publicStepLines (stepDef, completedObjectiveIds, ctx)
1117
{
1118
if (stepDef.exit?.kind === "branches")
1119
{
1120
return (stepDef.exit.branches ?? []).map((branch, index) =>
1121
{
1122
const progress = countableObjectiveProgress(branch.when, ctx);
1123
return {
1124
objectiveId: `branch-${index}`,
1125
text: branch.text || branch.label || `Path ${index + 1}`,
1126
done: false,
1127
current: progress?.current ?? null,
1128
required: progress?.required ?? null
1129
};
1130
});
1131
}
1132
return (stepDef.objectives ?? []).map((obj) =>
1133
{
1134
const done = completedObjectiveIds.includes(obj.objectiveId);
1135
const progress = countableObjectiveProgress(obj.when, ctx);
1136
return {
1137
objectiveId: obj.objectiveId,
1138
text: obj.text,
1139
done,
1140
current: progress?.current ?? null,
1141
required: progress?.required ?? null
1142
};
1143
});
1144
}
1145
981
1146
function journalPublic (row)
982
1147
{
983
1148
return {
@@ -1,4 +1,10 @@1
import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";1
import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";2
import {3
deriveCompletedStepIds,4
isActiveQuestState,5
rememberCompletedStep,6
resolveQuestStepId7
} from "../../../shared/quests/questProgress.js";2
import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";8
import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";3
import {9
import {4
countableObjectiveProgress,10
countableObjectiveProgress,@@ -72,8 +78,12 @@ export class QuestRuntime72
});78
});73
continue;79
continue;74
}80
}75
const stepIndex = typeof row.state === "number" ? row.state : null;81
const stepDef = isActiveQuestState(row.state)76
const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null;82
? activeQuestStep(def, row.state)83
: null;84
const resolvedState = isActiveQuestState(row.state)85
? (resolveQuestStepId(def, row.state) ?? row.state)86
: row.state;77
const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];87
const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];78
const ctx = stepDef88
const ctx = stepDef79
? this.buildConditionContext(characterId, playerView, row.questId)89
? this.buildConditionContext(characterId, playerView, row.questId)@@ -82,25 +92,14 @@ export class QuestRuntime82
questId: def.questId,92
questId: def.questId,83
title: def.title,93
title: def.title,84
orphaned: false,94
orphaned: false,85
state: row.state,95
state: resolvedState,86
description: def.description,96
description: def.description,87
step: stepDef97
step: stepDef88
? {98
? {89
stepId: stepDef.stepId,99
stepId: stepDef.stepId,90
title: stepDef.title,100
title: stepDef.title,91
description: stepDef.description,101
description: stepDef.description,92
objectives: stepDef.objectives.map((obj) =>102
objectives: publicStepLines(stepDef, completedObjectiveIds, ctx)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 ?? null102
};103
})104
}103
}105
: null,104
: null,106
journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)105
journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)@@ -178,7 +177,26 @@ export class QuestRuntime178
stamina: playerView?.stamina ?? 0,177
stamina: playerView?.stamina ?? 0,179
maxStamina: playerView?.maxStamina ?? 1,178
maxStamina: playerView?.maxStamina ?? 1,180
countItem: (itemId) => countItemInSlots(inventory, itemId | 0),179
countItem: (itemId) => countItemInSlots(inventory, itemId | 0),181
questState: (questId) => this.stateDb.getQuestState(characterId, questId).state,180
questState: (questId) =>181
{182
const row = this.stateDb.getQuestState(characterId, questId);183
return resolveQuestStepId(this.content.quest(questId), row.state);184
},185
questSteps: (questId) =>186
{187
const def = this.content.quest(questId);188
return def ? def.steps.map((step) => step.stepId) : null;189
},190
hasCompletedStep: (questId, stepId) =>191
{192
const row = this.stateDb.getQuestState(characterId, questId);193
const ids = deriveCompletedStepIds(194
this.content.quest(questId),195
row.state,196
row.progress197
);198
return ids.includes(String(stepId ?? ""));199
},182
dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId),200
dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId),183
dialogueTriggerLatched: (dialogueId, trigger) =>201
dialogueTriggerLatched: (dialogueId, trigger) =>184
this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger),202
this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger),@@ -670,12 +688,15 @@ export class QuestRuntime670
const current = this.stateDb.getQuestState(characterId, questId);688
const current = this.stateDb.getQuestState(characterId, questId);671
if (current.state !== "not-started")689
if (current.state !== "not-started")672
{ return; }690
{ return; }673
this.stateDb.saveQuestState(characterId, questId, 1, {691
const first = def.steps[0];692
this.stateDb.saveQuestState(characterId, questId, first.stepId, {674
completedObjectiveIds: [],693
completedObjectiveIds: [],675
counters: {},694
counters: {},676
interacts: {}695
interacts: {},696
completedStepIds: [],697
progressFingerprint: ""677
}, Date.now(), null);698
}, Date.now(), null);678
this.#applyEffects(characterId, def.steps[0]?.onEnter, playerView, events);699
this.#applyEffects(characterId, first.onEnter, playerView, events);679
events.push({ type: "questsDirty", characterId });700
events.push({ type: "questsDirty", characterId });680
this.#reevaluateQuests(characterId, playerView, events);701
this.#reevaluateQuests(characterId, playerView, events);681
}702
}@@ -842,102 +863,192 @@ export class QuestRuntime842
863
843
#reevaluateQuests (characterId, playerView, events)864
#reevaluateQuests (characterId, playerView, events)844
{865
{845
const states = this.stateDb.listQuestStates(characterId)866
const outer = this._transitionedQuestIds == null;846
.filter((row) => typeof row.state === "number");867
if (outer)847
for (const row of states)868
{ this._transitionedQuestIds = new Set(); }869
try848
{870
{849
const def = this.content.quest(row.questId);871
const states = this.stateDb.listQuestStates(characterId)850
if (!def)872
.filter((row) => isActiveQuestState(row.state));851
{ continue; }873
for (const row of states)852
const stepDef = def.steps[row.state - 1];853
if (!stepDef)854
{ continue; }855
const ctx = this.buildConditionContext(characterId, playerView, row.questId);856
const completed = new Set(row.progress?.completedObjectiveIds ?? []);857
const newlyDone = [];858
let changed = false;859
for (const obj of stepDef.objectives)860
{874
{861
if (completed.has(obj.objectiveId))875
if (this._transitionedQuestIds.has(row.questId))862
{ continue; }876
{ continue; }863
if (evaluateConditionSet(obj.when, ctx))877
const def = this.content.quest(row.questId);864
{878
if (!def)865
completed.add(obj.objectiveId);879
{ continue; }866
newlyDone.push(obj);880
const stepDef = activeQuestStep(def, row.state);867
changed = true;881
if (!stepDef)868
}882
{ continue; }883
const ctx = this.buildConditionContext(characterId, playerView, row.questId);884
if (stepDef.exit?.kind === "branches")885
{ this.#advanceBranchStep(characterId, def, row, stepDef, ctx, playerView, events); }886
else887
{ this.#advanceLinearStep(characterId, def, row, stepDef, ctx, playerView, events); }869
}888
}870
const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);889
}871
const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");890
finally872
if (!changed && !progressChanged)891
{892
if (outer)893
{ this._transitionedQuestIds = null; }894
}895
}896
897
#advanceLinearStep (characterId, def, row, stepDef, ctx, playerView, events)898
{899
const completed = new Set(row.progress?.completedObjectiveIds ?? []);900
const newlyDone = [];901
let changed = false;902
for (const obj of stepDef.objectives)903
{904
if (completed.has(obj.objectiveId))873
{ continue; }905
{ continue; }874
for (const obj of newlyDone)906
if (evaluateConditionSet(obj.when, ctx))875
{876
events.push({877
type: "questObjectiveComplete",878
questId: row.questId,879
objectiveId: obj.objectiveId,880
text: obj.text || "Objective"881
});882
}883
const progress = {884
...row.progress,885
completedObjectiveIds: [...completed],886
progressFingerprint: fingerprint887
};888
const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));889
if (!allDone)890
{907
{891
this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);908
completed.add(obj.objectiveId);892
events.push({ type: "questsDirty", characterId });909
newlyDone.push(obj);893
continue;910
changed = true;894
}911
}895
if (!changed)912
}896
{913
const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);897
// Progress-only update while already fully complete (should not happen).914
const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");898
this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);915
const progress = {899
events.push({ type: "questsDirty", characterId });916
...row.progress,900
continue;917
completedObjectiveIds: [...completed],901
}918
progressFingerprint: fingerprint,902
this.#applyEffects(characterId, stepDef.onComplete, playerView, events);919
completedStepIds: deriveCompletedStepIds(def, row.state, row.progress)903
const journal = this.stateDb.appendQuestJournal(920
};904
characterId,921
const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));905
row.questId,922
for (const obj of newlyDone)906
stepDef.stepId,923
{907
stepDef.completionJournalText924
events.push({908
);925
type: "questObjectiveComplete",909
const nextIndex = row.state + 1;926
questId: row.questId,910
if (nextIndex > def.steps.length)927
objectiveId: obj.objectiveId,928
text: obj.text || "Objective"929
});930
}931
if (allDone && this.#leaveStep(characterId, def, row, stepDef, null, playerView, events))932
{ return; }933
if (!changed && !progressChanged)934
{ return; }935
this.#saveActiveProgress(characterId, def, row, progress);936
events.push({ type: "questsDirty", characterId });937
}938
939
#advanceBranchStep (characterId, def, row, stepDef, ctx, playerView, events)940
{941
const branches = stepDef.exit?.branches ?? [];942
let matched = null;943
for (const branch of branches)944
{945
if (evaluateConditionSet(branch.when, ctx))911
{946
{912
const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);947
matched = branch;913
this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());948
break;914
events.push({915
type: "questComplete",916
questId: row.questId,917
title: def.title,918
xp: summary.xp,919
items: summary.bagItems920
});921
}949
}922
else950
}951
const fingerprint = objectiveProgressFingerprint(branchProgressRows(branches), ctx);952
const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");953
if (!matched)954
{955
if (!progressChanged)956
{ return; }957
this.#saveActiveProgress(characterId, def, row, {958
...row.progress,959
progressFingerprint: fingerprint,960
completedStepIds: deriveCompletedStepIds(def, row.state, row.progress)961
});962
events.push({ type: "questsDirty", characterId });963
return;964
}965
this.#leaveStep(characterId, def, row, stepDef, matched, playerView, events);966
}967
968
/**969
* One hop away from the current step. Returns false when a continue/branch970
* names a step that does not exist (stay put; retry next evaluation).971
* Empty nextStepId completes the quest. Quest-wide rewards fire only here.972
*/973
#leaveStep (characterId, def, row, stepDef, branch, playerView, events)974
{975
const exit = stepDef.exit ?? { kind: "complete" };976
let destination = null;977
if (branch)978
{979
if (branch.nextStepId)923
{980
{924
const nextStep = def.steps[nextIndex - 1];981
destination = def.steps.find((step) => step.stepId === branch.nextStepId) ?? null;925
this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {982
if (!destination)926
completedObjectiveIds: [],983
{ return false; }927
counters: {},928
interacts: {},929
progressFingerprint: ""930
}, row.startedAt, null);931
this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);932
events.push({933
type: "questStepComplete",934
questId: row.questId,935
title: def.title,936
journalText: journal?.text ?? null937
});938
}984
}939
events.push({ type: "questsDirty", characterId });940
}985
}986
else if (exit.kind === "continue" && exit.nextStepId)987
{988
destination = def.steps.find((step) => step.stepId === exit.nextStepId) ?? null;989
if (!destination)990
{ return false; }991
}992
this._transitionedQuestIds?.add(row.questId);993
const completedStepIds = rememberCompletedStep(994
deriveCompletedStepIds(def, row.state, row.progress),995
stepDef.stepId996
);997
this.#applyEffects(characterId, stepDef.onComplete, playerView, events);998
if (branch)999
{ this.#applyEffects(characterId, branch.effects, playerView, events); }1000
const journal = this.stateDb.appendQuestJournal(1001
characterId,1002
row.questId,1003
stepDef.stepId,1004
stepDef.completionJournalText1005
);1006
if (!destination)1007
{1008
const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);1009
this.stateDb.saveQuestState(characterId, row.questId, "completed", {1010
...row.progress,1011
completedStepIds1012
}, row.startedAt, Date.now());1013
events.push({1014
type: "questComplete",1015
questId: row.questId,1016
title: def.title,1017
xp: summary.xp,1018
items: summary.bagItems1019
});1020
}1021
else1022
{1023
this.stateDb.saveQuestState(characterId, row.questId, destination.stepId, {1024
completedObjectiveIds: [],1025
counters: {},1026
interacts: {},1027
progressFingerprint: "",1028
completedStepIds1029
}, row.startedAt, null);1030
this.#applyEffects(characterId, destination.onEnter, playerView, events);1031
events.push({1032
type: "questStepComplete",1033
questId: row.questId,1034
title: def.title,1035
journalText: journal?.text ?? null1036
});1037
}1038
events.push({ type: "questsDirty", characterId });1039
return true;1040
}1041
1042
#saveActiveProgress (characterId, def, row, progress)1043
{1044
const stepId = resolveQuestStepId(def, row.state) ?? row.state;1045
const completedStepIds = Array.isArray(progress?.completedStepIds)1046
? progress.completedStepIds1047
: deriveCompletedStepIds(def, row.state, row.progress);1048
this.stateDb.saveQuestState(characterId, row.questId, stepId, {1049
...progress,1050
completedStepIds1051
}, row.startedAt, row.completedAt);941
}1052
}942
1053
943
noteKill (characterId, { mobTypeId, spawnerId })1054
noteKill (characterId, { mobTypeId, spawnerId })@@ -945,18 +1056,18 @@ export class QuestRuntime945
const events = [];1056
const events = [];946
const playerView = this.playerViewFor(characterId);1057
const playerView = this.playerViewFor(characterId);947
const states = this.stateDb.listQuestStates(characterId)1058
const states = this.stateDb.listQuestStates(characterId)948
.filter((row) => typeof row.state === "number");1059
.filter((row) => isActiveQuestState(row.state));949
for (const row of states)1060
for (const row of states)950
{1061
{951
const def = this.content.quest(row.questId);1062
const def = this.content.quest(row.questId);952
const stepDef = def?.steps[row.state - 1];1063
const stepDef = def ? activeQuestStep(def, row.state) : null;953
if (!stepDef)1064
if (!stepDef)954
{ continue; }1065
{ continue; }955
let changed = false;1066
let changed = false;956
const counters = { ...(row.progress?.counters ?? {}) };1067
const counters = { ...(row.progress?.counters ?? {}) };957
for (const obj of stepDef.objectives)1068
for (const set of stepConditionSets(stepDef))958
{1069
{959
for (const clause of obj.when?.all ?? [])1070
for (const clause of set?.all ?? [])960
{1071
{961
const c = clause.condition;1072
const c = clause.condition;962
if (!matchesKillCondition(c, mobTypeId, spawnerId))1073
if (!matchesKillCondition(c, mobTypeId, spawnerId))@@ -968,16 +1079,70 @@ export class QuestRuntime968
}1079
}969
if (!changed)1080
if (!changed)970
{ continue; }1081
{ continue; }971
this.stateDb.saveQuestState(characterId, row.questId, row.state, {1082
this.#saveActiveProgress(characterId, def, row, {972
...row.progress,1083
...row.progress,973
counters1084
counters,974
}, row.startedAt, row.completedAt);1085
completedStepIds: deriveCompletedStepIds(def, row.state, row.progress)1086
});975
}1087
}976
this.#reevaluateQuests(characterId, playerView, events);1088
this.#reevaluateQuests(characterId, playerView, events);977
return events;1089
return events;978
}1090
}979
}1091
}980
1092
1093
function activeQuestStep (def, state)1094
{1095
const stepId = resolveQuestStepId(def, state);1096
if (!stepId || stepId === "not-started" || stepId === "completed")1097
{ return null; }1098
return def.steps.find((step) => step.stepId === stepId) ?? null;1099
}1100
1101
function stepConditionSets (stepDef)1102
{1103
if (stepDef?.exit?.kind === "branches")1104
{ return (stepDef.exit.branches ?? []).map((branch) => branch.when); }1105
return (stepDef?.objectives ?? []).map((obj) => obj.when);1106
}1107
1108
function branchProgressRows (branches)1109
{1110
return (branches ?? []).map((branch, index) => ({1111
objectiveId: `branch-${index}`,1112
when: branch.when1113
}));1114
}1115
1116
function publicStepLines (stepDef, completedObjectiveIds, ctx)1117
{1118
if (stepDef.exit?.kind === "branches")1119
{1120
return (stepDef.exit.branches ?? []).map((branch, index) =>1121
{1122
const progress = countableObjectiveProgress(branch.when, ctx);1123
return {1124
objectiveId: `branch-${index}`,1125
text: branch.text || branch.label || `Path ${index + 1}`,1126
done: false,1127
current: progress?.current ?? null,1128
required: progress?.required ?? null1129
};1130
});1131
}1132
return (stepDef.objectives ?? []).map((obj) =>1133
{1134
const done = completedObjectiveIds.includes(obj.objectiveId);1135
const progress = countableObjectiveProgress(obj.when, ctx);1136
return {1137
objectiveId: obj.objectiveId,1138
text: obj.text,1139
done,1140
current: progress?.current ?? null,1141
required: progress?.required ?? null1142
};1143
});1144
}1145
981
function journalPublic (row)1146
function journalPublic (row)982
{1147
{983
return {1148
return {@@ -231,6 +231,8 @@ export class Simulation
231
231
this.market?.refreshIndex();
232
232
this.questContent.reload();
233
233
this.quests?.closeAllSessions();
234
for (const characterId of this.characterEntities.keys())
235
{ this.syncCharacterConditionAccess(characterId); }
234
236
this.#refreshAltarIndex();
235
237
// Quest defs become live on Apply — grant any newly available initial quests.
236
238
this.#grantInitialQuestsAndNotify();
@@ -561,7 +563,11 @@ export class Simulation
561
563
dimensionId,
562
564
sinceMs: this.now
563
565
},
564
conditionAccess: buildConditionAccessSnapshot(this.stateDb, character.character_id ?? row.character_id)
566
conditionAccess: buildConditionAccessSnapshot(
567
this.stateDb,
568
character.character_id ?? row.character_id,
569
this.questContent
570
)
565
571
};
566
572
if (isDead)
567
573
{ components.dead = {}; }
@@ -651,7 +657,7 @@ export class Simulation
651
657
this.workers[record.workerId]?.call({
652
658
type: WorkerMessage.applyConditionAccess,
653
659
entityId,
654
conditionAccess: buildConditionAccessSnapshot(this.stateDb, id)
660
conditionAccess: buildConditionAccessSnapshot(this.stateDb, id, this.questContent)
655
661
});
656
662
}
657
663
@@ -231,6 +231,8 @@ export class Simulation231
this.market?.refreshIndex();231
this.market?.refreshIndex();232
this.questContent.reload();232
this.questContent.reload();233
this.quests?.closeAllSessions();233
this.quests?.closeAllSessions();234
for (const characterId of this.characterEntities.keys())235
{ this.syncCharacterConditionAccess(characterId); }234
this.#refreshAltarIndex();236
this.#refreshAltarIndex();235
// Quest defs become live on Apply — grant any newly available initial quests.237
// Quest defs become live on Apply — grant any newly available initial quests.236
this.#grantInitialQuestsAndNotify();238
this.#grantInitialQuestsAndNotify();@@ -561,7 +563,11 @@ export class Simulation561
dimensionId,563
dimensionId,562
sinceMs: this.now564
sinceMs: this.now563
},565
},564
conditionAccess: buildConditionAccessSnapshot(this.stateDb, character.character_id ?? row.character_id)566
conditionAccess: buildConditionAccessSnapshot(567
this.stateDb,568
character.character_id ?? row.character_id,569
this.questContent570
)565
};571
};566
if (isDead)572
if (isDead)567
{ components.dead = {}; }573
{ components.dead = {}; }@@ -651,7 +657,7 @@ export class Simulation651
this.workers[record.workerId]?.call({657
this.workers[record.workerId]?.call({652
type: WorkerMessage.applyConditionAccess,658
type: WorkerMessage.applyConditionAccess,653
entityId,659
entityId,654
conditionAccess: buildConditionAccessSnapshot(this.stateDb, id)660
conditionAccess: buildConditionAccessSnapshot(this.stateDb, id, this.questContent)655
});661
});656
}662
}657
663
@@ -982,6 +982,7 @@ export class WorkerWorld
982
982
: {
983
983
questStates: {},
984
984
questProgress: {},
985
questSteps: {},
985
986
dialogueHeard: [],
986
987
dialogueTriggers: [],
987
988
visitedDimensions: []
@@ -982,6 +982,7 @@ export class WorkerWorld982
: {982
: {983
questStates: {},983
questStates: {},984
questProgress: {},984
questProgress: {},985
questSteps: {},985
dialogueHeard: [],986
dialogueHeard: [],986
dialogueTriggers: [],987
dialogueTriggers: [],987
visitedDimensions: []988
visitedDimensions: []@@ -56,7 +56,7 @@ test("initial quests grant on apply after quest def becomes live", () =>
56
56
57
57
assert.equal(
58
58
harness.stateDb.getQuestState(character.character_id, "starter-hello").state,
59
1
59
"step-1"
60
60
);
61
61
const snap = harness.simulation.quests.questSnapshot(character.character_id);
62
62
assert.equal(snap.quests.length, 1);
@@ -103,7 +103,7 @@ test("request-quests ensures missing initial quests before snapshot", () =>
103
103
assert.equal(snap.quests[0].questId, "late-grant");
104
104
assert.equal(
105
105
harness.stateDb.getQuestState(character.character_id, "late-grant").state,
106
1
106
"step-1"
107
107
);
108
108
}
109
109
finally
@@ -169,7 +169,7 @@ test("request-quests re-checks hasItem objectives against the live bag", () =>
169
169
assert.ok(snap);
170
170
const questSnap = snap.quests.find((q) => q.questId === "fetch-rock");
171
171
assert.ok(questSnap);
172
assert.equal(questSnap.state, 1);
172
assert.equal(questSnap.state, "step-1");
173
173
assert.equal(questSnap.step.objectives.find((o) => o.objectiveId === "obj-rock")?.done, true);
174
174
assert.equal(questSnap.step.objectives.find((o) => o.objectiveId === "obj-gem")?.done, false);
175
175
}
@@ -56,7 +56,7 @@ test("initial quests grant on apply after quest def becomes live", () =>56
56
57
assert.equal(57
assert.equal(58
harness.stateDb.getQuestState(character.character_id, "starter-hello").state,58
harness.stateDb.getQuestState(character.character_id, "starter-hello").state,59
159
"step-1"60
);60
);61
const snap = harness.simulation.quests.questSnapshot(character.character_id);61
const snap = harness.simulation.quests.questSnapshot(character.character_id);62
assert.equal(snap.quests.length, 1);62
assert.equal(snap.quests.length, 1);@@ -103,7 +103,7 @@ test("request-quests ensures missing initial quests before snapshot", () =>103
assert.equal(snap.quests[0].questId, "late-grant");103
assert.equal(snap.quests[0].questId, "late-grant");104
assert.equal(104
assert.equal(105
harness.stateDb.getQuestState(character.character_id, "late-grant").state,105
harness.stateDb.getQuestState(character.character_id, "late-grant").state,106
1106
"step-1"107
);107
);108
}108
}109
finally109
finally@@ -169,7 +169,7 @@ test("request-quests re-checks hasItem objectives against the live bag", () =>169
assert.ok(snap);169
assert.ok(snap);170
const questSnap = snap.quests.find((q) => q.questId === "fetch-rock");170
const questSnap = snap.quests.find((q) => q.questId === "fetch-rock");171
assert.ok(questSnap);171
assert.ok(questSnap);172
assert.equal(questSnap.state, 1);172
assert.equal(questSnap.state, "step-1");173
assert.equal(questSnap.step.objectives.find((o) => o.objectiveId === "obj-rock")?.done, true);173
assert.equal(questSnap.step.objectives.find((o) => o.objectiveId === "obj-rock")?.done, true);174
assert.equal(questSnap.step.objectives.find((o) => o.objectiveId === "obj-gem")?.done, false);174
assert.equal(questSnap.step.objectives.find((o) => o.objectiveId === "obj-gem")?.done, false);175
}175
}@@ -0,0 +1,376 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import { normalizeQuestDef } from "../../shared/quests/normalize.js";
4
import { ConditionKind } from "../../shared/quests/conditions.js";
5
import { normalizeDoorConfig } from "../../shared/world/doorRequirements.js";
6
import { BlockType } from "../../shared/definitions/tiles.js";
7
import { ItemId } from "../../shared/definitions/items.js";
8
import { SkillId } from "../../shared/definitions/skills.js";
9
import { emptyEquipment, emptySlots, INVENTORY_SLOTS } from "../../shared/items/inventory.js";
10
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
11
12
function saveLiveQuest (harness, raw)
13
{
14
const revisionId = harness.worldDb.getActiveRevisionId();
15
const quest = normalizeQuestDef(raw);
16
harness.worldDb.saveQuestDef(revisionId, quest);
17
harness.simulation.questContent.reload();
18
return quest;
19
}
20
21
function stuckObjective (itemId = 99999)
22
{
23
return [{
24
objectiveId: "stay",
25
text: "Stay",
26
when: { all: [{ condition: { kind: "hasItem", itemId, quantity: 1 } }] }
27
}];
28
}
29
30
function openObjective ()
31
{
32
return [{ objectiveId: "go", text: "Go", when: { all: [] } }];
33
}
34
35
function workerOf (simulation, entityId)
36
{
37
const record = simulation.entityRecord(entityId);
38
assert.ok(record);
39
return simulation.workers[record.workerId];
40
}
41
42
function placeDoor (worker, tileX, tileY, when)
43
{
44
const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
45
const localX = ((tileX % 16) + 16) % 16;
46
const localY = ((tileY % 16) + 16) % 16;
47
data.blocks[localY * 16 + localX] = {
48
typeId: BlockType.door,
49
state: "oak-n-closed",
50
config: normalizeDoorConfig({ when, blockedMessage: "Not yet." })
51
};
52
}
53
54
test("linear quests still advance one step per evaluation and reward once", () =>
55
{
56
const harness = makeSimulation({ workerCount: 1 });
57
try
58
{
59
const quest = saveLiveQuest(harness, {
60
questId: "linear-chain",
61
title: "Linear",
62
steps: [
63
{ stepId: "s1", title: "One", objectives: openObjective(), completionJournalText: "One done." },
64
{ stepId: "s2", title: "Two", objectives: openObjective(), completionJournalText: "Two done." },
65
{ stepId: "s3", title: "Three", objectives: openObjective(), completionJournalText: "Three done." }
66
],
67
rewards: [{ kind: "giveXp", skillId: SkillId.woodworking, amount: 11 }]
68
});
69
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
70
harness.simulation.spawnCharacter(1, character);
71
harness.simulation.step();
72
const view = harness.simulation.quests.playerViewFor(character.character_id);
73
const events = [];
74
harness.simulation.quests.startQuest(character.character_id, quest.questId, view, events);
75
assert.equal(events.some((event) => event.type === "questComplete"), false);
76
let state = harness.stateDb.getQuestState(character.character_id, quest.questId);
77
assert.equal(state.state, "s2");
78
assert.deepEqual(state.progress.completedStepIds, ["s1"]);
79
80
harness.simulation.quests.reevaluateQuests(character.character_id, view, []);
81
state = harness.stateDb.getQuestState(character.character_id, quest.questId);
82
assert.equal(state.state, "s3");
83
assert.deepEqual(state.progress.completedStepIds, ["s1", "s2"]);
84
assert.equal(harness.stateDb.getSkills(character.character_id).xp.woodworking, 0);
85
86
harness.simulation.quests.reevaluateQuests(character.character_id, view, []);
87
state = harness.stateDb.getQuestState(character.character_id, quest.questId);
88
assert.equal(state.state, "completed");
89
assert.deepEqual(state.progress.completedStepIds, ["s1", "s2", "s3"]);
90
assert.equal(harness.stateDb.getSkills(character.character_id).xp.woodworking, 11);
91
92
harness.simulation.quests.reevaluateQuests(character.character_id, view, []);
93
assert.equal(harness.stateDb.getSkills(character.character_id).xp.woodworking, 11);
94
assert.equal(
95
harness.stateDb.getQuestState(character.character_id, quest.questId).state,
96
"completed"
97
);
98
}
99
finally
100
{ harness.close(); }
101
});
102
103
test("branch exit takes the first matching condition set only", () =>
104
{
105
const harness = makeSimulation({ workerCount: 1 });
106
try
107
{
108
const quest = saveLiveQuest(harness, {
109
questId: "branch-first",
110
title: "Branch",
111
steps: [{
112
stepId: "hub",
113
title: "Hub",
114
exit: {
115
kind: "branches",
116
branches: [
117
{
118
label: "Bones",
119
text: "Bring bones",
120
when: { all: [{ condition: { kind: "hasItem", itemId: ItemId.bones, quantity: 1 } }] },
121
nextStepId: "bones-path"
122
},
123
{
124
label: "Other",
125
text: "Otherwise",
126
when: { all: [] },
127
nextStepId: "other-path"
128
}
129
]
130
}
131
}, {
132
stepId: "bones-path",
133
title: "Bones",
134
objectives: stuckObjective()
135
}, {
136
stepId: "other-path",
137
title: "Other",
138
objectives: stuckObjective()
139
}]
140
});
141
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
142
const playerId = harness.simulation.spawnCharacter(1, character);
143
harness.simulation.step();
144
const inventory = emptySlots(INVENTORY_SLOTS);
145
inventory[0] = { itemId: ItemId.bones, quantity: 1 };
146
harness.simulation.applyBag(playerId, {
147
inventory,
148
equipment: emptyEquipment(),
149
vault: [],
150
vaultReserved: []
151
});
152
const view = harness.simulation.quests.playerViewFor(character.character_id);
153
harness.simulation.quests.startQuest(character.character_id, quest.questId, view, []);
154
const state = harness.stateDb.getQuestState(character.character_id, quest.questId);
155
assert.equal(state.state, "bones-path");
156
assert.deepEqual(state.progress.completedStepIds, ["hub"]);
157
const snap = harness.simulation.quests.questSnapshot(character.character_id);
158
assert.equal(snap.quests[0].step.stepId, "bones-path");
159
}
160
finally
161
{ harness.close(); }
162
});
163
164
test("unmatched branch step shows branch texts with kill progress", () =>
165
{
166
const harness = makeSimulation({ workerCount: 1 });
167
try
168
{
169
const quest = saveLiveQuest(harness, {
170
questId: "branch-log",
171
title: "Log",
172
steps: [{
173
stepId: "choice",
174
title: "Choose",
175
exit: {
176
kind: "branches",
177
branches: [
178
{
179
text: "Kill rats",
180
when: { all: [{ condition: { kind: "killCount", mobTypeId: "rat", count: 3 } }] },
181
nextStepId: "done"
182
},
183
{
184
text: "Bring bones",
185
when: { all: [{ condition: { kind: "hasItem", itemId: ItemId.bones, quantity: 2 } }] },
186
nextStepId: "done"
187
}
188
]
189
}
190
}, {
191
stepId: "done",
192
title: "Done",
193
objectives: stuckObjective()
194
}]
195
});
196
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
197
harness.simulation.spawnCharacter(1, character);
198
harness.simulation.step();
199
const view = harness.simulation.quests.playerViewFor(character.character_id);
200
harness.simulation.quests.startQuest(character.character_id, quest.questId, view, []);
201
let snap = harness.simulation.quests.questSnapshot(character.character_id);
202
assert.deepEqual(
203
snap.quests[0].step.objectives.map((line) => line.text),
204
["Kill rats", "Bring bones"]
205
);
206
assert.equal(snap.quests[0].step.objectives[0].current, 0);
207
assert.equal(snap.quests[0].step.objectives[0].required, 3);
208
209
harness.simulation.quests.noteKill(character.character_id, { mobTypeId: "rat", spawnerId: null });
210
snap = harness.simulation.quests.questSnapshot(character.character_id);
211
assert.equal(snap.quests[0].step.stepId, "choice");
212
assert.equal(snap.quests[0].step.objectives[0].current, 1);
213
assert.equal(
214
harness.stateDb.getQuestState(character.character_id, quest.questId).state,
215
"choice"
216
);
217
}
218
finally
219
{ harness.close(); }
220
});
221
222
test("noteKill counts only the active step resolved by step id", () =>
223
{
224
const harness = makeSimulation({ workerCount: 1 });
225
try
226
{
227
const quest = saveLiveQuest(harness, {
228
questId: "kill-which",
229
title: "Which",
230
steps: [{
231
stepId: "first",
232
title: "Deer",
233
objectives: [{
234
objectiveId: "deer",
235
text: "Deer",
236
when: { all: [{ condition: { kind: "killCount", mobTypeId: "deer", count: 1 } }] }
237
}]
238
}, {
239
stepId: "second",
240
title: "Rats",
241
objectives: [{
242
objectiveId: "rats",
243
text: "Rats",
244
when: { all: [{ condition: { kind: "killCount", mobTypeId: "rat", count: 2 } }] }
245
}]
246
}]
247
});
248
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
249
harness.simulation.spawnCharacter(1, character);
250
harness.simulation.step();
251
harness.stateDb.saveQuestState(character.character_id, quest.questId, "second", {
252
completedObjectiveIds: [],
253
counters: {},
254
completedStepIds: ["first"]
255
}, Date.now(), null);
256
harness.simulation.quests.noteKill(character.character_id, { mobTypeId: "deer", spawnerId: null });
257
harness.simulation.quests.noteKill(character.character_id, { mobTypeId: "rat", spawnerId: null });
258
const state = harness.stateDb.getQuestState(character.character_id, quest.questId);
259
assert.equal(state.state, "second");
260
assert.equal(state.progress.counters?.["mob:deer"], undefined);
261
assert.equal(state.progress.counters?.["mob:rat"], 1);
262
assert.deepEqual(state.progress.completedStepIds, ["first"]);
263
}
264
finally
265
{ harness.close(); }
266
});
267
268
test("completed step ids survive a loop back onto the same step", () =>
269
{
270
const harness = makeSimulation({ workerCount: 1 });
271
try
272
{
273
const quest = saveLiveQuest(harness, {
274
questId: "loop-q",
275
title: "Loop",
276
steps: [{
277
stepId: "alpha",
278
title: "Alpha",
279
exit: {
280
kind: "branches",
281
branches: [{ text: "To beta", when: { all: [] }, nextStepId: "beta" }]
282
}
283
}, {
284
stepId: "beta",
285
title: "Beta",
286
exit: {
287
kind: "branches",
288
branches: [{ text: "To alpha", when: { all: [] }, nextStepId: "alpha" }]
289
}
290
}]
291
});
292
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
293
harness.simulation.spawnCharacter(1, character);
294
harness.simulation.step();
295
const view = harness.simulation.quests.playerViewFor(character.character_id);
296
harness.simulation.quests.startQuest(character.character_id, quest.questId, view, []);
297
let state = harness.stateDb.getQuestState(character.character_id, quest.questId);
298
assert.equal(state.state, "beta");
299
assert.deepEqual(state.progress.completedStepIds, ["alpha"]);
300
301
harness.simulation.quests.reevaluateQuests(character.character_id, view, []);
302
state = harness.stateDb.getQuestState(character.character_id, quest.questId);
303
assert.equal(state.state, "alpha");
304
assert.deepEqual(state.progress.completedStepIds, ["alpha", "beta"]);
305
306
harness.simulation.quests.reevaluateQuests(character.character_id, view, []);
307
state = harness.stateDb.getQuestState(character.character_id, quest.questId);
308
assert.equal(state.state, "beta");
309
assert.deepEqual(state.progress.completedStepIds, ["alpha", "beta"]);
310
assert.equal(state.state === "completed", false);
311
}
312
finally
313
{ harness.close(); }
314
});
315
316
test("legacy numeric quest index resolves the step and unlocks doors", () =>
317
{
318
const harness = makeSimulation({ workerCount: 1 });
319
try
320
{
321
const quest = saveLiveQuest(harness, {
322
questId: "door-steps",
323
title: "Door Steps",
324
steps: [{
325
stepId: "gate-a",
326
title: "First",
327
objectives: stuckObjective(99991)
328
}, {
329
stepId: "gate-b",
330
title: "Second",
331
objectives: stuckObjective(99992)
332
}]
333
});
334
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
335
const entityId = harness.simulation.spawnCharacter(1, character);
336
harness.simulation.step();
337
const worker = workerOf(harness.simulation, entityId);
338
placeDoor(worker, 9, 8, {
339
all: [{ condition: { kind: ConditionKind.questStepAtLeast, questId: quest.questId, step: 2 } }]
340
});
341
assert.equal(worker.world.walkableFor(entityId, 9, 8), false);
342
343
harness.stateDb.saveQuestState(character.character_id, quest.questId, 2, {}, Date.now(), null);
344
harness.simulation.syncCharacterConditionAccess(character.character_id);
345
const snap = harness.simulation.quests.questSnapshot(character.character_id);
346
assert.equal(snap.quests[0].step.stepId, "gate-b");
347
assert.equal(worker.world.walkableFor(entityId, 9, 8), true, "at least step 2 means gate-a was completed");
348
349
placeDoor(worker, 9, 8, {
350
all: [{
351
condition: {
352
kind: ConditionKind.hasCompletedStep,
353
questId: quest.questId,
354
stepId: "gate-b"
355
}
356
}]
357
});
358
assert.equal(worker.world.walkableFor(entityId, 9, 8), false);
359
360
placeDoor(worker, 9, 8, {
361
all: [{
362
condition: { kind: ConditionKind.questState, questId: quest.questId, state: "gate-b" }
363
}]
364
});
365
assert.equal(worker.world.walkableFor(entityId, 9, 8), true);
366
367
placeDoor(worker, 9, 8, {
368
all: [{
369
condition: { kind: ConditionKind.questState, questId: quest.questId, state: "gate-a" }
370
}]
371
});
372
assert.equal(worker.world.walkableFor(entityId, 9, 8), false);
373
}
374
finally
375
{ harness.close(); }
376
});
@@ -0,0 +1,376 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import { normalizeQuestDef } from "../../shared/quests/normalize.js";4
import { ConditionKind } from "../../shared/quests/conditions.js";5
import { normalizeDoorConfig } from "../../shared/world/doorRequirements.js";6
import { BlockType } from "../../shared/definitions/tiles.js";7
import { ItemId } from "../../shared/definitions/items.js";8
import { SkillId } from "../../shared/definitions/skills.js";9
import { emptyEquipment, emptySlots, INVENTORY_SLOTS } from "../../shared/items/inventory.js";10
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";11
12
function saveLiveQuest (harness, raw)13
{14
const revisionId = harness.worldDb.getActiveRevisionId();15
const quest = normalizeQuestDef(raw);16
harness.worldDb.saveQuestDef(revisionId, quest);17
harness.simulation.questContent.reload();18
return quest;19
}20
21
function stuckObjective (itemId = 99999)22
{23
return [{24
objectiveId: "stay",25
text: "Stay",26
when: { all: [{ condition: { kind: "hasItem", itemId, quantity: 1 } }] }27
}];28
}29
30
function openObjective ()31
{32
return [{ objectiveId: "go", text: "Go", when: { all: [] } }];33
}34
35
function workerOf (simulation, entityId)36
{37
const record = simulation.entityRecord(entityId);38
assert.ok(record);39
return simulation.workers[record.workerId];40
}41
42
function placeDoor (worker, tileX, tileY, when)43
{44
const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));45
const localX = ((tileX % 16) + 16) % 16;46
const localY = ((tileY % 16) + 16) % 16;47
data.blocks[localY * 16 + localX] = {48
typeId: BlockType.door,49
state: "oak-n-closed",50
config: normalizeDoorConfig({ when, blockedMessage: "Not yet." })51
};52
}53
54
test("linear quests still advance one step per evaluation and reward once", () =>55
{56
const harness = makeSimulation({ workerCount: 1 });57
try58
{59
const quest = saveLiveQuest(harness, {60
questId: "linear-chain",61
title: "Linear",62
steps: [63
{ stepId: "s1", title: "One", objectives: openObjective(), completionJournalText: "One done." },64
{ stepId: "s2", title: "Two", objectives: openObjective(), completionJournalText: "Two done." },65
{ stepId: "s3", title: "Three", objectives: openObjective(), completionJournalText: "Three done." }66
],67
rewards: [{ kind: "giveXp", skillId: SkillId.woodworking, amount: 11 }]68
});69
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });70
harness.simulation.spawnCharacter(1, character);71
harness.simulation.step();72
const view = harness.simulation.quests.playerViewFor(character.character_id);73
const events = [];74
harness.simulation.quests.startQuest(character.character_id, quest.questId, view, events);75
assert.equal(events.some((event) => event.type === "questComplete"), false);76
let state = harness.stateDb.getQuestState(character.character_id, quest.questId);77
assert.equal(state.state, "s2");78
assert.deepEqual(state.progress.completedStepIds, ["s1"]);79
80
harness.simulation.quests.reevaluateQuests(character.character_id, view, []);81
state = harness.stateDb.getQuestState(character.character_id, quest.questId);82
assert.equal(state.state, "s3");83
assert.deepEqual(state.progress.completedStepIds, ["s1", "s2"]);84
assert.equal(harness.stateDb.getSkills(character.character_id).xp.woodworking, 0);85
86
harness.simulation.quests.reevaluateQuests(character.character_id, view, []);87
state = harness.stateDb.getQuestState(character.character_id, quest.questId);88
assert.equal(state.state, "completed");89
assert.deepEqual(state.progress.completedStepIds, ["s1", "s2", "s3"]);90
assert.equal(harness.stateDb.getSkills(character.character_id).xp.woodworking, 11);91
92
harness.simulation.quests.reevaluateQuests(character.character_id, view, []);93
assert.equal(harness.stateDb.getSkills(character.character_id).xp.woodworking, 11);94
assert.equal(95
harness.stateDb.getQuestState(character.character_id, quest.questId).state,96
"completed"97
);98
}99
finally100
{ harness.close(); }101
});102
103
test("branch exit takes the first matching condition set only", () =>104
{105
const harness = makeSimulation({ workerCount: 1 });106
try107
{108
const quest = saveLiveQuest(harness, {109
questId: "branch-first",110
title: "Branch",111
steps: [{112
stepId: "hub",113
title: "Hub",114
exit: {115
kind: "branches",116
branches: [117
{118
label: "Bones",119
text: "Bring bones",120
when: { all: [{ condition: { kind: "hasItem", itemId: ItemId.bones, quantity: 1 } }] },121
nextStepId: "bones-path"122
},123
{124
label: "Other",125
text: "Otherwise",126
when: { all: [] },127
nextStepId: "other-path"128
}129
]130
}131
}, {132
stepId: "bones-path",133
title: "Bones",134
objectives: stuckObjective()135
}, {136
stepId: "other-path",137
title: "Other",138
objectives: stuckObjective()139
}]140
});141
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });142
const playerId = harness.simulation.spawnCharacter(1, character);143
harness.simulation.step();144
const inventory = emptySlots(INVENTORY_SLOTS);145
inventory[0] = { itemId: ItemId.bones, quantity: 1 };146
harness.simulation.applyBag(playerId, {147
inventory,148
equipment: emptyEquipment(),149
vault: [],150
vaultReserved: []151
});152
const view = harness.simulation.quests.playerViewFor(character.character_id);153
harness.simulation.quests.startQuest(character.character_id, quest.questId, view, []);154
const state = harness.stateDb.getQuestState(character.character_id, quest.questId);155
assert.equal(state.state, "bones-path");156
assert.deepEqual(state.progress.completedStepIds, ["hub"]);157
const snap = harness.simulation.quests.questSnapshot(character.character_id);158
assert.equal(snap.quests[0].step.stepId, "bones-path");159
}160
finally161
{ harness.close(); }162
});163
164
test("unmatched branch step shows branch texts with kill progress", () =>165
{166
const harness = makeSimulation({ workerCount: 1 });167
try168
{169
const quest = saveLiveQuest(harness, {170
questId: "branch-log",171
title: "Log",172
steps: [{173
stepId: "choice",174
title: "Choose",175
exit: {176
kind: "branches",177
branches: [178
{179
text: "Kill rats",180
when: { all: [{ condition: { kind: "killCount", mobTypeId: "rat", count: 3 } }] },181
nextStepId: "done"182
},183
{184
text: "Bring bones",185
when: { all: [{ condition: { kind: "hasItem", itemId: ItemId.bones, quantity: 2 } }] },186
nextStepId: "done"187
}188
]189
}190
}, {191
stepId: "done",192
title: "Done",193
objectives: stuckObjective()194
}]195
});196
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });197
harness.simulation.spawnCharacter(1, character);198
harness.simulation.step();199
const view = harness.simulation.quests.playerViewFor(character.character_id);200
harness.simulation.quests.startQuest(character.character_id, quest.questId, view, []);201
let snap = harness.simulation.quests.questSnapshot(character.character_id);202
assert.deepEqual(203
snap.quests[0].step.objectives.map((line) => line.text),204
["Kill rats", "Bring bones"]205
);206
assert.equal(snap.quests[0].step.objectives[0].current, 0);207
assert.equal(snap.quests[0].step.objectives[0].required, 3);208
209
harness.simulation.quests.noteKill(character.character_id, { mobTypeId: "rat", spawnerId: null });210
snap = harness.simulation.quests.questSnapshot(character.character_id);211
assert.equal(snap.quests[0].step.stepId, "choice");212
assert.equal(snap.quests[0].step.objectives[0].current, 1);213
assert.equal(214
harness.stateDb.getQuestState(character.character_id, quest.questId).state,215
"choice"216
);217
}218
finally219
{ harness.close(); }220
});221
222
test("noteKill counts only the active step resolved by step id", () =>223
{224
const harness = makeSimulation({ workerCount: 1 });225
try226
{227
const quest = saveLiveQuest(harness, {228
questId: "kill-which",229
title: "Which",230
steps: [{231
stepId: "first",232
title: "Deer",233
objectives: [{234
objectiveId: "deer",235
text: "Deer",236
when: { all: [{ condition: { kind: "killCount", mobTypeId: "deer", count: 1 } }] }237
}]238
}, {239
stepId: "second",240
title: "Rats",241
objectives: [{242
objectiveId: "rats",243
text: "Rats",244
when: { all: [{ condition: { kind: "killCount", mobTypeId: "rat", count: 2 } }] }245
}]246
}]247
});248
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });249
harness.simulation.spawnCharacter(1, character);250
harness.simulation.step();251
harness.stateDb.saveQuestState(character.character_id, quest.questId, "second", {252
completedObjectiveIds: [],253
counters: {},254
completedStepIds: ["first"]255
}, Date.now(), null);256
harness.simulation.quests.noteKill(character.character_id, { mobTypeId: "deer", spawnerId: null });257
harness.simulation.quests.noteKill(character.character_id, { mobTypeId: "rat", spawnerId: null });258
const state = harness.stateDb.getQuestState(character.character_id, quest.questId);259
assert.equal(state.state, "second");260
assert.equal(state.progress.counters?.["mob:deer"], undefined);261
assert.equal(state.progress.counters?.["mob:rat"], 1);262
assert.deepEqual(state.progress.completedStepIds, ["first"]);263
}264
finally265
{ harness.close(); }266
});267
268
test("completed step ids survive a loop back onto the same step", () =>269
{270
const harness = makeSimulation({ workerCount: 1 });271
try272
{273
const quest = saveLiveQuest(harness, {274
questId: "loop-q",275
title: "Loop",276
steps: [{277
stepId: "alpha",278
title: "Alpha",279
exit: {280
kind: "branches",281
branches: [{ text: "To beta", when: { all: [] }, nextStepId: "beta" }]282
}283
}, {284
stepId: "beta",285
title: "Beta",286
exit: {287
kind: "branches",288
branches: [{ text: "To alpha", when: { all: [] }, nextStepId: "alpha" }]289
}290
}]291
});292
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });293
harness.simulation.spawnCharacter(1, character);294
harness.simulation.step();295
const view = harness.simulation.quests.playerViewFor(character.character_id);296
harness.simulation.quests.startQuest(character.character_id, quest.questId, view, []);297
let state = harness.stateDb.getQuestState(character.character_id, quest.questId);298
assert.equal(state.state, "beta");299
assert.deepEqual(state.progress.completedStepIds, ["alpha"]);300
301
harness.simulation.quests.reevaluateQuests(character.character_id, view, []);302
state = harness.stateDb.getQuestState(character.character_id, quest.questId);303
assert.equal(state.state, "alpha");304
assert.deepEqual(state.progress.completedStepIds, ["alpha", "beta"]);305
306
harness.simulation.quests.reevaluateQuests(character.character_id, view, []);307
state = harness.stateDb.getQuestState(character.character_id, quest.questId);308
assert.equal(state.state, "beta");309
assert.deepEqual(state.progress.completedStepIds, ["alpha", "beta"]);310
assert.equal(state.state === "completed", false);311
}312
finally313
{ harness.close(); }314
});315
316
test("legacy numeric quest index resolves the step and unlocks doors", () =>317
{318
const harness = makeSimulation({ workerCount: 1 });319
try320
{321
const quest = saveLiveQuest(harness, {322
questId: "door-steps",323
title: "Door Steps",324
steps: [{325
stepId: "gate-a",326
title: "First",327
objectives: stuckObjective(99991)328
}, {329
stepId: "gate-b",330
title: "Second",331
objectives: stuckObjective(99992)332
}]333
});334
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });335
const entityId = harness.simulation.spawnCharacter(1, character);336
harness.simulation.step();337
const worker = workerOf(harness.simulation, entityId);338
placeDoor(worker, 9, 8, {339
all: [{ condition: { kind: ConditionKind.questStepAtLeast, questId: quest.questId, step: 2 } }]340
});341
assert.equal(worker.world.walkableFor(entityId, 9, 8), false);342
343
harness.stateDb.saveQuestState(character.character_id, quest.questId, 2, {}, Date.now(), null);344
harness.simulation.syncCharacterConditionAccess(character.character_id);345
const snap = harness.simulation.quests.questSnapshot(character.character_id);346
assert.equal(snap.quests[0].step.stepId, "gate-b");347
assert.equal(worker.world.walkableFor(entityId, 9, 8), true, "at least step 2 means gate-a was completed");348
349
placeDoor(worker, 9, 8, {350
all: [{351
condition: {352
kind: ConditionKind.hasCompletedStep,353
questId: quest.questId,354
stepId: "gate-b"355
}356
}]357
});358
assert.equal(worker.world.walkableFor(entityId, 9, 8), false);359
360
placeDoor(worker, 9, 8, {361
all: [{362
condition: { kind: ConditionKind.questState, questId: quest.questId, state: "gate-b" }363
}]364
});365
assert.equal(worker.world.walkableFor(entityId, 9, 8), true);366
367
placeDoor(worker, 9, 8, {368
all: [{369
condition: { kind: ConditionKind.questState, questId: quest.questId, state: "gate-a" }370
}]371
});372
assert.equal(worker.world.walkableFor(entityId, 9, 8), false);373
}374
finally375
{ harness.close(); }376
});@@ -10,7 +10,9 @@ import {
10
10
countableObjectiveProgress,
11
11
formatObjectiveDisplayText
12
12
} from "../../shared/quests/objectiveProgress.js";
13
import { normalizeQuestDef, normalizeDialogueTree } from "../../shared/quests/normalize.js";
13
import { normalizeQuestDef, normalizeDialogueTree, questLookupFromRawDefs } from "../../shared/quests/normalize.js";
14
import { deriveCompletedStepIds, resolveQuestStepId } from "../../shared/quests/questProgress.js";
15
import { evaluateCondition } from "../../shared/quests/conditions.js";
14
16
import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage, formatDialogueTakeMessage } from "../../shared/quests/dialogueRewards.js";
15
17
16
18
test("ConditionSet AND + NOT", () =>
@@ -74,6 +76,8 @@ test("normalize quest and dialogue", () =>
74
76
});
75
77
assert.equal(quest.questId, "fetch-ore");
76
78
assert.equal(quest.steps[0].objectives[0].when.all[0].condition.kind, "hasItem");
79
assert.equal(quest.steps[0].exit.kind, "complete");
80
assert.equal(quest.steps[0].exit.implicit, true);
77
81
78
82
const tree = normalizeDialogueTree({
79
83
dialogueId: "Smith",
@@ -149,6 +153,127 @@ test("countable objective progress for hasItem killCount and skillLevelAtLeast",
149
153
"Collect Pine Logs (5 / 30)"
150
154
);
151
155
156
const quests = [{
157
questId: "q",
158
steps: [{ stepId: "alpha" }, { stepId: "beta" }]
159
}];
160
const converted = normalizeConditionSet({
161
all: [
162
{ condition: { kind: "questStepAtLeast", questId: "q", step: 1 } },
163
{ condition: { kind: "questStepAtLeast", questId: "q", step: 2 } },
164
{ condition: { kind: "questStepAtLeast", questId: "q", step: 3 } },
165
{ condition: { kind: "questStepAtLeast", questId: "q", step: 9 } },
166
{ condition: { kind: "questState", questId: "q", state: 2 } }
167
]
168
}, { quests });
169
assert.deepEqual(converted.all[0].condition, { kind: "questState", questId: "q", state: "started" });
170
assert.deepEqual(converted.all[1].condition, { kind: "hasCompletedStep", questId: "q", stepId: "alpha" });
171
assert.deepEqual(converted.all[2].condition, { kind: "hasCompletedStep", questId: "q", stepId: "beta" });
172
assert.deepEqual(converted.all[3].condition, { kind: "questState", questId: "q", state: "completed" });
173
assert.equal(converted.all[4].condition.state, "beta");
174
175
const pending = normalizeConditionSet({
176
all: [{ condition: { kind: "questStepAtLeast", questId: "missing", step: 2 } }]
177
});
178
assert.equal(pending.all[0].condition.kind, "questStepAtLeast");
179
assert.equal(
180
evaluateCondition(pending.all[0].condition, {
181
questState: () => "beta",
182
questSteps: () => ["alpha", "beta"],
183
hasCompletedStep: (_questId, stepId) => stepId === "alpha"
184
}),
185
true
186
);
187
assert.equal(
188
evaluateCondition(
189
{ kind: ConditionKind.hasCompletedStep, questId: "q", stepId: "alpha" },
190
{ hasCompletedStep: (_questId, stepId) => stepId === "alpha" }
191
),
192
true
193
);
194
assert.equal(
195
evaluateCondition(
196
{ kind: ConditionKind.questState, questId: "q", state: "beta" },
197
{ questState: () => "beta" }
198
),
199
true
200
);
201
assert.equal(
202
evaluateCondition(
203
{ kind: ConditionKind.questState, questId: "q", state: "started" },
204
{ questState: () => "not-started" }
205
),
206
false
207
);
208
209
const lookup = questLookupFromRawDefs(quests);
210
const tree = normalizeDialogueTree({
211
dialogueId: "gate",
212
steps: [{
213
stepId: "hi",
214
lines: [{ speaker: "npc", text: "Hi" }],
215
exit: {
216
kind: "branches",
217
branches: [{
218
when: { all: [{ condition: { kind: "questStepAtLeast", questId: "q", step: 2 } }] },
219
nextStepId: null
220
}]
221
}
222
}]
223
}, lookup);
224
assert.equal(tree.steps[0].exit.branches[0].when.all[0].condition.kind, "hasCompletedStep");
225
assert.equal(tree.steps[0].exit.branches[0].when.all[0].condition.stepId, "alpha");
226
227
const linked = normalizeQuestDef({
228
questId: "chain",
229
steps: [{ stepId: "a" }, { stepId: "b" }]
230
});
231
assert.equal(linked.steps[0].exit.kind, "continue");
232
assert.equal(linked.steps[0].exit.nextStepId, "b");
233
assert.equal(linked.steps[0].exit.implicit, true);
234
const inserted = normalizeQuestDef({
235
...linked,
236
steps: [linked.steps[0], { stepId: "mid", title: "Mid" }, linked.steps[1]]
237
});
238
assert.equal(inserted.steps[0].exit.nextStepId, "mid");
239
assert.equal(inserted.steps[1].exit.nextStepId, "b");
240
assert.equal(inserted.steps[2].exit.kind, "complete");
241
242
const branched = normalizeQuestDef({
243
questId: "hub-quest",
244
steps: [{
245
stepId: "hub",
246
exit: {
247
kind: "branches",
248
branches: [{
249
label: "Cave",
250
text: "Stand in the cave",
251
when: { all: [{ condition: { kind: "atTile", tileX: 3, tileY: 4, dimensionId: "cave" } }] },
252
nextStepId: "end"
253
}]
254
}
255
}, { stepId: "end" }]
256
});
257
assert.equal(branched.steps[0].exit.kind, "branches");
258
assert.equal(branched.steps[0].exit.implicit, undefined);
259
assert.equal(branched.steps[0].exit.branches[0].when.all[0].condition.dimensionId, "cave");
260
assert.equal(branched.steps[1].exit.kind, "complete");
261
262
const linearDef = {
263
steps: [{ stepId: "alpha" }, { stepId: "beta" }, { stepId: "gamma" }]
264
};
265
assert.deepEqual(deriveCompletedStepIds(linearDef, 2, {}), ["alpha"]);
266
assert.deepEqual(
267
deriveCompletedStepIds(linearDef, "completed", {}),
268
["alpha", "beta", "gamma"]
269
);
270
assert.deepEqual(
271
deriveCompletedStepIds(linearDef, "beta", { completedStepIds: ["alpha"] }),
272
["alpha"]
273
);
274
assert.equal(resolveQuestStepId(linearDef, 2), "beta");
275
assert.equal(resolveQuestStepId(linearDef, "gamma"), "gamma");
276
152
277
const kills = normalizeConditionSet({
153
278
all: [{ condition: { kind: ConditionKind.killCount, mobTypeId: "rat", count: 3 } }]
154
279
});
@@ -10,7 +10,9 @@ import {10
countableObjectiveProgress,10
countableObjectiveProgress,11
formatObjectiveDisplayText11
formatObjectiveDisplayText12
} from "../../shared/quests/objectiveProgress.js";12
} from "../../shared/quests/objectiveProgress.js";13
import { normalizeQuestDef, normalizeDialogueTree } from "../../shared/quests/normalize.js";13
import { normalizeQuestDef, normalizeDialogueTree, questLookupFromRawDefs } from "../../shared/quests/normalize.js";14
import { deriveCompletedStepIds, resolveQuestStepId } from "../../shared/quests/questProgress.js";15
import { evaluateCondition } from "../../shared/quests/conditions.js";14
import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage, formatDialogueTakeMessage } from "../../shared/quests/dialogueRewards.js";16
import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage, formatDialogueTakeMessage } from "../../shared/quests/dialogueRewards.js";15
17
16
test("ConditionSet AND + NOT", () =>18
test("ConditionSet AND + NOT", () =>@@ -74,6 +76,8 @@ test("normalize quest and dialogue", () =>74
});76
});75
assert.equal(quest.questId, "fetch-ore");77
assert.equal(quest.questId, "fetch-ore");76
assert.equal(quest.steps[0].objectives[0].when.all[0].condition.kind, "hasItem");78
assert.equal(quest.steps[0].objectives[0].when.all[0].condition.kind, "hasItem");79
assert.equal(quest.steps[0].exit.kind, "complete");80
assert.equal(quest.steps[0].exit.implicit, true);77
81
78
const tree = normalizeDialogueTree({82
const tree = normalizeDialogueTree({79
dialogueId: "Smith",83
dialogueId: "Smith",@@ -149,6 +153,127 @@ test("countable objective progress for hasItem killCount and skillLevelAtLeast",149
"Collect Pine Logs (5 / 30)"153
"Collect Pine Logs (5 / 30)"150
);154
);151
155
156
const quests = [{157
questId: "q",158
steps: [{ stepId: "alpha" }, { stepId: "beta" }]159
}];160
const converted = normalizeConditionSet({161
all: [162
{ condition: { kind: "questStepAtLeast", questId: "q", step: 1 } },163
{ condition: { kind: "questStepAtLeast", questId: "q", step: 2 } },164
{ condition: { kind: "questStepAtLeast", questId: "q", step: 3 } },165
{ condition: { kind: "questStepAtLeast", questId: "q", step: 9 } },166
{ condition: { kind: "questState", questId: "q", state: 2 } }167
]168
}, { quests });169
assert.deepEqual(converted.all[0].condition, { kind: "questState", questId: "q", state: "started" });170
assert.deepEqual(converted.all[1].condition, { kind: "hasCompletedStep", questId: "q", stepId: "alpha" });171
assert.deepEqual(converted.all[2].condition, { kind: "hasCompletedStep", questId: "q", stepId: "beta" });172
assert.deepEqual(converted.all[3].condition, { kind: "questState", questId: "q", state: "completed" });173
assert.equal(converted.all[4].condition.state, "beta");174
175
const pending = normalizeConditionSet({176
all: [{ condition: { kind: "questStepAtLeast", questId: "missing", step: 2 } }]177
});178
assert.equal(pending.all[0].condition.kind, "questStepAtLeast");179
assert.equal(180
evaluateCondition(pending.all[0].condition, {181
questState: () => "beta",182
questSteps: () => ["alpha", "beta"],183
hasCompletedStep: (_questId, stepId) => stepId === "alpha"184
}),185
true186
);187
assert.equal(188
evaluateCondition(189
{ kind: ConditionKind.hasCompletedStep, questId: "q", stepId: "alpha" },190
{ hasCompletedStep: (_questId, stepId) => stepId === "alpha" }191
),192
true193
);194
assert.equal(195
evaluateCondition(196
{ kind: ConditionKind.questState, questId: "q", state: "beta" },197
{ questState: () => "beta" }198
),199
true200
);201
assert.equal(202
evaluateCondition(203
{ kind: ConditionKind.questState, questId: "q", state: "started" },204
{ questState: () => "not-started" }205
),206
false207
);208
209
const lookup = questLookupFromRawDefs(quests);210
const tree = normalizeDialogueTree({211
dialogueId: "gate",212
steps: [{213
stepId: "hi",214
lines: [{ speaker: "npc", text: "Hi" }],215
exit: {216
kind: "branches",217
branches: [{218
when: { all: [{ condition: { kind: "questStepAtLeast", questId: "q", step: 2 } }] },219
nextStepId: null220
}]221
}222
}]223
}, lookup);224
assert.equal(tree.steps[0].exit.branches[0].when.all[0].condition.kind, "hasCompletedStep");225
assert.equal(tree.steps[0].exit.branches[0].when.all[0].condition.stepId, "alpha");226
227
const linked = normalizeQuestDef({228
questId: "chain",229
steps: [{ stepId: "a" }, { stepId: "b" }]230
});231
assert.equal(linked.steps[0].exit.kind, "continue");232
assert.equal(linked.steps[0].exit.nextStepId, "b");233
assert.equal(linked.steps[0].exit.implicit, true);234
const inserted = normalizeQuestDef({235
...linked,236
steps: [linked.steps[0], { stepId: "mid", title: "Mid" }, linked.steps[1]]237
});238
assert.equal(inserted.steps[0].exit.nextStepId, "mid");239
assert.equal(inserted.steps[1].exit.nextStepId, "b");240
assert.equal(inserted.steps[2].exit.kind, "complete");241
242
const branched = normalizeQuestDef({243
questId: "hub-quest",244
steps: [{245
stepId: "hub",246
exit: {247
kind: "branches",248
branches: [{249
label: "Cave",250
text: "Stand in the cave",251
when: { all: [{ condition: { kind: "atTile", tileX: 3, tileY: 4, dimensionId: "cave" } }] },252
nextStepId: "end"253
}]254
}255
}, { stepId: "end" }]256
});257
assert.equal(branched.steps[0].exit.kind, "branches");258
assert.equal(branched.steps[0].exit.implicit, undefined);259
assert.equal(branched.steps[0].exit.branches[0].when.all[0].condition.dimensionId, "cave");260
assert.equal(branched.steps[1].exit.kind, "complete");261
262
const linearDef = {263
steps: [{ stepId: "alpha" }, { stepId: "beta" }, { stepId: "gamma" }]264
};265
assert.deepEqual(deriveCompletedStepIds(linearDef, 2, {}), ["alpha"]);266
assert.deepEqual(267
deriveCompletedStepIds(linearDef, "completed", {}),268
["alpha", "beta", "gamma"]269
);270
assert.deepEqual(271
deriveCompletedStepIds(linearDef, "beta", { completedStepIds: ["alpha"] }),272
["alpha"]273
);274
assert.equal(resolveQuestStepId(linearDef, 2), "beta");275
assert.equal(resolveQuestStepId(linearDef, "gamma"), "gamma");276
152
const kills = normalizeConditionSet({277
const kills = normalizeConditionSet({153
all: [{ condition: { kind: ConditionKind.killCount, mobTypeId: "rat", count: 3 } }]278
all: [{ condition: { kind: ConditionKind.killCount, mobTypeId: "rat", count: 3 } }]154
});279
});