BlueGit

timfa questward

Lock in quests/dialogue v1 plan: world editors, shared conditions, toast.

EOF

timfa Tim Falken · pushed by timfa

Authored 2026-08-27 · 2 months ago

Hash
9f43f5fbb88d72599a311374a22d60cfb6054a31
Parent
1383a51b
2 files changed +404 −284
docs/FEATURES.md +3 −3
@@ -70,7 +70,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
70 70 ## World editor (client)
71 71
72 72 **Status:** full
73 **Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states (for outdoor seasonal tiles: summer/fall/winter, which also updates Season preview), open/closed, per-chunk changelog, night preview slider, **season preview** dropdown, world-settings modal, save chunk and Apply now. **Save chunk** is disabled when clean and **pulses** when the draft is dirty; navigating N/S/E/W with unsaved edits opens a confirm modal (Cancel / Discard / Save). **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). **Flower** is a single palette entry; each paint rolls a random colour (same as harvest respawn). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only.
73 **Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states (for outdoor seasonal tiles: summer/fall/winter, which also updates Season preview), open/closed, per-chunk changelog, night preview slider, **season preview** dropdown, world-settings modal, save chunk and Apply now. **Save chunk** is disabled when clean and **pulses** when the draft is dirty; navigating N/S/E/W with unsaved edits opens a confirm modal (Cancel / Discard / Save). Bottom status bar shows hovered **tile** and **chunk** coordinates. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). **Flower** is a single palette entry; each paint rolls a random colour (same as harvest respawn). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only.
74 74 **Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`
75 75
76 76 ## Per-chunk changelog
@@ -190,13 +190,13 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
190 190 ## Mob definitions (content schema)
191 191
192 192 **Status:** partial
193 **Spec:** Target mob content shape: `displayName`, `maxHealth`, `attackSkill`, `drops`, `sells`, and `dialogue` trees. **Authored dialogue** for talkable/humanoid NPCs lives on the **spawner** in the world editor (not hard-coded mob defs). Node shape: `trigger`, `lines[]` (`speaker: npc|player`, `text`), `responses[]` (`label`, `nextTrigger`, `require[]`, optional `effects[]`). See [`docs/QUESTS.md`](QUESTS.md).
193 **Spec:** Target mob content shape: `displayName`, `maxHealth`, `attackSkill`, `drops`, `sells`. **Dialogue trees** are world-scoped assets (Dialogues editor); humanoid spawners assign `config.dialogueId`. See [`docs/QUESTS.md`](QUESTS.md).
194 194 **Code:** `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`
195 195
196 196 ## Quests
197 197
198 198 **Status:** not implemented (design)
199 **Spec:** Full design in [`docs/QUESTS.md`](QUESTS.md). Editor **Quests** menu authors world-scoped quest defs (linear steps + conditions: has item, at place, dialogue trigger on spawner, kill/count, block interact). Dialogue on spawners can start quests and gate responses on quest state. Progress in `state.sqlite`; rewards may pigeon overflow to vault.
199 **Spec:** Full design in [`docs/QUESTS.md`](QUESTS.md). World editor **Quests** / **Dialogues** buttons (under Settings) author world-scoped defs. Spawners link `dialogueId`; unique dialogues require one spawner with `maxAlive: 1`. Shared `ConditionSet` (AND + per-clause NOT). Play **Quests** UI + step-complete toast “Quest objectives achieved”. Progress / journal / `dialogueHeard` in `state.sqlite`.
200 200 **Code:** —
201 201
202 202 ## Character logout resume
@@ -70,7 +70,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
70## World editor (client)
70## World editor (client)
71
71
72**Status:** full
72**Status:** full
73**Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states (for outdoor seasonal tiles: summer/fall/winter, which also updates Season preview), open/closed, per-chunk changelog, night preview slider, **season preview** dropdown, world-settings modal, save chunk and Apply now. **Save chunk** is disabled when clean and **pulses** when the draft is dirty; navigating N/S/E/W with unsaved edits opens a confirm modal (Cancel / Discard / Save). **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). **Flower** is a single palette entry; each paint rolls a random colour (same as harvest respawn). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only.
73**Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states (for outdoor seasonal tiles: summer/fall/winter, which also updates Season preview), open/closed, per-chunk changelog, night preview slider, **season preview** dropdown, world-settings modal, save chunk and Apply now. **Save chunk** is disabled when clean and **pulses** when the draft is dirty; navigating N/S/E/W with unsaved edits opens a confirm modal (Cancel / Discard / Save). Bottom status bar shows hovered **tile** and **chunk** coordinates. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). **Flower** is a single palette entry; each paint rolls a random colour (same as harvest respawn). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only.
74**Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`
74**Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`
75
75
76## Per-chunk changelog
76## Per-chunk changelog
@@ -190,13 +190,13 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
190## Mob definitions (content schema)
190## Mob definitions (content schema)
191
191
192**Status:** partial
192**Status:** partial
193**Spec:** Target mob content shape: `displayName`, `maxHealth`, `attackSkill`, `drops`, `sells`, and `dialogue` trees. **Authored dialogue** for talkable/humanoid NPCs lives on the **spawner** in the world editor (not hard-coded mob defs). Node shape: `trigger`, `lines[]` (`speaker: npc|player`, `text`), `responses[]` (`label`, `nextTrigger`, `require[]`, optional `effects[]`). See [`docs/QUESTS.md`](QUESTS.md).
193**Spec:** Target mob content shape: `displayName`, `maxHealth`, `attackSkill`, `drops`, `sells`. **Dialogue trees** are world-scoped assets (Dialogues editor); humanoid spawners assign `config.dialogueId`. See [`docs/QUESTS.md`](QUESTS.md).
194**Code:** `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`
194**Code:** `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`
195
195
196## Quests
196## Quests
197
197
198**Status:** not implemented (design)
198**Status:** not implemented (design)
199**Spec:** Full design in [`docs/QUESTS.md`](QUESTS.md). Editor **Quests** menu authors world-scoped quest defs (linear steps + conditions: has item, at place, dialogue trigger on spawner, kill/count, block interact). Dialogue on spawners can start quests and gate responses on quest state. Progress in `state.sqlite`; rewards may pigeon overflow to vault.
199**Spec:** Full design in [`docs/QUESTS.md`](QUESTS.md). World editor **Quests** / **Dialogues** buttons (under Settings) author world-scoped defs. Spawners link `dialogueId`; unique dialogues require one spawner with `maxAlive: 1`. Shared `ConditionSet` (AND + per-clause NOT). Play **Quests** UI + step-complete toast “Quest objectives achieved”. Progress / journal / `dialogueHeard` in `state.sqlite`.
200**Code:** —
200**Code:** —
201
201
202## Character logout resume
202## Character logout resume
docs/QUESTS.md +401 −281
@@ -1,281 +1,401 @@
1 # Quests & NPC dialogue (world editor)
2
3 **Status:** not implemented (design only)
4 **Related:** `docs/FEATURES.md` (Quests, Mob definitions), `docs/SCRIPTS.md` (parity reminder for future script verbs), server authority rules
5
6 Quests and NPC dialogue are **admin-authored content**. Authors create and edit them entirely in the **world editor**. Runtime evaluation is **server-authoritative**; clients only display dialogue UI and quest log snapshots.
7
8 This document is the product + data + editor spec for implementation.
9
10 ---
11
12 ## 1. Goals
13
14 - Author quests without code changes (editor **Quests** menu).
15 - Author full NPC dialogue trees on the **spawner** that owns that NPC.
16 - Progress quests via clear, checkable **conditions** (inventory, place, dialogue, kills, block interact).
17 - Keep data stable, reviewable, and Apply-revision friendly (same map-revision pipeline as chunks where content is world-scoped).
18 - Fail safe: broken references do not soft-lock players forever without admin tools / clear errors.
19
20 ---
21
22 ## 2. Persistence & identity
23
24 | Asset | Storage | Apply model |
25 |-------|---------|-------------|
26 | **Quest definitions** | `world.sqlite` (authored, revisioned with map / pending revision — same spirit as chunks) | Editor save → pending; **Apply now** loads into live sim |
27 | **Dialogue trees** | On each **spawner config** inside chunk data (`config.dialogue[]`) | Saved with the chunk |
28 | **Quest progress** | `state.sqlite` per character | Live; never in world revision |
29
30 ### 2.1 IDs
31
32 - **Quest id:** stable string slug, editor-assigned, unique (`deliver-tin-ore`, `guard-rats-1`). Immutable after first publish preferred; rename is a new id + migration warning.
33 - **Step id:** stable string within a quest (`step-gather`, `step-return`).
34 - **Dialogue trigger:** stable string within a spawner’s dialogue set (`greeting`, `quest-offer`, `quest-turnin`).
35 - **NPC reference in quests:** prefer **spawner id** (`chunkX:chunkY:index` or authored `spawnerId`) + optional display-name hint — not transient entity ids.
36
37 ### 2.2 Quests menu (editor)
38
39 Top-level editor control **Quests** (alongside Settings / palette):
40
41 - List all quests (id, title, step count, validation warnings).
42 - **New** / **Edit** / **Duplicate** / **Delete** (delete warns if dialogue responses reference the quest).
43 - Editor panel is world-global (not per-chunk), but saves go through the same admin auth + revision story as other authored world data.
44
45 ---
46
47 ## 3. Quest definition shape
48
49 ```text
50 Quest {
51 questId: string
52 title: string
53 description: string // player-facing log blurb (in-universe)
54 steps: Step[] // ordered progression
55 rewards?: Reward[] // granted on final step complete
56 cancelable?: boolean // default false in v1
57 }
58 ```
59
60 ### 3.1 Steps
61
62 Each step is completed when **all** of its `require` conditions are true (AND). Optional `anyOf` groups later; v1 stays AND-only for clarity.
63
64 ```text
65 Step {
66 stepId: string
67 title: string // short log line
68 hint?: string // optional guidance
69 require: Condition[] // all must pass
70 onEnter?: Effect[] // optional (toast, flag) — keep minimal in v1
71 onComplete?: Effect[] // optional mid-quest grants; prefer final rewards
72 }
73 ```
74
75 Advancement: when the active step’s conditions are satisfied, the server marks it complete and activates the next step (or completes the quest).
76
77 ### 3.2 Conditions (v1)
78
79 | Kind | Fields | Meaning |
80 |------|--------|---------|
81 | `hasItem` | `itemId`, `quantity` (≥ 1) | Bag (not vault) contains at least N |
82 | `atTile` | `tileX`, `tileY` (optional `radius` Chebyshev, default 0) | Player stands on/near tile |
83 | `atChunk` | `chunkX`, `chunkY` | Player’s chunk equals (coarse place) |
84 | `dialogueTrigger` | `spawnerId`, `trigger` | Player fired that dialogue trigger on an NPC from that spawner (see §5) |
85 | `killMob` | `mobTypeId` **or** `spawnerId`, optional `displayName` | **Event:** player deals killing blow to matching mob (advances a counter or one-shot flag on the step) |
86 | `killCount` | `mobTypeId` **or** `spawnerId`, `count` N | Player has killed N matching mobs **while this step is active** (quota) |
87 | `interactBlock` | `tileX`, `tileY` **or** `blockTypeId` + optional tile, `action?` | Player successfully interacts with that block (LMB/use as defined for the block) |
88
89 **Notes:**
90
91 - `killMob` vs `killCount`: one-shot event vs quota. Prefer `killCount` with `count: 1` instead of a separate one-shot if it simplifies the engine — editor can still show “kill once” UX that writes `killCount: 1`.
92 - Kill attribution: **last hitting player** / engaged killer consistent with existing combat kill credit (same as bounty).
93 - `hasItem` does **not** consume items unless an **effect** or turn-in dialogue action says so.
94 - `interactBlock` must be a real completed interact (open bank alone does not count unless the quest names that block and the interact handler emits the quest event).
95
96 ### 3.3 Rewards & effects (v1)
97
98 | Kind | Fields |
99 |------|--------|
100 | `giveItem` | `itemId`, `quantity` |
101 | `giveXp` | `skillId`, `amount` |
102 | `takeItem` | `itemId`, `quantity` (turn-in) |
103 | `startQuest` | `questId` (from dialogue) |
104 | `setDialogueFlag` | optional local flag — defer if unused |
105
106 Full bag on `giveItem`: overflow to vault by **carrier pigeon** (existing FEATURES note).
107
108 ---
109
110 ## 4. Character quest state
111
112 ```text
113 CharacterQuest {
114 questId
115 status: inactive | active | completed | failed // failed unused in v1 unless cancel
116 activeStepId: string | null
117 completedStepIds: string[]
118 counters: { [key: string]: number } // e.g. kill quotas for current step
119 startedAt, completedAt
120 }
121 ```
122
123 - Persist in `state.sqlite`.
124 - Replicate a compact **quest log** snapshot to the client (title, step title/hint, progress counts).
125 - Server re-evaluates conditions on relevant events (inventory change, move, kill, interact, dialogue) — not on a tight poll.
126
127 ---
128
129 ## 5. Dialogue on spawners
130
131 Dialogue is authored **per spawner** (humanoid / talkable NPC), not in code mob defs (defs may keep empty `dialogue: []`).
132
133 ### 5.1 Shape
134
135 ```text
136 DialogueNode {
137 trigger: string
138 lines: { speaker: "npc" | "player", text: string }[]
139 responses: DialogueResponse[]
140 }
141
142 DialogueResponse {
143 label: string // button text
144 nextTrigger: string | null // follow-up node trigger; null = end
145 require?: DialogueRequirement[] // all must pass to show/enable
146 effects?: Effect[] // on choose: startQuest, takeItem, …
147 }
148 ```
149
150 ### 5.2 Requirements on responses
151
152 | Kind | Fields |
153 |------|--------|
154 | `hasItem` | `itemId`, `quantity` |
155 | `questActive` | `questId` |
156 | `questCompleted` | `questId` |
157 | `questStepActive` | `questId`, `stepId` |
158 | `questStepCompleted` | `questId`, `stepId` |
159
160 Hidden vs disabled: **hide** responses that fail requirements (cleaner UX). Optional later: show disabled with reason.
161
162 ### 5.3 Runtime
163
164 1. Player talks to NPC (existing talkable interact).
165 2. Server opens dialogue at default trigger (`greeting` or first node) — or a quest-forced trigger if an effect set one.
166 3. Client shows lines in order (npc/player attribution for layout).
167 4. Player picks a response → server validates requirements + effects → may emit `dialogueTrigger` quest event with `{ spawnerId, trigger: chosen.nextTrigger or node.trigger }` as designed.
168 5. **Quest condition `dialogueTrigger`:** fires when the player **selects a response that leads to** that trigger, or when a node with that trigger is **entered** — pick **one** rule and stick to it.
169
170 **Resolved default:** condition matches when a dialogue **node with that `trigger` begins** (lines start showing). Starting a quest offer node counts; merely hovering a response does not.
171
172 ### 5.4 Editor UI (spawner modal)
173
174 Under humanoid fields: **Dialogue** section
175
176 - List nodes by trigger; add/remove/reorder.
177 - Per node: trigger id, lines editor (speaker toggle + text), responses (label, next trigger dropdown, requirement rows, optional effects).
178 - Validation: orphan triggers, missing nextTrigger targets, empty lines, unknown quest ids in requirements.
179
180 Central Exchange staff share one spawner config’s dialogue (same as shared equipment) unless we later split per clerk — **v1: shared tree**.
181
182 ---
183
184 ## 6. How quests start
185
186 Primary: dialogue response effect `startQuest`.
187 Secondary (optional v1.1): auto-start on enter tile / pickup — out of scope until needed.
188
189 Cannot start if already active or completed (unless quest allows repeat — **v1: no repeats**).
190
191 ---
192
193 ## 7. Implementation plan (phased)
194
195 1. **Data model + world DB tables** for quest defs; chunk spawner `dialogue[]` normalize/save.
196 2. **Editor Quests menu** CRUD + validation UI (no runtime).
197 3. **Editor spawner dialogue** UI + save on chunk.
198 4. **Editor UX** unsaved-chunk guard (§9) — can ship earlier independently.
199 5. **Runtime dialogue** — talk → server nodes → client panel; requirements; effects `startQuest` / `takeItem` / `giveItem`.
200 6. **Runtime quest engine** — state, condition listeners, step advance, rewards, quest log UI.
201 7. **Apply revision** reloads quest defs; in-flight character progress keeps quest ids (orphan progress if quest deleted — §8).
202 8. **Tests** for normalize, dialogue requirements, kill quotas, turn-in, overflow pigeon.
203 9. **Script verbs** (later): `if quest active "…"`, etc., in same commit as needed — see SCRIPTS.md parity rule.
204
205 ---
206
207 ## 8. Edge cases (resolved in plan)
208
209 | Topic | Decision |
210 |-------|----------|
211 | Quest deleted while players active | Progress remains `orphaned`; log shows “Quest unavailable”; cannot advance; admin may clear |
212 | Spawner id renamed | Dialogue/quest refs break → editor validation warning; runtime condition fails closed |
213 | Multiple NPCs same dialogue trigger string | Triggers are **per spawnerId**; no global trigger namespace |
214 | `hasItem` while item in vault | False — bag only |
215 | Kill credit for `killCount` | Only kills while step active; deaths by unrelated players don’t count for this character |
216 | Player dies mid-quest | Progress kept (no fail-on-death in v1) |
217 | Aggressive NPC + dialogue | Talkable only when not in combat / or always if talkable flag — **defer:** talkable if not currently targeting the player |
218 | Turn-in without removing items | Use explicit `takeItem` effect on the turn-in response or step `onComplete` |
219 | Concurrent steps | **No** — one active step per quest |
220 | Parallel quests | **Yes** — multiple active quests per character; soft cap e.g. **20** |
221 | `atTile` with multiplayer crowding | Standing on tile is enough |
222 | Interact same block repeatedly | `interactBlock` sets a once-flag per step unless condition is re-checkable each interact — **once per step** |
223 | Dialogue effects vs quest step conditions | Both allowed; prefer turn-in items via dialogue effects so the NPC “takes” them narratively |
224 | Chunk not loaded | Kill/interact on unloaded sim: only live simulating entities emit events (normal) |
225 | Apply mid-dialogue | Close dialogue on revision apply; reopen requires talk again |
226 | Non-humanoid dialogue | Only `talkable` / humanoid spawners show dialogue editor |
227
228 ### 8.1 Known weaknesses / open problems
229
230 1. **Quest ↔ dialogue coupling** — easy to leave dangling quest ids in responses. *Mitigation:* editor validation + delete warnings.
231 2. **No visual tile picker in v1 quest editor** — authors type coordinates (reuse live position readout idea from scripts). *Mitigation:* “Use current editor hover tile” button later.
232 3. **Repeatable quests / daily** — not in v1.
233 4. **Branching quest graphs** — v1 is linear steps only; branches via different quests or dialogue-only forks.
234 5. **Localization** — single language strings in authored data.
235 6. **Script parity** — quest inspect/advance verbs lag until play scripts need them.
236
237 ---
238
239 ## 9. World editor: unsaved chunk navigation & Save affordance
240
241 Independent of quests; ship with this plan’s commit.
242
243 ### 9.1 Dirty state
244
245 - Track a **baseline** snapshot when the selected chunk finishes loading / after successful save.
246 - Any paint, erase, open toggle, spawner add/edit/remove → **dirty**.
247 - Compare structurally (grounds, blocks, spawners, open), not by reference.
248
249 ### 9.2 Navigate away
250
251 Navigating to another chunk (N/S/E/W or any future jump) while dirty:
252
253 1. Modal: **You have unsaved changes on this chunk.**
254 - **Cancel** — stay.
255 - **Discard** — load target chunk, drop local draft.
256 - **Save** — save current chunk, then navigate (on save success).
257
258 ### 9.3 Save button
259
260 - **Disabled** when not dirty (or no draft loaded).
261 - **Enabled + blinking** (CSS pulse) when dirty — draws attention that a save is pending.
262 - After successful save: clear dirty, stop blink, disable until next edit.
263
264 ---
265
266 ## 10. Authority & safety
267
268 - Clients never decide quest completion or dialogue effect outcomes.
269 - Dialogue response payloads send `trigger` / `responseIndex`; server re-checks requirements.
270 - Quest defs and dialogue are admin-only edits.
271 - Condition checks use the same inventory/combat/interact pipelines as play.
272
273 ---
274
275 ## 11. Feasibility
276
277 **High** for linear quests + spawner dialogue + editor CRUD.
278 **Medium** for polished validation and revision/orphan UX.
279 Kill quotas and dialogue start/turn-in cover most MMO tutorial/fetch/kill loops without a full quest graph language.
280
281 **Stability:** good if events are explicit (kill, interact, dialogue enter) and conditions fail closed on bad refs. Risk concentrates in authoring mistakes (dangling ids) — editor validation is mandatory for a sturdy content pipeline.
1 # Quests & NPC dialogue (world editor)
2
3 **Status:** not implemented (design only)
4 **Related:** `docs/FEATURES.md` (Quests, Mob definitions), `docs/SCRIPTS.md` (parity reminder for future script verbs), server authority rules
5
6 Quests and NPC dialogue are **admin-authored content**. Authors create and edit them entirely in the **world editor**. Runtime evaluation is **server-authoritative**; clients only display dialogue UI and quest log snapshots.
7
8 This document is the product + data + editor spec for implementation.
9
10 ---
11
12 ## 1. Goals
13
14 - Author **quests** and **dialogue trees** as world-scoped assets (editors under **World settings**).
15 - Assign a dialogue to a **humanoid spawner** by reference (`dialogueId`); show assignment counts; support **unique** dialogues.
16 - Progress quests via **objectives** with shared multi-condition sets (including negations) and per-step **journal** text.
17 - Dialogue: line gifts, player-choice triggers, or **auto-branches**; track **dialogueHeard** per step; **interrupt on attack**.
18 - Player **Quests** UI: list + split detail (journal | step/objectives).
19 - Fail safe: broken references fail closed; editor validation catches unique/assignment rules.
20
21 ---
22
23 ## 2. Persistence & identity
24
25 | Asset | Storage | Apply model |
26 |-------|---------|-------------|
27 | **Quest definitions** | `world.sqlite` (revisioned with map) | Editor save → pending; **Apply now** → live |
28 | **Dialogue trees** | `world.sqlite` (revisioned with map) — **not** embedded in chunk JSON | Same as quests |
29 | **Spawner → dialogue link** | Chunk spawner `config.dialogueId` (string \| null) | Saved with the chunk |
30 | **Quest progress** | `state.sqlite` (`questState`) | Live |
31 | **Dialogue heard** | `state.sqlite` (`dialogueHeard`) | Live |
32
33 ### 2.1 IDs
34
35 - **Quest id:** stable slug (`deliver-tin-ore`). Prefer immutable after publish.
36 - **Quest step id:** stable within quest; conditions also use **1-based index** in `steps[]` (§4).
37 - **Dialogue id:** stable world-scoped id (`smith-intro`). Keys `dialogueHeard`, conditions, spawner assignment.
38 - **Dialogue step id / trigger id:** stable within that dialogue.
39 - **NPC reference in quests:** prefer **spawner id** + optional display-name hint — not transient entity ids.
40
41 ### 2.2 World settings: Quests & Dialogues editors
42
43 In the world editor chrome, place **Quests** and **Dialogues** as **separate buttons directly under the Settings button** (same control stack, not tabs inside the Settings modal).
44
45 | Button | Purpose |
46 |--------|---------|
47 | **Settings** | Existing world settings |
48 | **Quests** | CRUD all quest defs (id, title, steps, objectives, rewards, validation) |
49 | **Dialogues** | CRUD all dialogue trees (id, unique flag, steps, exits, validation) |
50
51 Both editors are **world-global** (not per-chunk). Saves go through the same admin auth + revision story as other authored world data.
52
53 **Dialogues list columns:** id, label/title, step count, **`unique`**, **assigned spawner count**, validation warnings.
54
55 **Delete dialogue:** warn if any spawner still references it; optionally block delete until unassigned.
56
57 ### 2.3 Spawner assignment
58
59 On a **humanoid / talkable** spawner:
60
61 - Dropdown: **Dialogue** → none, or pick from world dialogue list (show id + unique badge).
62 - Stores `config.dialogueId` only (no inline tree on the spawner).
63
64 **Assignment count:** Dialogues editor shows how many spawners currently reference each `dialogueId` (scan loaded/pending world chunks, or maintain an index on save). Click-through list of assignees (chunk + spawner label) is nice-to-have in v1.
65
66 ### 2.4 Unique dialogues
67
68 ```text
69 DialogueTree.unique: boolean // default false
70 ```
71
72 When `unique === true`:
73
74 1. **At most one spawner** in the world may have `config.dialogueId` equal to that id.
75 2. That spawner’s **`maxAlive` must be `1`** (editor clamps / blocks save otherwise; server normalize rejects Apply if violated).
76
77 Editor UX:
78
79 - Toggling **Unique** on while 2+ spawners assigned → block or offer “unassign others / cancel”.
80 - Assigning a unique dialogue to a second spawner → block with clear error.
81 - Setting `maxAlive > 1` on a spawner that holds a unique dialogue → block or force `maxAlive = 1`.
82
83 Non-unique dialogues may be shared by many spawners (and many alive NPCs); `dialogueHeard` is still keyed by `dialogueId`+`stepId` (shared script progress).
84
85 ---
86
87 ## 3. Quest definition shape
88
89 ```text
90 Quest {
91 questId: string
92 title: string
93 description: string // player-facing log blurb (in-universe)
94 steps: Step[] // ordered progression
95 rewards?: Reward[] // granted on final step complete
96 cancelable?: boolean // default false in v1
97 }
98 ```
99
100 ### 3.1 Steps & objectives
101
102 A quest advances one **step** at a time. Each step has one or more **objectives**. Each objective has a player-facing **text** and a **ConditionSet** (multiple conditions with optional negation). The step completes only when **all** objectives on that step are done (AND).
103
104 ```text
105 Step {
106 stepId: string
107 title: string
108 description: string
109 completionJournalText: string
110 objectives: Objective[] // ≥ 1; all must complete
111 onEnter?: Effect[]
112 onComplete?: Effect[]
113 }
114
115 Objective {
116 objectiveId: string
117 text: string // HUD / detail line
118 when: ConditionSet // objective complete when set passes (or event latch inside set)
119 }
120 ```
121
122 **Advancement:**
123
124 1. While a step is active, the server tracks which `objectiveId`s are satisfied.
125 2. When every objective on the step is complete → append journal line → `state` `n` → `n+1` or `completed` + rewards → show toast **“Quest objectives achieved”**. Clicking the toast opens the **Quests** detail modal on **that quest**.
126 3. Client: completed objectives struck through.
127
128 ### 3.2 Condition sets (quests + dialogue)
129
130 Shared in `shared/`. Evaluated **only on the server**.
131
132 ```text
133 ConditionSet {
134 all: ConditionClause[] // every clause must pass (AND); empty = always true
135 }
136
137 ConditionClause {
138 not?: boolean // default false; if true, invert the condition result
139 condition: Condition
140 }
141 ```
142
143 **Semantics:** `all` clauses AND-ed. “Has item X, but **not** quest completed Y” → two clauses, second with `not: true` (or use a dedicated negative kind — prefer **`not` on the clause** so every kind is invertible).
144
145 Used by:
146
147 - quest **objectives** (`when`)
148 - dialogue **triggers** (`when` — hide if fail)
149 - dialogue **auto-branches** (`when` — first branch whose set passes)
150
151 Editor: condition picker rows with a **NOT** toggle per row; add/remove rows.
152
153 #### Condition kinds
154
155 | Kind | Fields | Meaning |
156 |------|--------|---------|
157 | `hasItem` | `itemId`, `quantity` (≥ 1) | Bag (not vault) has ≥ N |
158 | `atTile` | `tileX`, `tileY` | Exact tile |
159 | `nearTile` | `tileX`, `tileY`, `range` (≥ 1) | Chebyshev ≤ range |
160 | `inRect` | `minTileX`, `minTileY`, `maxTileX`, `maxTileY` | Inclusive AABB |
161 | `atChunk` | `chunkX`, `chunkY` | Player chunk |
162 | `questState` | `questId`, `state` | Equals `not-started` \| `completed` \| number `n` |
163 | `questStepAtLeast` | `questId`, `step` (≥ 1) | Active index ≥ step **or** `completed` |
164 | `dialogueHeard` | `dialogueId`, `stepId` | Heard row exists |
165 | `dialogueTrigger` | `dialogueId`, `trigger` | **Latch:** player chose that trigger (quest objectives) |
166 | `hpAtLeast` | `amount` (≥ 0) | Current HP ≥ amount |
167 | `staminaAtLeast` | `amount` (≥ 0) | Current stamina ≥ amount |
168 | `hpPercentAtLeast` | `percent` (0–100) | currentHP / maxHP × 100 ≥ percent |
169 | `staminaPercentAtLeast` | `percent` (0–100) | currentStamina / maxStamina × 100 ≥ percent |
170 | `skillLevelAtLeast` | `skillId`, `level` (1–99) | `skillLevel(skills, skillId) ≥ level` |
171 | `killCount` | `mobTypeId` **or** `spawnerId`, `count` N | Kills while this quest step active |
172 | `interactBlock` | tile and/or `blockTypeId` | Successful interact (once per quest step) |
173
174 **Notes:**
175
176 - Prefer **`not` + `hasItem`** over a separate `lacksItem` kind (legacy alias ok). Same for `dialogueNotHeard` → `not` + `dialogueHeard`.
177 - Thresholds use **≥** (“above or equal”); document in editor labels as “at least”.
178 - Max HP / max stamina = same formulas the play sim already uses for the character.
179 - Unknown ids → clause **fails closed** (raw condition false; with `not`, that becomes true — authors should avoid dangling ids; validation warns).
180 - Kill attribution = existing combat kill credit.
181
182 ### 3.3 Rewards & effects (v1)
183
184 | Kind | Fields |
185 |------|--------|
186 | `giveItem` | `itemId`, `quantity` |
187 | `giveXp` | `skillId`, `amount` |
188 | `takeItem` | `itemId`, `quantity` |
189 | `startQuest` | `questId` |
190
191 Sources: quest `onEnter` / `onComplete`, dialogue **line**, **trigger**, **branch**.
192 Full bag → vault via carrier pigeon.
193
194 ---
195
196 ## 4. Character quest state & journal
197
198 ### 4.0 Quest state
199
200 ```text
201 QuestStateValue = "not-started" | number | "completed"
202 // number = 1-based index of current incomplete step
203 ```
204
205 ```text
206 CharacterQuest {
207 questId: string
208 state: QuestStateValue
209 completedObjectiveIds: string[]
210 counters: { [key: string]: number }
211 startedAt?, completedAt?
212 }
213 ```
214
215 Missing row ⇒ `not-started`. Conditions read `state` only; counters/objectives are runtime detail for UI + event objectives.
216
217 ### 4.0b Dialogue heard
218
219 ```text
220 dialogueHeard (characterId, dialogueId, stepId, heardAt)
221 UNIQUE (characterId, dialogueId, stepId)
222 ```
223
224 Insert on step **enter** (first time). Permanent in v1. Gate repeat gifts with `when` sets (`not` + `dialogueHeard`, `not` + `hasItem`, etc.).
225
226 ### 4.0c Journal
227
228 ```text
229 QuestJournalEntry { questId, stepId, text, writtenAt }
230 ```
231
232 Append-only; text frozen at write time.
233
234 ---
235
236 ## 4.1 Player UI — Quests
237
238 - **Quests** HUD control → list modal: active (`state` number) first, **completed** at bottom; hide `not-started`.
239 - Detail modal: left journal (this quest), right step description + objectives (strikethrough when done).
240 - **Step-complete toast:** text **“Quest objectives achieved”**. Click → open quest detail for the quest that just advanced (same modal stack as the Quests button).
241
242 ---
243
244 ## 5. Dialogue (world asset + spawner link)
245
246 ### 5.1 Shape
247
248 ```text
249 DialogueTree {
250 dialogueId: string
251 label: string // editor list title
252 unique: boolean // default false; see §2.4
253 steps: DialogueStep[]
254 entryStepId?: string
255 }
256
257 DialogueStep {
258 stepId: string
259 label: string
260 lines: DialogueLine[]
261 exit:
262 | { kind: "triggers", triggers: DialogueTrigger[] }
263 | { kind: "branches", branches: DialogueBranch[] }
264 | { kind: "end" }
265 }
266
267 DialogueLine {
268 speaker: "npc" | "player"
269 text: string
270 effects?: Effect[]
271 }
272
273 DialogueTrigger {
274 trigger: string
275 label: string // editor
276 text: string // player button
277 nextStepId: string | null // null → end
278 when?: ConditionSet // hide if fail; omit = always show
279 effects?: Effect[]
280 }
281
282 DialogueBranch {
283 label?: string
284 when: ConditionSet // empty all[] = always
285 nextStepId: string | null
286 effects?: Effect[]
287 }
288 ```
289
290 **End rules:** null `nextStepId`, `exit.kind: "end"`, no matching branch, or no visible triggers → **close dialogue**.
291
292 ### 5.2 Runtime
293
294 1. Talk to NPC whose spawner has `dialogueId` → load world DialogueTree → open `entryStepId`.
295 2. Enter step → insert `dialogueHeard` if new → play lines (apply line effects).
296 3. Triggers / branches / end as authored.
297 4. **Interrupt:** if the NPC is **attacked** (takes a hostile hit / combat engagement against it) while a player has this dialogue open → **immediately close** that dialogue session (no further lines, choices, or pending line effects). Re-talk required. Does not roll back already-applied effects or heard rows.
298
299 ### 5.3 Editor (Dialogues panel)
300
301 - List + inspector (graph canvas = v1.1).
302 - Per dialogue: id, label, **unique**, assignment count, steps, exit modes, shared condition-set picker (with NOT).
303 - Validation: unique rules (§2.4), missing refs, empty texts, unreachable steps.
304
305 ### 5.4 Spawner modal
306
307 Humanoid: **Dialogue** dropdown bound to world dialogues (not an inline tree editor). Link to “Open in Dialogues editor” optional.
308
309 ---
310
311 ## 6. How quests start
312
313 `startQuest` effect → `not-started` → `1`. Block if already numeric or `completed` (v1 no repeats).
314
315 ---
316
317 ## 7. Implementation plan (phased)
318
319 1. Shared `Condition` / `ConditionSet` / `Effect` in `shared/`.
320 2. World DB: quest defs + dialogue trees; state: `questState`, `dialogueHeard`, journal.
321 3. World settings **Quests** + **Dialogues** editors; spawner `dialogueId` + unique/maxAlive validation; assignment counts.
322 4. Editor unsaved-chunk guard (§9) — may already ship.
323 5. Runtime dialogue + combat interrupt; line/trigger/branch effects.
324 6. Quest engine + Quests HUD.
325 7. Apply revision + tests (conditions+NOT, unique, interrupt, heard, journal).
326
327 ---
328
329 ## 8. Edge cases (resolved)
330
331 | Topic | Decision |
332 |-------|----------|
333 | Unique + 2 assignees | Editor/server reject until ≤ 1 |
334 | Unique + maxAlive ≠ 1 | Reject / clamp to 1 |
335 | Mark unique while assigned elsewhere | Must unassign others first |
336 | Shared (non-unique) dialogue | Many spawners OK; heard shared by dialogueId |
337 | Spawner dialogueId missing tree | Talk no-ops / error log; fail closed |
338 | NPC attacked mid-dialogue | Session closes immediately |
339 | Player walks away / disconnect | Close session (no progress loss beyond already applied) |
340 | `not` + unknown id | Raw false → NOT true — validation must warn on unknown ids |
341 | Thresholds | All “at least” (≥) |
342 | Parallel quests | Yes; soft cap ~20 active |
343 | One step per quest | Yes (single numeric state) |
344 | Apply mid-dialogue | Close sessions |
345
346 ### 8.1 Open product choices (see §12)
347
348 Small list of remaining decisions before / during implementation — none are architectural blockers if defaults in §12 are accepted.
349
350 ---
351
352 ## 9. World editor: unsaved chunk navigation & Save affordance
353
354 Independent of quests; ship with this plan’s commit.
355
356 ### 9.1 Dirty state
357
358 - Baseline when chunk loads / after save; paint/spawner edits → dirty; structural compare.
359
360 ### 9.2 Navigate away
361
362 Modal: Cancel / Discard / Save then navigate.
363
364 ### 9.3 Save button
365
366 Disabled when clean; enabled + blinking when dirty.
367
368 ---
369
370 ## 10. Authority & safety
371
372 - Client never decides conditions, heard, quest state, or effects.
373 - Choose payload: `dialogueId`, `stepId`, `trigger`; server re-evaluates `when`.
374 - Branches and interrupts are server-side.
375 - Unique / maxAlive enforced on save and Apply.
376
377 ---
378
379 ## 11. Feasibility
380
381 **High–medium.** World-scoped dialogue assets + assignment is cleaner than per-spawner trees. ConditionSet + `not` covers “A but not B” without exploding kind count. Combat interrupt is a small session hook.
382
383 Hardest: event wiring for quest objectives + revision/orphan UX. Graph canvas still v1.1.
384
385 ---
386
387 ## 12. Defaults if unspecified (implementation may proceed)
388
389 Accept these unless overridden:
390
391 1. **Condition polarity:** per-clause `not?: boolean` inside `ConditionSet.all` (no separate OR groups in v1; use multiple ordered dialogue branches for OR).
392 2. **Thresholds:** all ≥ (“at least”).
393 3. **Interrupt:** any hostile damage/engagement **on the NPC** closes dialogue for whoever was talking to it (not only if the talker is the attacker).
394 4. **Unique conflict:** editor **blocks** the illegal save (does not auto-unassign silently).
395 5. **Assignment count:** computed from pending/applied chunk spawners when opening Dialogues editor (accurate enough for v1).
396 6. **`lacksItem` / `dialogueNotHeard`:** not separate kinds; use `not` + positive kind (editor may offer presets).
397 7. **Objectives:** one objective completes when its entire `ConditionSet` is true (event kinds latch once true).
398 8. **Editors placement:** **Quests** and **Dialogues** buttons stacked **under** the Settings button (separate modals, not Settings tabs).
399 9. **Step-complete toast:** “Quest objectives achieved”; click opens that quest’s detail modal.
400
401 **Not blocking for v1:** graph canvas, script verbs, repeatable quests, localization, visual tile picker.
@@ -1,281 +1,401 @@
1# Quests & NPC dialogue (world editor)
1# Quests & NPC dialogue (world editor)
2
2
3**Status:** not implemented (design only)
3**Status:** not implemented (design only)
4**Related:** `docs/FEATURES.md` (Quests, Mob definitions), `docs/SCRIPTS.md` (parity reminder for future script verbs), server authority rules
4**Related:** `docs/FEATURES.md` (Quests, Mob definitions), `docs/SCRIPTS.md` (parity reminder for future script verbs), server authority rules
5
5
6Quests and NPC dialogue are **admin-authored content**. Authors create and edit them entirely in the **world editor**. Runtime evaluation is **server-authoritative**; clients only display dialogue UI and quest log snapshots.
6Quests and NPC dialogue are **admin-authored content**. Authors create and edit them entirely in the **world editor**. Runtime evaluation is **server-authoritative**; clients only display dialogue UI and quest log snapshots.
7
7
8This document is the product + data + editor spec for implementation.
8This document is the product + data + editor spec for implementation.
9
9
10---
10---
11
11
12## 1. Goals
12## 1. Goals
13
13
14- Author quests without code changes (editor **Quests** menu).
14- Author **quests** and **dialogue trees** as world-scoped assets (editors under **World settings**).
15- Author full NPC dialogue trees on the **spawner** that owns that NPC.
15- Assign a dialogue to a **humanoid spawner** by reference (`dialogueId`); show assignment counts; support **unique** dialogues.
16- Progress quests via clear, checkable **conditions** (inventory, place, dialogue, kills, block interact).
16- Progress quests via **objectives** with shared multi-condition sets (including negations) and per-step **journal** text.
17- Keep data stable, reviewable, and Apply-revision friendly (same map-revision pipeline as chunks where content is world-scoped).
17- Dialogue: line gifts, player-choice triggers, or **auto-branches**; track **dialogueHeard** per step; **interrupt on attack**.
18- Fail safe: broken references do not soft-lock players forever without admin tools / clear errors.
18- Player **Quests** UI: list + split detail (journal | step/objectives).
19
19- Fail safe: broken references fail closed; editor validation catches unique/assignment rules.
20---
20
21
21---
22## 2. Persistence & identity
22
23
23## 2. Persistence & identity
24| Asset | Storage | Apply model |
24
25|-------|---------|-------------|
25| Asset | Storage | Apply model |
26| **Quest definitions** | `world.sqlite` (authored, revisioned with map / pending revision — same spirit as chunks) | Editor save → pending; **Apply now** loads into live sim |
26|-------|---------|-------------|
27| **Dialogue trees** | On each **spawner config** inside chunk data (`config.dialogue[]`) | Saved with the chunk |
27| **Quest definitions** | `world.sqlite` (revisioned with map) | Editor save → pending; **Apply now** → live |
28| **Quest progress** | `state.sqlite` per character | Live; never in world revision |
28| **Dialogue trees** | `world.sqlite` (revisioned with map) — **not** embedded in chunk JSON | Same as quests |
29
29| **Spawner → dialogue link** | Chunk spawner `config.dialogueId` (string \| null) | Saved with the chunk |
30### 2.1 IDs
30| **Quest progress** | `state.sqlite` (`questState`) | Live |
31
31| **Dialogue heard** | `state.sqlite` (`dialogueHeard`) | Live |
32- **Quest id:** stable string slug, editor-assigned, unique (`deliver-tin-ore`, `guard-rats-1`). Immutable after first publish preferred; rename is a new id + migration warning.
32
33- **Step id:** stable string within a quest (`step-gather`, `step-return`).
33### 2.1 IDs
34- **Dialogue trigger:** stable string within a spawner’s dialogue set (`greeting`, `quest-offer`, `quest-turnin`).
34
35- **NPC reference in quests:** prefer **spawner id** (`chunkX:chunkY:index` or authored `spawnerId`) + optional display-name hint — not transient entity ids.
35- **Quest id:** stable slug (`deliver-tin-ore`). Prefer immutable after publish.
36
36- **Quest step id:** stable within quest; conditions also use **1-based index** in `steps[]` (§4).
37### 2.2 Quests menu (editor)
37- **Dialogue id:** stable world-scoped id (`smith-intro`). Keys `dialogueHeard`, conditions, spawner assignment.
38
38- **Dialogue step id / trigger id:** stable within that dialogue.
39Top-level editor control **Quests** (alongside Settings / palette):
39- **NPC reference in quests:** prefer **spawner id** + optional display-name hint — not transient entity ids.
40
40
41- List all quests (id, title, step count, validation warnings).
41### 2.2 World settings: Quests & Dialogues editors
42- **New** / **Edit** / **Duplicate** / **Delete** (delete warns if dialogue responses reference the quest).
42
43- Editor panel is world-global (not per-chunk), but saves go through the same admin auth + revision story as other authored world data.
43In the world editor chrome, place **Quests** and **Dialogues** as **separate buttons directly under the Settings button** (same control stack, not tabs inside the Settings modal).
44
44
45---
45| Button | Purpose |
46
46|--------|---------|
47## 3. Quest definition shape
47| **Settings** | Existing world settings |
48
48| **Quests** | CRUD all quest defs (id, title, steps, objectives, rewards, validation) |
49```text
49| **Dialogues** | CRUD all dialogue trees (id, unique flag, steps, exits, validation) |
50Quest {
50
51 questId: string
51Both editors are **world-global** (not per-chunk). Saves go through the same admin auth + revision story as other authored world data.
52 title: string
52
53 description: string // player-facing log blurb (in-universe)
53**Dialogues list columns:** id, label/title, step count, **`unique`**, **assigned spawner count**, validation warnings.
54 steps: Step[] // ordered progression
54
55 rewards?: Reward[] // granted on final step complete
55**Delete dialogue:** warn if any spawner still references it; optionally block delete until unassigned.
56 cancelable?: boolean // default false in v1
56
57}
57### 2.3 Spawner assignment
58```
58
59
59On a **humanoid / talkable** spawner:
60### 3.1 Steps
60
61
61- Dropdown: **Dialogue** → none, or pick from world dialogue list (show id + unique badge).
62Each step is completed when **all** of its `require` conditions are true (AND). Optional `anyOf` groups later; v1 stays AND-only for clarity.
62- Stores `config.dialogueId` only (no inline tree on the spawner).
63
63
64```text
64**Assignment count:** Dialogues editor shows how many spawners currently reference each `dialogueId` (scan loaded/pending world chunks, or maintain an index on save). Click-through list of assignees (chunk + spawner label) is nice-to-have in v1.
65Step {
65
66 stepId: string
66### 2.4 Unique dialogues
67 title: string // short log line
67
68 hint?: string // optional guidance
68```text
69 require: Condition[] // all must pass
69DialogueTree.unique: boolean // default false
70 onEnter?: Effect[] // optional (toast, flag) — keep minimal in v1
70```
71 onComplete?: Effect[] // optional mid-quest grants; prefer final rewards
71
72}
72When `unique === true`:
73```
73
74
741. **At most one spawner** in the world may have `config.dialogueId` equal to that id.
75Advancement: when the active step’s conditions are satisfied, the server marks it complete and activates the next step (or completes the quest).
752. That spawner’s **`maxAlive` must be `1`** (editor clamps / blocks save otherwise; server normalize rejects Apply if violated).
76
76
77### 3.2 Conditions (v1)
77Editor UX:
78
78
79| Kind | Fields | Meaning |
79- Toggling **Unique** on while 2+ spawners assigned → block or offer “unassign others / cancel”.
80|------|--------|---------|
80- Assigning a unique dialogue to a second spawner → block with clear error.
81| `hasItem` | `itemId`, `quantity` (≥ 1) | Bag (not vault) contains at least N |
81- Setting `maxAlive > 1` on a spawner that holds a unique dialogue → block or force `maxAlive = 1`.
82| `atTile` | `tileX`, `tileY` (optional `radius` Chebyshev, default 0) | Player stands on/near tile |
82
83| `atChunk` | `chunkX`, `chunkY` | Player’s chunk equals (coarse place) |
83Non-unique dialogues may be shared by many spawners (and many alive NPCs); `dialogueHeard` is still keyed by `dialogueId`+`stepId` (shared script progress).
84| `dialogueTrigger` | `spawnerId`, `trigger` | Player fired that dialogue trigger on an NPC from that spawner (see §5) |
84
85| `killMob` | `mobTypeId` **or** `spawnerId`, optional `displayName` | **Event:** player deals killing blow to matching mob (advances a counter or one-shot flag on the step) |
85---
86| `killCount` | `mobTypeId` **or** `spawnerId`, `count` N | Player has killed N matching mobs **while this step is active** (quota) |
86
87| `interactBlock` | `tileX`, `tileY` **or** `blockTypeId` + optional tile, `action?` | Player successfully interacts with that block (LMB/use as defined for the block) |
87## 3. Quest definition shape
88
88
89**Notes:**
89```text
90
90Quest {
91- `killMob` vs `killCount`: one-shot event vs quota. Prefer `killCount` with `count: 1` instead of a separate one-shot if it simplifies the engine — editor can still show “kill once” UX that writes `killCount: 1`.
91 questId: string
92- Kill attribution: **last hitting player** / engaged killer consistent with existing combat kill credit (same as bounty).
92 title: string
93- `hasItem` does **not** consume items unless an **effect** or turn-in dialogue action says so.
93 description: string // player-facing log blurb (in-universe)
94- `interactBlock` must be a real completed interact (open bank alone does not count unless the quest names that block and the interact handler emits the quest event).
94 steps: Step[] // ordered progression
95
95 rewards?: Reward[] // granted on final step complete
96### 3.3 Rewards & effects (v1)
96 cancelable?: boolean // default false in v1
97
97}
98| Kind | Fields |
98```
99|------|--------|
99
100| `giveItem` | `itemId`, `quantity` |
100### 3.1 Steps & objectives
101| `giveXp` | `skillId`, `amount` |
101
102| `takeItem` | `itemId`, `quantity` (turn-in) |
102A quest advances one **step** at a time. Each step has one or more **objectives**. Each objective has a player-facing **text** and a **ConditionSet** (multiple conditions with optional negation). The step completes only when **all** objectives on that step are done (AND).
103| `startQuest` | `questId` (from dialogue) |
103
104| `setDialogueFlag` | optional local flag — defer if unused |
104```text
105
105Step {
106Full bag on `giveItem`: overflow to vault by **carrier pigeon** (existing FEATURES note).
106 stepId: string
107
107 title: string
108---
108 description: string
109
109 completionJournalText: string
110## 4. Character quest state
110 objectives: Objective[] // ≥ 1; all must complete
111
111 onEnter?: Effect[]
112```text
112 onComplete?: Effect[]
113CharacterQuest {
113}
114 questId
114
115 status: inactive | active | completed | failed // failed unused in v1 unless cancel
115Objective {
116 activeStepId: string | null
116 objectiveId: string
117 completedStepIds: string[]
117 text: string // HUD / detail line
118 counters: { [key: string]: number } // e.g. kill quotas for current step
118 when: ConditionSet // objective complete when set passes (or event latch inside set)
119 startedAt, completedAt
119}
120}
120```
121```
121
122
122**Advancement:**
123- Persist in `state.sqlite`.
123
124- Replicate a compact **quest log** snapshot to the client (title, step title/hint, progress counts).
1241. While a step is active, the server tracks which `objectiveId`s are satisfied.
125- Server re-evaluates conditions on relevant events (inventory change, move, kill, interact, dialogue) — not on a tight poll.
1252. When every objective on the step is complete → append journal line → `state` `n` → `n+1` or `completed` + rewards → show toast **“Quest objectives achieved”**. Clicking the toast opens the **Quests** detail modal on **that quest**.
126
1263. Client: completed objectives struck through.
127---
127
128
128### 3.2 Condition sets (quests + dialogue)
129## 5. Dialogue on spawners
129
130
130Shared in `shared/`. Evaluated **only on the server**.
131Dialogue is authored **per spawner** (humanoid / talkable NPC), not in code mob defs (defs may keep empty `dialogue: []`).
131
132
132```text
133### 5.1 Shape
133ConditionSet {
134
134 all: ConditionClause[] // every clause must pass (AND); empty = always true
135```text
135}
136DialogueNode {
136
137 trigger: string
137ConditionClause {
138 lines: { speaker: "npc" | "player", text: string }[]
138 not?: boolean // default false; if true, invert the condition result
139 responses: DialogueResponse[]
139 condition: Condition
140}
140}
141
141```
142DialogueResponse {
142
143 label: string // button text
143**Semantics:** `all` clauses AND-ed. “Has item X, but **not** quest completed Y” → two clauses, second with `not: true` (or use a dedicated negative kind — prefer **`not` on the clause** so every kind is invertible).
144 nextTrigger: string | null // follow-up node trigger; null = end
144
145 require?: DialogueRequirement[] // all must pass to show/enable
145Used by:
146 effects?: Effect[] // on choose: startQuest, takeItem, …
146
147}
147- quest **objectives** (`when`)
148```
148- dialogue **triggers** (`when` — hide if fail)
149
149- dialogue **auto-branches** (`when` — first branch whose set passes)
150### 5.2 Requirements on responses
150
151
151Editor: condition picker rows with a **NOT** toggle per row; add/remove rows.
152| Kind | Fields |
152
153|------|--------|
153#### Condition kinds
154| `hasItem` | `itemId`, `quantity` |
154
155| `questActive` | `questId` |
155| Kind | Fields | Meaning |
156| `questCompleted` | `questId` |
156|------|--------|---------|
157| `questStepActive` | `questId`, `stepId` |
157| `hasItem` | `itemId`, `quantity` (≥ 1) | Bag (not vault) has ≥ N |
158| `questStepCompleted` | `questId`, `stepId` |
158| `atTile` | `tileX`, `tileY` | Exact tile |
159
159| `nearTile` | `tileX`, `tileY`, `range` (≥ 1) | Chebyshev ≤ range |
160Hidden vs disabled: **hide** responses that fail requirements (cleaner UX). Optional later: show disabled with reason.
160| `inRect` | `minTileX`, `minTileY`, `maxTileX`, `maxTileY` | Inclusive AABB |
161
161| `atChunk` | `chunkX`, `chunkY` | Player chunk |
162### 5.3 Runtime
162| `questState` | `questId`, `state` | Equals `not-started` \| `completed` \| number `n` |
163
163| `questStepAtLeast` | `questId`, `step` (≥ 1) | Active index ≥ step **or** `completed` |
1641. Player talks to NPC (existing talkable interact).
164| `dialogueHeard` | `dialogueId`, `stepId` | Heard row exists |
1652. Server opens dialogue at default trigger (`greeting` or first node) — or a quest-forced trigger if an effect set one.
165| `dialogueTrigger` | `dialogueId`, `trigger` | **Latch:** player chose that trigger (quest objectives) |
1663. Client shows lines in order (npc/player attribution for layout).
166| `hpAtLeast` | `amount` (≥ 0) | Current HP ≥ amount |
1674. Player picks a response → server validates requirements + effects → may emit `dialogueTrigger` quest event with `{ spawnerId, trigger: chosen.nextTrigger or node.trigger }` as designed.
167| `staminaAtLeast` | `amount` (≥ 0) | Current stamina ≥ amount |
1685. **Quest condition `dialogueTrigger`:** fires when the player **selects a response that leads to** that trigger, or when a node with that trigger is **entered** — pick **one** rule and stick to it.
168| `hpPercentAtLeast` | `percent` (0–100) | currentHP / maxHP × 100 ≥ percent |
169
169| `staminaPercentAtLeast` | `percent` (0–100) | currentStamina / maxStamina × 100 ≥ percent |
170**Resolved default:** condition matches when a dialogue **node with that `trigger` begins** (lines start showing). Starting a quest offer node counts; merely hovering a response does not.
170| `skillLevelAtLeast` | `skillId`, `level` (1–99) | `skillLevel(skills, skillId) ≥ level` |
171
171| `killCount` | `mobTypeId` **or** `spawnerId`, `count` N | Kills while this quest step active |
172### 5.4 Editor UI (spawner modal)
172| `interactBlock` | tile and/or `blockTypeId` | Successful interact (once per quest step) |
173
173
174Under humanoid fields: **Dialogue** section
174**Notes:**
175
175
176- List nodes by trigger; add/remove/reorder.
176- Prefer **`not` + `hasItem`** over a separate `lacksItem` kind (legacy alias ok). Same for `dialogueNotHeard` → `not` + `dialogueHeard`.
177- Per node: trigger id, lines editor (speaker toggle + text), responses (label, next trigger dropdown, requirement rows, optional effects).
177- Thresholds use **≥** (“above or equal”); document in editor labels as “at least”.
178- Validation: orphan triggers, missing nextTrigger targets, empty lines, unknown quest ids in requirements.
178- Max HP / max stamina = same formulas the play sim already uses for the character.
179
179- Unknown ids → clause **fails closed** (raw condition false; with `not`, that becomes true — authors should avoid dangling ids; validation warns).
180Central Exchange staff share one spawner config’s dialogue (same as shared equipment) unless we later split per clerk — **v1: shared tree**.
180- Kill attribution = existing combat kill credit.
181
181
182---
182### 3.3 Rewards & effects (v1)
183
183
184## 6. How quests start
184| Kind | Fields |
185
185|------|--------|
186Primary: dialogue response effect `startQuest`.
186| `giveItem` | `itemId`, `quantity` |
187Secondary (optional v1.1): auto-start on enter tile / pickup — out of scope until needed.
187| `giveXp` | `skillId`, `amount` |
188
188| `takeItem` | `itemId`, `quantity` |
189Cannot start if already active or completed (unless quest allows repeat — **v1: no repeats**).
189| `startQuest` | `questId` |
190
190
191---
191Sources: quest `onEnter` / `onComplete`, dialogue **line**, **trigger**, **branch**.
192
192Full bag → vault via carrier pigeon.
193## 7. Implementation plan (phased)
193
194
194---
1951. **Data model + world DB tables** for quest defs; chunk spawner `dialogue[]` normalize/save.
195
1962. **Editor Quests menu** CRUD + validation UI (no runtime).
196## 4. Character quest state & journal
1973. **Editor spawner dialogue** UI + save on chunk.
197
1984. **Editor UX** unsaved-chunk guard (§9) — can ship earlier independently.
198### 4.0 Quest state
1995. **Runtime dialogue** — talk → server nodes → client panel; requirements; effects `startQuest` / `takeItem` / `giveItem`.
199
2006. **Runtime quest engine** — state, condition listeners, step advance, rewards, quest log UI.
200```text
2017. **Apply revision** reloads quest defs; in-flight character progress keeps quest ids (orphan progress if quest deleted — §8).
201QuestStateValue = "not-started" | number | "completed"
2028. **Tests** for normalize, dialogue requirements, kill quotas, turn-in, overflow pigeon.
202// number = 1-based index of current incomplete step
2039. **Script verbs** (later): `if quest active "…"`, etc., in same commit as needed — see SCRIPTS.md parity rule.
203```
204
204
205---
205```text
206
206CharacterQuest {
207## 8. Edge cases (resolved in plan)
207 questId: string
208
208 state: QuestStateValue
209| Topic | Decision |
209 completedObjectiveIds: string[]
210|-------|----------|
210 counters: { [key: string]: number }
211| Quest deleted while players active | Progress remains `orphaned`; log shows “Quest unavailable”; cannot advance; admin may clear |
211 startedAt?, completedAt?
212| Spawner id renamed | Dialogue/quest refs break → editor validation warning; runtime condition fails closed |
212}
213| Multiple NPCs same dialogue trigger string | Triggers are **per spawnerId**; no global trigger namespace |
213```
214| `hasItem` while item in vault | False — bag only |
214
215| Kill credit for `killCount` | Only kills while step active; deaths by unrelated players don’t count for this character |
215Missing row ⇒ `not-started`. Conditions read `state` only; counters/objectives are runtime detail for UI + event objectives.
216| Player dies mid-quest | Progress kept (no fail-on-death in v1) |
216
217| Aggressive NPC + dialogue | Talkable only when not in combat / or always if talkable flag — **defer:** talkable if not currently targeting the player |
217### 4.0b Dialogue heard
218| Turn-in without removing items | Use explicit `takeItem` effect on the turn-in response or step `onComplete` |
218
219| Concurrent steps | **No** — one active step per quest |
219```text
220| Parallel quests | **Yes** — multiple active quests per character; soft cap e.g. **20** |
220dialogueHeard (characterId, dialogueId, stepId, heardAt)
221| `atTile` with multiplayer crowding | Standing on tile is enough |
221UNIQUE (characterId, dialogueId, stepId)
222| Interact same block repeatedly | `interactBlock` sets a once-flag per step unless condition is re-checkable each interact — **once per step** |
222```
223| Dialogue effects vs quest step conditions | Both allowed; prefer turn-in items via dialogue effects so the NPC “takes” them narratively |
223
224| Chunk not loaded | Kill/interact on unloaded sim: only live simulating entities emit events (normal) |
224Insert on step **enter** (first time). Permanent in v1. Gate repeat gifts with `when` sets (`not` + `dialogueHeard`, `not` + `hasItem`, etc.).
225| Apply mid-dialogue | Close dialogue on revision apply; reopen requires talk again |
225
226| Non-humanoid dialogue | Only `talkable` / humanoid spawners show dialogue editor |
226### 4.0c Journal
227
227
228### 8.1 Known weaknesses / open problems
228```text
229
229QuestJournalEntry { questId, stepId, text, writtenAt }
2301. **Quest ↔ dialogue coupling** — easy to leave dangling quest ids in responses. *Mitigation:* editor validation + delete warnings.
230```
2312. **No visual tile picker in v1 quest editor** — authors type coordinates (reuse live position readout idea from scripts). *Mitigation:* “Use current editor hover tile” button later.
231
2323. **Repeatable quests / daily** — not in v1.
232Append-only; text frozen at write time.
2334. **Branching quest graphs** — v1 is linear steps only; branches via different quests or dialogue-only forks.
233
2345. **Localization** — single language strings in authored data.
234---
2356. **Script parity** — quest inspect/advance verbs lag until play scripts need them.
235
236
236## 4.1 Player UI — Quests
237---
237
238
238- **Quests** HUD control → list modal: active (`state` number) first, **completed** at bottom; hide `not-started`.
239## 9. World editor: unsaved chunk navigation & Save affordance
239- Detail modal: left journal (this quest), right step description + objectives (strikethrough when done).
240
240- **Step-complete toast:** text **“Quest objectives achieved”**. Click → open quest detail for the quest that just advanced (same modal stack as the Quests button).
241Independent of quests; ship with this plan’s commit.
241
242
242---
243### 9.1 Dirty state
243
244
244## 5. Dialogue (world asset + spawner link)
245- Track a **baseline** snapshot when the selected chunk finishes loading / after successful save.
245
246- Any paint, erase, open toggle, spawner add/edit/remove → **dirty**.
246### 5.1 Shape
247- Compare structurally (grounds, blocks, spawners, open), not by reference.
247
248
248```text
249### 9.2 Navigate away
249DialogueTree {
250
250 dialogueId: string
251Navigating to another chunk (N/S/E/W or any future jump) while dirty:
251 label: string // editor list title
252
252 unique: boolean // default false; see §2.4
2531. Modal: **You have unsaved changes on this chunk.**
253 steps: DialogueStep[]
254 - **Cancel** — stay.
254 entryStepId?: string
255 - **Discard** — load target chunk, drop local draft.
255}
256 - **Save** — save current chunk, then navigate (on save success).
256
257
257DialogueStep {
258### 9.3 Save button
258 stepId: string
259
259 label: string
260- **Disabled** when not dirty (or no draft loaded).
260 lines: DialogueLine[]
261- **Enabled + blinking** (CSS pulse) when dirty — draws attention that a save is pending.
261 exit:
262- After successful save: clear dirty, stop blink, disable until next edit.
262 | { kind: "triggers", triggers: DialogueTrigger[] }
263
263 | { kind: "branches", branches: DialogueBranch[] }
264---
264 | { kind: "end" }
265
265}
266## 10. Authority & safety
266
267
267DialogueLine {
268- Clients never decide quest completion or dialogue effect outcomes.
268 speaker: "npc" | "player"
269- Dialogue response payloads send `trigger` / `responseIndex`; server re-checks requirements.
269 text: string
270- Quest defs and dialogue are admin-only edits.
270 effects?: Effect[]
271- Condition checks use the same inventory/combat/interact pipelines as play.
271}
272
272
273---
273DialogueTrigger {
274
274 trigger: string
275## 11. Feasibility
275 label: string // editor
276
276 text: string // player button
277**High** for linear quests + spawner dialogue + editor CRUD.
277 nextStepId: string | null // null → end
278**Medium** for polished validation and revision/orphan UX.
278 when?: ConditionSet // hide if fail; omit = always show
279Kill quotas and dialogue start/turn-in cover most MMO tutorial/fetch/kill loops without a full quest graph language.
279 effects?: Effect[]
280
280}
281**Stability:** good if events are explicit (kill, interact, dialogue enter) and conditions fail closed on bad refs. Risk concentrates in authoring mistakes (dangling ids) — editor validation is mandatory for a sturdy content pipeline.
281
282DialogueBranch {
283 label?: string
284 when: ConditionSet // empty all[] = always
285 nextStepId: string | null
286 effects?: Effect[]
287}
288```
289
290**End rules:** null `nextStepId`, `exit.kind: "end"`, no matching branch, or no visible triggers → **close dialogue**.
291
292### 5.2 Runtime
293
2941. Talk to NPC whose spawner has `dialogueId` → load world DialogueTree → open `entryStepId`.
2952. Enter step → insert `dialogueHeard` if new → play lines (apply line effects).
2963. Triggers / branches / end as authored.
2974. **Interrupt:** if the NPC is **attacked** (takes a hostile hit / combat engagement against it) while a player has this dialogue open → **immediately close** that dialogue session (no further lines, choices, or pending line effects). Re-talk required. Does not roll back already-applied effects or heard rows.
298
299### 5.3 Editor (Dialogues panel)
300
301- List + inspector (graph canvas = v1.1).
302- Per dialogue: id, label, **unique**, assignment count, steps, exit modes, shared condition-set picker (with NOT).
303- Validation: unique rules (§2.4), missing refs, empty texts, unreachable steps.
304
305### 5.4 Spawner modal
306
307Humanoid: **Dialogue** dropdown bound to world dialogues (not an inline tree editor). Link to “Open in Dialogues editor” optional.
308
309---
310
311## 6. How quests start
312
313`startQuest` effect → `not-started` → `1`. Block if already numeric or `completed` (v1 no repeats).
314
315---
316
317## 7. Implementation plan (phased)
318
3191. Shared `Condition` / `ConditionSet` / `Effect` in `shared/`.
3202. World DB: quest defs + dialogue trees; state: `questState`, `dialogueHeard`, journal.
3213. World settings **Quests** + **Dialogues** editors; spawner `dialogueId` + unique/maxAlive validation; assignment counts.
3224. Editor unsaved-chunk guard (§9) — may already ship.
3235. Runtime dialogue + combat interrupt; line/trigger/branch effects.
3246. Quest engine + Quests HUD.
3257. Apply revision + tests (conditions+NOT, unique, interrupt, heard, journal).
326
327---
328
329## 8. Edge cases (resolved)
330
331| Topic | Decision |
332|-------|----------|
333| Unique + 2 assignees | Editor/server reject until ≤ 1 |
334| Unique + maxAlive ≠ 1 | Reject / clamp to 1 |
335| Mark unique while assigned elsewhere | Must unassign others first |
336| Shared (non-unique) dialogue | Many spawners OK; heard shared by dialogueId |
337| Spawner dialogueId missing tree | Talk no-ops / error log; fail closed |
338| NPC attacked mid-dialogue | Session closes immediately |
339| Player walks away / disconnect | Close session (no progress loss beyond already applied) |
340| `not` + unknown id | Raw false → NOT true — validation must warn on unknown ids |
341| Thresholds | All “at least” (≥) |
342| Parallel quests | Yes; soft cap ~20 active |
343| One step per quest | Yes (single numeric state) |
344| Apply mid-dialogue | Close sessions |
345
346### 8.1 Open product choices (see §12)
347
348Small list of remaining decisions before / during implementation — none are architectural blockers if defaults in §12 are accepted.
349
350---
351
352## 9. World editor: unsaved chunk navigation & Save affordance
353
354Independent of quests; ship with this plan’s commit.
355
356### 9.1 Dirty state
357
358- Baseline when chunk loads / after save; paint/spawner edits → dirty; structural compare.
359
360### 9.2 Navigate away
361
362Modal: Cancel / Discard / Save then navigate.
363
364### 9.3 Save button
365
366Disabled when clean; enabled + blinking when dirty.
367
368---
369
370## 10. Authority & safety
371
372- Client never decides conditions, heard, quest state, or effects.
373- Choose payload: `dialogueId`, `stepId`, `trigger`; server re-evaluates `when`.
374- Branches and interrupts are server-side.
375- Unique / maxAlive enforced on save and Apply.
376
377---
378
379## 11. Feasibility
380
381**High–medium.** World-scoped dialogue assets + assignment is cleaner than per-spawner trees. ConditionSet + `not` covers “A but not B” without exploding kind count. Combat interrupt is a small session hook.
382
383Hardest: event wiring for quest objectives + revision/orphan UX. Graph canvas still v1.1.
384
385---
386
387## 12. Defaults if unspecified (implementation may proceed)
388
389Accept these unless overridden:
390
3911. **Condition polarity:** per-clause `not?: boolean` inside `ConditionSet.all` (no separate OR groups in v1; use multiple ordered dialogue branches for OR).
3922. **Thresholds:** all ≥ (“at least”).
3933. **Interrupt:** any hostile damage/engagement **on the NPC** closes dialogue for whoever was talking to it (not only if the talker is the attacker).
3944. **Unique conflict:** editor **blocks** the illegal save (does not auto-unassign silently).
3955. **Assignment count:** computed from pending/applied chunk spawners when opening Dialogues editor (accurate enough for v1).
3966. **`lacksItem` / `dialogueNotHeard`:** not separate kinds; use `not` + positive kind (editor may offer presets).
3977. **Objectives:** one objective completes when its entire `ConditionSet` is true (event kinds latch once true).
3988. **Editors placement:** **Quests** and **Dialogues** buttons stacked **under** the Settings button (separate modals, not Settings tabs).
3999. **Step-complete toast:** “Quest objectives achieved”; click opens that quest’s detail modal.
400
401**Not blocking for v1:** graph canvas, script verbs, repeatable quests, localization, visual tile picker.