# Quests & NPC dialogue (world editor) **Status:** partial (v1 runtime + editors; polish / graph / effects UI later) **Related:** `docs/FEATURES.md` (Quests, Mob definitions), `docs/SCRIPTS.md` (parity reminder for future script verbs), server authority rules 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. This document is the product + data + editor spec for implementation. --- ## 1. Goals - Author **quests** and **dialogue trees** as world-scoped assets (editors under **World settings**). - Assign a dialogue to a **humanoid spawner** by reference (`dialogueId`); show assignment counts; support **unique** dialogues. - Progress quests via **objectives** with shared multi-condition sets (including negations) and per-step **journal** text. - Dialogue: line gifts, player-choice triggers, or **auto-branches**; track **dialogueHeard** per step; **interrupt on attack**. - Player **Quests** UI: list + split detail (journal | step/objectives). - Fail safe: broken references fail closed; editor validation catches unique/assignment rules. --- ## 2. Persistence & identity | Asset | Storage | Apply model | |-------|---------|-------------| | **Quest definitions** | `world.sqlite` (revisioned with map) | Editor save → pending; **Apply now** → live | | **Dialogue trees** | `world.sqlite` (revisioned with map) — **not** embedded in chunk JSON | Same as quests | | **Spawner → dialogue link** | Chunk spawner `config.dialogueId` (string \| null) | Saved with the chunk | | **Quest progress** | `state.sqlite` (`questState`) | Live | | **Dialogue heard** | `state.sqlite` (`dialogueHeard`) | Live | ### 2.1 IDs - **Quest id:** stable slug (`deliver-tin-ore`). Prefer immutable after publish. - **Quest step id:** stable within quest; conditions also use **1-based index** in `steps[]` (§4). - **Dialogue id:** stable world-scoped id (`smith-intro`). Keys `dialogueHeard`, conditions, spawner assignment. - **Dialogue step id / trigger id:** stable within that dialogue. - **NPC reference in quests:** prefer **spawner id** + optional display-name hint — not transient entity ids. ### 2.2 World settings: Quests & Dialogues editors 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). | Button | Purpose | |--------|---------| | **Settings** | Existing world settings | | **Quests** | CRUD all quest defs (id, title, steps, objectives, rewards, validation) | | **Dialogues** | CRUD all dialogue trees (id, unique flag, steps, exits, validation) | Both editors are **world-global** (not per-chunk). Saves go through the same admin auth + revision story as other authored world data. **Dialogues list columns:** id, label/title, step count, **`unique`**, **assigned spawner count**, validation warnings. **Delete dialogue:** warn if any spawner still references it; optionally block delete until unassigned. ### 2.3 Spawner assignment On a **humanoid / talkable** spawner: - Dropdown: **Dialogue** → none, or pick from world dialogue list (show id + unique badge). - Stores `config.dialogueId` only (no inline tree on the spawner). **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. ### 2.4 Unique dialogues ```text DialogueTree.unique: boolean // default false ``` When `unique === true`: 1. **At most one spawner** in the world may have `config.dialogueId` equal to that id. 2. That spawner’s **`maxAlive` must be `1`** (editor clamps / blocks save otherwise; server normalize rejects Apply if violated). Editor UX: - Toggling **Unique** on while 2+ spawners assigned → block or offer “unassign others / cancel”. - Assigning a unique dialogue to a second spawner → block with clear error. - Setting `maxAlive > 1` on a spawner that holds a unique dialogue → block or force `maxAlive = 1`. Non-unique dialogues may be shared by many spawners (and many alive NPCs); `dialogueHeard` is still keyed by `dialogueId`+`stepId` (shared script progress). --- ## 3. Quest definition shape ```text Quest { questId: string title: string description: string // player-facing log blurb (in-universe) steps: Step[] // ordered progression rewards?: Reward[] // granted on final step complete cancelable?: boolean // default false in v1 } ``` ### 3.1 Steps & objectives 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). ```text Step { stepId: string title: string description: string completionJournalText: string objectives: Objective[] // ≥ 1; all must complete onEnter?: Effect[] onComplete?: Effect[] } Objective { objectiveId: string text: string // HUD / detail line when: ConditionSet // objective complete when set passes (or event latch inside set) } ``` **Advancement:** 1. While a step is active, the server tracks which `objectiveId`s are satisfied. 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**. 3. Client: completed objectives struck through. ### 3.2 Condition sets (quests + dialogue) Shared in `shared/`. Evaluated **only on the server**. ```text ConditionSet { all: ConditionClause[] // every clause must pass (AND); empty = always true } ConditionClause { not?: boolean // default false; if true, invert the condition result condition: Condition } ``` **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). Used by: - quest **objectives** (`when`) - dialogue **triggers** (`when` — hide if fail) - dialogue **auto-branches** (`when` — first branch whose set passes) Editor: condition picker rows with a **NOT** toggle per row; add/remove rows. #### Condition kinds | Kind | Fields | Meaning | |------|--------|---------| | `hasItem` | `itemId`, `quantity` (≥ 1) | Bag (not vault) has ≥ N | | `atTile` | `dimensionId`, `tileX`, `tileY` | Exact tile in that dimension (default `overworld`) | | `nearTile` | `dimensionId`, `tileX`, `tileY`, `range` (≥ 1) | Chebyshev ≤ range in dim | | `inRect` | `dimensionId`, `minTileX`, `minTileY`, `maxTileX`, `maxTileY` | Inclusive AABB in dim | | `atChunk` | `dimensionId`, `chunkX`, `chunkY` | Player chunk in dim | | `inDimension` | `dimensionId` | Currently in that dimension | | `hasVisitedDimension` | `dimensionId` | Has entered that dim at least once | | `questState` | `questId`, `state` | Equals `not-started` \| `completed` \| number `n` | | `questStepAtLeast` | `questId`, `step` (≥ 1) | Active index ≥ step **or** `completed` | | `dialogueHeard` | `dialogueId`, `stepId` | Heard row exists | | `dialogueTrigger` | `dialogueId`, `trigger` | **Latch:** player chose that trigger (quest objectives) | | `hpAtLeast` | `amount` (≥ 0) | Current HP ≥ amount | | `staminaAtLeast` | `amount` (≥ 0) | Current stamina ≥ amount | | `hpPercentAtLeast` | `percent` (0–100) | currentHP / maxHP × 100 ≥ percent | | `staminaPercentAtLeast` | `percent` (0–100) | currentStamina / maxStamina × 100 ≥ percent | | `skillLevelAtLeast` | `skillId`, `level` (1–99) | `skillLevel(skills, skillId) ≥ level` | | `killCount` | `mobTypeId` **or** `spawnerId`, `count` N | Kills while this quest step active | | `interactBlock` | `dimensionId`, tile and/or `blockTypeId` | Successful interact (once per quest step) | **Notes:** - Prefer **`not` + `hasItem`** over a separate `lacksItem` kind (legacy alias ok). Same for `dialogueNotHeard` → `not` + `dialogueHeard`. - Thresholds use **≥** (“above or equal”); document in editor labels as “at least”. - Max HP / max stamina = same formulas the play sim already uses for the character. - Unknown ids → clause **fails closed** (raw condition false; with `not`, that becomes true — authors should avoid dangling ids; validation warns). - Kill attribution = existing combat kill credit. ### 3.3 Rewards & effects (v1) | Kind | Fields | |------|--------| | `giveItem` | `itemId`, `quantity` | | `giveXp` | `skillId`, `amount` | | `takeItem` | `itemId`, `quantity` | | `startQuest` | `questId` | Sources: quest `onEnter` / `onComplete`, dialogue **line**, **trigger**, **branch**. Full bag → vault via carrier pigeon. --- ## 4. Character quest state & journal ### 4.0 Quest state ```text QuestStateValue = "not-started" | number | "completed" // number = 1-based index of current incomplete step ``` ```text CharacterQuest { questId: string state: QuestStateValue completedObjectiveIds: string[] counters: { [key: string]: number } startedAt?, completedAt? } ``` Missing row ⇒ `not-started`. Conditions read `state` only; counters/objectives are runtime detail for UI + event objectives. ### 4.0b Dialogue heard ```text dialogueHeard (characterId, dialogueId, stepId, heardAt) UNIQUE (characterId, dialogueId, stepId) ``` Insert on step **enter** (first time). Permanent in v1. Gate repeat gifts with `when` sets (`not` + `dialogueHeard`, `not` + `hasItem`, etc.). ### 4.0c Journal ```text QuestJournalEntry { questId, stepId, text, writtenAt } ``` Append-only; text frozen at write time. --- ## 4.1 Player UI — Quests - **Quests** HUD control → list modal: active (`state` number) first, **completed** at bottom; hide `not-started`. - Detail modal: left journal (this quest), right step description + objectives (strikethrough when done). - **Step-complete toast:** text **“Quest objectives achieved”**. Click → open quest detail for the quest that just advanced (same modal stack as the Quests button). --- ## 5. Dialogue (world asset + spawner link) ### 5.1 Shape ```text DialogueTree { dialogueId: string label: string // editor list title unique: boolean // default false; see §2.4 steps: DialogueStep[] entryStepId?: string } DialogueStep { stepId: string label: string lines: DialogueLine[] itemRewards?: { itemId: number, quantity: number }[] // after lines, before exit exit: | { kind: "triggers", triggers: DialogueTrigger[] } | { kind: "branches", branches: DialogueBranch[] } | { kind: "end" } } DialogueLine { speaker: "npc" | "player" text: string effects?: Effect[] } DialogueTrigger { trigger: string label: string // editor text: string // player button nextStepId: string | null // null → end when?: ConditionSet // hide if fail; omit = always show effects?: Effect[] } DialogueBranch { label?: string when: ConditionSet // empty all[] = always nextStepId: string | null effects?: Effect[] } ``` **End rules:** null `nextStepId`, `exit.kind: "end"`, no matching branch, or no visible triggers → **close dialogue**. ### 5.2 Runtime 1. Talk to NPC whose spawner has `dialogueId` → load world DialogueTree → open `entryStepId`. 2. Enter step → insert `dialogueHeard` if new → play lines (apply line effects). 3. On **advance** after the last line: grant `itemRewards` (bag first, overflow to bank/vault), show reward notices in the dialogue UI, then evaluate exit. 4. Triggers / branches / end as authored (conditions see items already granted). 5. **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. ### 5.3 Editor (Dialogues panel) - List + inspector (graph canvas = v1.1). - Per dialogue: id, label, **unique**, assignment count, steps, exit modes, shared condition-set picker (with NOT). - Validation: unique rules (§2.4), missing refs, empty texts, unreachable steps. ### 5.4 Spawner modal Humanoid: **Dialogue** dropdown bound to world dialogues (not an inline tree editor). Link to “Open in Dialogues editor” optional. --- ## 6. How quests start `startQuest` effect → `not-started` → `1`. Block if already numeric or `completed` (v1 no repeats). --- ## 7. Implementation plan (phased) 1. Shared `Condition` / `ConditionSet` / `Effect` in `shared/`. 2. World DB: quest defs + dialogue trees; state: `questState`, `dialogueHeard`, journal. 3. World settings **Quests** + **Dialogues** editors; spawner `dialogueId` + unique/maxAlive validation; assignment counts. 4. Editor unsaved-chunk guard (§9) — may already ship. 5. Runtime dialogue + combat interrupt; line/trigger/branch effects. 6. Quest engine + Quests HUD. 7. Apply revision + tests (conditions+NOT, unique, interrupt, heard, journal). --- ## 8. Edge cases (resolved) | Topic | Decision | |-------|----------| | Unique + 2 assignees | Editor/server reject until ≤ 1 | | Unique + maxAlive ≠ 1 | Reject / clamp to 1 | | Mark unique while assigned elsewhere | Must unassign others first | | Shared (non-unique) dialogue | Many spawners OK; heard shared by dialogueId | | Spawner dialogueId missing tree | Talk no-ops / error log; fail closed | | NPC attacked mid-dialogue | Session closes immediately | | Player walks away / disconnect | Close session (no progress loss beyond already applied) | | `not` + unknown id | Raw false → NOT true — validation must warn on unknown ids | | Thresholds | All “at least” (≥) | | Parallel quests | Yes; soft cap ~20 active | | One step per quest | Yes (single numeric state) | | Apply mid-dialogue | Close sessions | ### 8.1 Open product choices (see §12) Small list of remaining decisions before / during implementation — none are architectural blockers if defaults in §12 are accepted. --- ## 9. World editor: unsaved chunk navigation & Save affordance Independent of quests; ship with this plan’s commit. ### 9.1 Dirty state - Baseline when chunk loads / after save; paint/spawner edits → dirty; structural compare. ### 9.2 Navigate away Modal: Cancel / Discard / Save then navigate. ### 9.3 Save button Disabled when clean; enabled + blinking when dirty. --- ## 10. Authority & safety - Client never decides conditions, heard, quest state, or effects. - Choose payload: `dialogueId`, `stepId`, `trigger`; server re-evaluates `when`. - Branches and interrupts are server-side. - Unique / maxAlive enforced on save and Apply. --- ## 11. Feasibility **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. Hardest: event wiring for quest objectives + revision/orphan UX. Graph canvas still v1.1. --- ## 12. Defaults if unspecified (implementation may proceed) Accept these unless overridden: 1. **Condition polarity:** per-clause `not?: boolean` inside `ConditionSet.all` (no separate OR groups in v1; use multiple ordered dialogue branches for OR). 2. **Thresholds:** all ≥ (“at least”). 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). 4. **Unique conflict:** editor **blocks** the illegal save (does not auto-unassign silently). 5. **Assignment count:** computed from pending/applied chunk spawners when opening Dialogues editor (accurate enough for v1). 6. **`lacksItem` / `dialogueNotHeard`:** not separate kinds; use `not` + positive kind (editor may offer presets). 7. **Objectives:** one objective completes when its entire `ConditionSet` is true (event kinds latch once true). 8. **Editors placement:** **Quests** and **Dialogues** buttons stacked **under** the Settings button (separate modals, not Settings tabs). 9. **Step-complete toast:** “Quest objectives achieved”; click opens that quest’s detail modal. **Not blocking for v1:** graph canvas, script verbs, repeatable quests, localization, visual tile picker.