Plan quests/dialogue editor and guard unsaved chunk navigation.
@@ -29,7 +29,7 @@
29
29
<button id="open-palette" type="button">Select block…</button>
30
30
<button type="button" id="tool-erase">Erase block</button>
31
31
</div>
32
<button id="save" type="button">Save chunk</button>
32
<button id="save" type="button" disabled title="No unsaved changes">Save chunk</button>
33
33
<button id="apply" type="button" disabled title="Save a chunk first to create a pending revision">Apply now</button>
34
34
<p id="apply-status" class="hint" aria-live="polite"></p>
35
35
<label>Night preview <input id="night" type="range" min="0" max="24" step="0.1" value="12"><span id="night-label">12.0</span></label>
@@ -131,6 +131,19 @@
131
131
</div>
132
132
</div>
133
133
</div>
134
135
<div id="unsaved-chunk-backdrop" hidden></div>
136
<div id="unsaved-chunk-modal" hidden role="dialog" aria-modal="true" aria-labelledby="unsaved-chunk-title">
137
<header>
138
<h2 id="unsaved-chunk-title">Unsaved changes</h2>
139
</header>
140
<p>You have unsaved changes on this chunk. Leave without saving?</p>
141
<footer class="unsaved-chunk-actions">
142
<button id="unsaved-chunk-cancel" type="button">Cancel</button>
143
<button id="unsaved-chunk-discard" type="button">Discard</button>
144
<button id="unsaved-chunk-save" type="button">Save</button>
145
</footer>
146
</div>
134
147
<script src="/framework/framework.js"></script>
135
148
<script type="module" src="/src/editor/main.js"></script>
136
149
</body>
@@ -29,7 +29,7 @@29
<button id="open-palette" type="button">Select block…</button>29
<button id="open-palette" type="button">Select block…</button>30
<button type="button" id="tool-erase">Erase block</button>30
<button type="button" id="tool-erase">Erase block</button>31
</div>31
</div>32
<button id="save" type="button">Save chunk</button>32
<button id="save" type="button" disabled title="No unsaved changes">Save chunk</button>33
<button id="apply" type="button" disabled title="Save a chunk first to create a pending revision">Apply now</button>33
<button id="apply" type="button" disabled title="Save a chunk first to create a pending revision">Apply now</button>34
<p id="apply-status" class="hint" aria-live="polite"></p>34
<p id="apply-status" class="hint" aria-live="polite"></p>35
<label>Night preview <input id="night" type="range" min="0" max="24" step="0.1" value="12"><span id="night-label">12.0</span></label>35
<label>Night preview <input id="night" type="range" min="0" max="24" step="0.1" value="12"><span id="night-label">12.0</span></label>@@ -131,6 +131,19 @@131
</div>131
</div>132
</div>132
</div>133
</div>133
</div>134
135
<div id="unsaved-chunk-backdrop" hidden></div>136
<div id="unsaved-chunk-modal" hidden role="dialog" aria-modal="true" aria-labelledby="unsaved-chunk-title">137
<header>138
<h2 id="unsaved-chunk-title">Unsaved changes</h2>139
</header>140
<p>You have unsaved changes on this chunk. Leave without saving?</p>141
<footer class="unsaved-chunk-actions">142
<button id="unsaved-chunk-cancel" type="button">Cancel</button>143
<button id="unsaved-chunk-discard" type="button">Discard</button>144
<button id="unsaved-chunk-save" type="button">Save</button>145
</footer>146
</div>134
<script src="/framework/framework.js"></script>147
<script src="/framework/framework.js"></script>135
<script type="module" src="/src/editor/main.js"></script>148
<script type="module" src="/src/editor/main.js"></script>136
</body>149
</body>@@ -36,6 +36,12 @@ let socket;
36
36
let scene;
37
37
let view;
38
38
let draft = null;
39
/** @type {string|null} JSON snapshot of last loaded/saved draft (grounds/blocks/spawners/open). */
40
let draftBaseline = null;
41
/** @type {{ chunkX: number, chunkY: number }|null} */
42
let pendingNavigate = null;
43
/** When true, next matching editorChunk after save should navigate to pendingNavigate. */
44
let navigateAfterSave = false;
39
45
let chunkX = 0;
40
46
let chunkY = 0;
41
47
let tool = { kind: "ground", typeId: GroundType.grass, state: null };
@@ -167,6 +173,83 @@ function spawnerAt (localX, localY)
167
173
return (draft?.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
168
174
}
169
175
176
function draftPersistable ()
177
{
178
if (!draft)
179
{ return null; }
180
return {
181
open: !!draft.open,
182
grounds: draft.grounds,
183
blocks: draft.blocks,
184
spawners: draft.spawners ?? []
185
};
186
}
187
188
function captureDraftBaseline ()
189
{
190
const payload = draftPersistable();
191
draftBaseline = payload ? JSON.stringify(payload) : null;
192
syncSaveButton();
193
}
194
195
function isDraftDirty ()
196
{
197
if (!draft || draftBaseline == null)
198
{ return false; }
199
return JSON.stringify(draftPersistable()) !== draftBaseline;
200
}
201
202
function syncSaveButton ()
203
{
204
const btn = $("save");
205
if (!btn)
206
{ return; }
207
const dirty = isDraftDirty();
208
btn.disabled = !dirty;
209
btn.classList.toggle("save-dirty", dirty);
210
btn.title = dirty ? "Save unsaved chunk changes" : "No unsaved changes";
211
}
212
213
function afterDraftMutation ()
214
{
215
syncSaveButton();
216
}
217
218
function showUnsavedModal (target)
219
{
220
pendingNavigate = target;
221
$("unsaved-chunk-backdrop").hidden = false;
222
$("unsaved-chunk-modal").hidden = false;
223
}
224
225
function hideUnsavedModal ()
226
{
227
$("unsaved-chunk-backdrop").hidden = true;
228
$("unsaved-chunk-modal").hidden = true;
229
}
230
231
function saveSelectedChunk ()
232
{
233
if (!draft || !isDraftDirty())
234
{ return false; }
235
$("error").textContent = "";
236
$("apply-status").textContent = "";
237
$("apply-status").className = "hint";
238
socket.send({
239
type: MessageType.editorSaveChunk,
240
chunkX,
241
chunkY,
242
draft: {
243
open: $("open").checked,
244
grounds: draft.grounds,
245
blocks: draft.blocks,
246
spawners: draft.spawners ?? []
247
}
248
});
249
requestNeighbors();
250
return true;
251
}
252
170
253
function paintAt (localX, localY)
171
254
{
172
255
if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
@@ -186,6 +269,7 @@ function paintAt (localX, localY)
186
269
});
187
270
if (removed && definitionUsesNeighborConnect(BLOCK_DEFINITIONS[removed.typeId]))
188
271
{ refreshNeighborConnect(localX, localY, removed.typeId); }
272
afterDraftMutation();
189
273
return;
190
274
}
191
275
else if (tool.kind === "spawner")
@@ -205,6 +289,7 @@ function paintAt (localX, localY)
205
289
draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY);
206
290
draft.spawners.push(entry);
207
291
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
292
afterDraftMutation();
208
293
return;
209
294
}
210
295
else
@@ -223,6 +308,7 @@ function paintAt (localX, localY)
223
308
});
224
309
if (definitionUsesNeighborConnect(def))
225
310
{ refreshNeighborConnect(localX, localY, tool.typeId); }
311
afterDraftMutation();
226
312
return;
227
313
}
228
314
view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
@@ -230,6 +316,7 @@ function paintAt (localX, localY)
230
316
block: draft.blocks[index],
231
317
light: draft.light[index]
232
318
});
319
afterDraftMutation();
233
320
}
234
321
235
322
/** Recompute neighbor-connect masks for a type around a local tile (same chunk). */
@@ -327,6 +414,14 @@ function showSelectedChunk (payload)
327
414
}
328
415
view.applySnapshot(snapshotFromPayload(payload));
329
416
syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);
417
captureDraftBaseline();
418
if (navigateAfterSave && pendingNavigate)
419
{
420
const next = pendingNavigate;
421
navigateAfterSave = false;
422
pendingNavigate = null;
423
doLoadNeighborhood(next.chunkX, next.chunkY);
424
}
330
425
}
331
426
332
427
function pruneView ()
@@ -414,7 +509,7 @@ function requestChunks (coords)
414
509
}
415
510
}
416
511
417
function loadNeighborhood (x, y)
512
function doLoadNeighborhood (x, y)
418
513
{
419
514
chunkX = x;
420
515
chunkY = y;
@@ -422,6 +517,16 @@ function loadNeighborhood (x, y)
422
517
requestChunks(neighborhoodCoords(x, y));
423
518
}
424
519
520
function loadNeighborhood (x, y)
521
{
522
if ((x !== chunkX || y !== chunkY) && isDraftDirty())
523
{
524
showUnsavedModal({ chunkX: x, chunkY: y });
525
return;
526
}
527
doLoadNeighborhood(x, y);
528
}
529
425
530
function requestNeighbors ()
426
531
{
427
532
requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
@@ -429,7 +534,10 @@ function requestNeighbors ()
429
534
430
535
function anyModalOpen ()
431
536
{
432
return settingsModal?.isOpen() || paletteModal?.isOpen() || tileConfigModal?.isOpen();
537
return settingsModal?.isOpen()
538
|| paletteModal?.isOpen()
539
|| tileConfigModal?.isOpen()
540
|| !$("unsaved-chunk-modal")?.hidden;
433
541
}
434
542
435
543
function updateTooltip (local)
@@ -535,6 +643,7 @@ async function main ()
535
643
draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
536
644
draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
537
645
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
646
afterDraftMutation();
538
647
},
539
648
onRemove (ctx)
540
649
{
@@ -542,6 +651,7 @@ async function main ()
542
651
{ return; }
543
652
draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
544
653
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
654
afterDraftMutation();
545
655
}
546
656
});
547
657
@@ -624,6 +734,7 @@ async function main ()
624
734
else if (message.type === MessageType.error)
625
735
{
626
736
$("error").textContent = message.message;
737
navigateAfterSave = false;
627
738
if (applyInFlight)
628
739
{
629
740
applyInFlight = false;
@@ -668,25 +779,48 @@ $("open").addEventListener("change", () =>
668
779
{
669
780
draft.open = $("open").checked;
670
781
view.setChunkOpen(chunkX, chunkY, draft.open);
782
afterDraftMutation();
671
783
}
672
784
});
673
785
$("save").addEventListener("click", () =>
674
786
{
675
$("error").textContent = "";
676
$("apply-status").textContent = "";
677
$("apply-status").className = "hint";
678
socket.send({
679
type: MessageType.editorSaveChunk,
680
chunkX,
681
chunkY,
682
draft: {
683
open: $("open").checked,
684
grounds: draft.grounds,
685
blocks: draft.blocks,
686
spawners: draft.spawners ?? []
687
}
688
});
689
requestNeighbors();
787
saveSelectedChunk();
788
});
789
$("unsaved-chunk-cancel")?.addEventListener("click", () =>
790
{
791
pendingNavigate = null;
792
navigateAfterSave = false;
793
hideUnsavedModal();
794
});
795
$("unsaved-chunk-backdrop")?.addEventListener("click", () =>
796
{
797
pendingNavigate = null;
798
navigateAfterSave = false;
799
hideUnsavedModal();
800
});
801
$("unsaved-chunk-discard")?.addEventListener("click", () =>
802
{
803
const next = pendingNavigate;
804
hideUnsavedModal();
805
pendingNavigate = null;
806
navigateAfterSave = false;
807
if (next)
808
{ doLoadNeighborhood(next.chunkX, next.chunkY); }
809
});
810
$("unsaved-chunk-save")?.addEventListener("click", () =>
811
{
812
hideUnsavedModal();
813
if (!pendingNavigate)
814
{ return; }
815
navigateAfterSave = true;
816
if (!saveSelectedChunk())
817
{
818
navigateAfterSave = false;
819
const next = pendingNavigate;
820
pendingNavigate = null;
821
if (next)
822
{ doLoadNeighborhood(next.chunkX, next.chunkY); }
823
}
690
824
});
691
825
$("apply").addEventListener("click", () =>
692
826
{
@@ -36,6 +36,12 @@ let socket;36
let scene;36
let scene;37
let view;37
let view;38
let draft = null;38
let draft = null;39
/** @type {string|null} JSON snapshot of last loaded/saved draft (grounds/blocks/spawners/open). */40
let draftBaseline = null;41
/** @type {{ chunkX: number, chunkY: number }|null} */42
let pendingNavigate = null;43
/** When true, next matching editorChunk after save should navigate to pendingNavigate. */44
let navigateAfterSave = false;39
let chunkX = 0;45
let chunkX = 0;40
let chunkY = 0;46
let chunkY = 0;41
let tool = { kind: "ground", typeId: GroundType.grass, state: null };47
let tool = { kind: "ground", typeId: GroundType.grass, state: null };@@ -167,6 +173,83 @@ function spawnerAt (localX, localY)167
return (draft?.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null;173
return (draft?.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null;168
}174
}169
175
176
function draftPersistable ()177
{178
if (!draft)179
{ return null; }180
return {181
open: !!draft.open,182
grounds: draft.grounds,183
blocks: draft.blocks,184
spawners: draft.spawners ?? []185
};186
}187
188
function captureDraftBaseline ()189
{190
const payload = draftPersistable();191
draftBaseline = payload ? JSON.stringify(payload) : null;192
syncSaveButton();193
}194
195
function isDraftDirty ()196
{197
if (!draft || draftBaseline == null)198
{ return false; }199
return JSON.stringify(draftPersistable()) !== draftBaseline;200
}201
202
function syncSaveButton ()203
{204
const btn = $("save");205
if (!btn)206
{ return; }207
const dirty = isDraftDirty();208
btn.disabled = !dirty;209
btn.classList.toggle("save-dirty", dirty);210
btn.title = dirty ? "Save unsaved chunk changes" : "No unsaved changes";211
}212
213
function afterDraftMutation ()214
{215
syncSaveButton();216
}217
218
function showUnsavedModal (target)219
{220
pendingNavigate = target;221
$("unsaved-chunk-backdrop").hidden = false;222
$("unsaved-chunk-modal").hidden = false;223
}224
225
function hideUnsavedModal ()226
{227
$("unsaved-chunk-backdrop").hidden = true;228
$("unsaved-chunk-modal").hidden = true;229
}230
231
function saveSelectedChunk ()232
{233
if (!draft || !isDraftDirty())234
{ return false; }235
$("error").textContent = "";236
$("apply-status").textContent = "";237
$("apply-status").className = "hint";238
socket.send({239
type: MessageType.editorSaveChunk,240
chunkX,241
chunkY,242
draft: {243
open: $("open").checked,244
grounds: draft.grounds,245
blocks: draft.blocks,246
spawners: draft.spawners ?? []247
}248
});249
requestNeighbors();250
return true;251
}252
170
function paintAt (localX, localY)253
function paintAt (localX, localY)171
{254
{172
if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)255
if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)@@ -186,6 +269,7 @@ function paintAt (localX, localY)186
});269
});187
if (removed && definitionUsesNeighborConnect(BLOCK_DEFINITIONS[removed.typeId]))270
if (removed && definitionUsesNeighborConnect(BLOCK_DEFINITIONS[removed.typeId]))188
{ refreshNeighborConnect(localX, localY, removed.typeId); }271
{ refreshNeighborConnect(localX, localY, removed.typeId); }272
afterDraftMutation();189
return;273
return;190
}274
}191
else if (tool.kind === "spawner")275
else if (tool.kind === "spawner")@@ -205,6 +289,7 @@ function paintAt (localX, localY)205
draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY);289
draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY);206
draft.spawners.push(entry);290
draft.spawners.push(entry);207
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);291
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);292
afterDraftMutation();208
return;293
return;209
}294
}210
else295
else@@ -223,6 +308,7 @@ function paintAt (localX, localY)223
});308
});224
if (definitionUsesNeighborConnect(def))309
if (definitionUsesNeighborConnect(def))225
{ refreshNeighborConnect(localX, localY, tool.typeId); }310
{ refreshNeighborConnect(localX, localY, tool.typeId); }311
afterDraftMutation();226
return;312
return;227
}313
}228
view.updateAuthoredTile(chunkX, chunkY, localX, localY, {314
view.updateAuthoredTile(chunkX, chunkY, localX, localY, {@@ -230,6 +316,7 @@ function paintAt (localX, localY)230
block: draft.blocks[index],316
block: draft.blocks[index],231
light: draft.light[index]317
light: draft.light[index]232
});318
});319
afterDraftMutation();233
}320
}234
321
235
/** Recompute neighbor-connect masks for a type around a local tile (same chunk). */322
/** Recompute neighbor-connect masks for a type around a local tile (same chunk). */@@ -327,6 +414,14 @@ function showSelectedChunk (payload)327
}414
}328
view.applySnapshot(snapshotFromPayload(payload));415
view.applySnapshot(snapshotFromPayload(payload));329
syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);416
syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);417
captureDraftBaseline();418
if (navigateAfterSave && pendingNavigate)419
{420
const next = pendingNavigate;421
navigateAfterSave = false;422
pendingNavigate = null;423
doLoadNeighborhood(next.chunkX, next.chunkY);424
}330
}425
}331
426
332
function pruneView ()427
function pruneView ()@@ -414,7 +509,7 @@ function requestChunks (coords)414
}509
}415
}510
}416
511
417
function loadNeighborhood (x, y)512
function doLoadNeighborhood (x, y)418
{513
{419
chunkX = x;514
chunkX = x;420
chunkY = y;515
chunkY = y;@@ -422,6 +517,16 @@ function loadNeighborhood (x, y)422
requestChunks(neighborhoodCoords(x, y));517
requestChunks(neighborhoodCoords(x, y));423
}518
}424
519
520
function loadNeighborhood (x, y)521
{522
if ((x !== chunkX || y !== chunkY) && isDraftDirty())523
{524
showUnsavedModal({ chunkX: x, chunkY: y });525
return;526
}527
doLoadNeighborhood(x, y);528
}529
425
function requestNeighbors ()530
function requestNeighbors ()426
{531
{427
requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));532
requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));@@ -429,7 +534,10 @@ function requestNeighbors ()429
534
430
function anyModalOpen ()535
function anyModalOpen ()431
{536
{432
return settingsModal?.isOpen() || paletteModal?.isOpen() || tileConfigModal?.isOpen();537
return settingsModal?.isOpen()538
|| paletteModal?.isOpen()539
|| tileConfigModal?.isOpen()540
|| !$("unsaved-chunk-modal")?.hidden;433
}541
}434
542
435
function updateTooltip (local)543
function updateTooltip (local)@@ -535,6 +643,7 @@ async function main ()535
draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);643
draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);536
draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });644
draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });537
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);645
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);646
afterDraftMutation();538
},647
},539
onRemove (ctx)648
onRemove (ctx)540
{649
{@@ -542,6 +651,7 @@ async function main ()542
{ return; }651
{ return; }543
draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);652
draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);544
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);653
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);654
afterDraftMutation();545
}655
}546
});656
});547
657
@@ -624,6 +734,7 @@ async function main ()624
else if (message.type === MessageType.error)734
else if (message.type === MessageType.error)625
{735
{626
$("error").textContent = message.message;736
$("error").textContent = message.message;737
navigateAfterSave = false;627
if (applyInFlight)738
if (applyInFlight)628
{739
{629
applyInFlight = false;740
applyInFlight = false;@@ -668,25 +779,48 @@ $("open").addEventListener("change", () =>668
{779
{669
draft.open = $("open").checked;780
draft.open = $("open").checked;670
view.setChunkOpen(chunkX, chunkY, draft.open);781
view.setChunkOpen(chunkX, chunkY, draft.open);782
afterDraftMutation();671
}783
}672
});784
});673
$("save").addEventListener("click", () =>785
$("save").addEventListener("click", () =>674
{786
{675
$("error").textContent = "";787
saveSelectedChunk();676
$("apply-status").textContent = "";788
});677
$("apply-status").className = "hint";789
$("unsaved-chunk-cancel")?.addEventListener("click", () =>678
socket.send({790
{679
type: MessageType.editorSaveChunk,791
pendingNavigate = null;680
chunkX,792
navigateAfterSave = false;681
chunkY,793
hideUnsavedModal();682
draft: {794
});683
open: $("open").checked,795
$("unsaved-chunk-backdrop")?.addEventListener("click", () =>684
grounds: draft.grounds,796
{685
blocks: draft.blocks,797
pendingNavigate = null;686
spawners: draft.spawners ?? []798
navigateAfterSave = false;687
}799
hideUnsavedModal();688
});800
});689
requestNeighbors();801
$("unsaved-chunk-discard")?.addEventListener("click", () =>802
{803
const next = pendingNavigate;804
hideUnsavedModal();805
pendingNavigate = null;806
navigateAfterSave = false;807
if (next)808
{ doLoadNeighborhood(next.chunkX, next.chunkY); }809
});810
$("unsaved-chunk-save")?.addEventListener("click", () =>811
{812
hideUnsavedModal();813
if (!pendingNavigate)814
{ return; }815
navigateAfterSave = true;816
if (!saveSelectedChunk())817
{818
navigateAfterSave = false;819
const next = pendingNavigate;820
pendingNavigate = null;821
if (next)822
{ doLoadNeighborhood(next.chunkX, next.chunkY); }823
}690
});824
});691
$("apply").addEventListener("click", () =>825
$("apply").addEventListener("click", () =>692
{826
{@@ -61,6 +61,48 @@ button:disabled {
61
61
opacity: 0.45;
62
62
cursor: not-allowed;
63
63
}
64
#save.save-dirty:not(:disabled) {
65
animation: save-pulse 1.1s ease-in-out infinite;
66
border-color: #c9a227;
67
box-shadow: 0 0 0 1px rgba(201, 162, 39, 0.35);
68
}
69
@keyframes save-pulse {
70
0%, 100% { opacity: 1; }
71
50% { opacity: 0.55; }
72
}
73
#unsaved-chunk-backdrop {
74
position: fixed;
75
inset: 0;
76
background: rgba(0, 0, 0, 0.62);
77
z-index: 29;
78
}
79
#unsaved-chunk-modal {
80
position: fixed;
81
left: 50%;
82
top: 50%;
83
transform: translate(-50%, -50%);
84
z-index: 30;
85
width: min(420px, 92vw);
86
padding: 1rem 1.1rem;
87
background: #161a22;
88
border: 1px solid #3a4250;
89
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
90
}
91
#unsaved-chunk-modal header {
92
margin: 0 0 0.5rem;
93
padding: 0;
94
border: 0;
95
}
96
#unsaved-chunk-modal h2 {
97
margin: 0;
98
font-size: 1.1rem;
99
}
100
.unsaved-chunk-actions {
101
display: flex;
102
justify-content: flex-end;
103
gap: 0.5rem;
104
margin-top: 1rem;
105
}
64
106
#apply-status.ok { color: #b8d4a0; }
65
107
.error { color: #f0a0a0; }
66
108
.hint { color: #9aa3b2; font-size: 0.85rem; }
@@ -61,6 +61,48 @@ button:disabled {61
opacity: 0.45;61
opacity: 0.45;62
cursor: not-allowed;62
cursor: not-allowed;63
}63
}64
#save.save-dirty:not(:disabled) {65
animation: save-pulse 1.1s ease-in-out infinite;66
border-color: #c9a227;67
box-shadow: 0 0 0 1px rgba(201, 162, 39, 0.35);68
}69
@keyframes save-pulse {70
0%, 100% { opacity: 1; }71
50% { opacity: 0.55; }72
}73
#unsaved-chunk-backdrop {74
position: fixed;75
inset: 0;76
background: rgba(0, 0, 0, 0.62);77
z-index: 29;78
}79
#unsaved-chunk-modal {80
position: fixed;81
left: 50%;82
top: 50%;83
transform: translate(-50%, -50%);84
z-index: 30;85
width: min(420px, 92vw);86
padding: 1rem 1.1rem;87
background: #161a22;88
border: 1px solid #3a4250;89
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);90
}91
#unsaved-chunk-modal header {92
margin: 0 0 0.5rem;93
padding: 0;94
border: 0;95
}96
#unsaved-chunk-modal h2 {97
margin: 0;98
font-size: 1.1rem;99
}100
.unsaved-chunk-actions {101
display: flex;102
justify-content: flex-end;103
gap: 0.5rem;104
margin-top: 1rem;105
}64
#apply-status.ok { color: #b8d4a0; }106
#apply-status.ok { color: #b8d4a0; }65
.error { color: #f0a0a0; }107
.error { color: #f0a0a0; }66
.hint { color: #9aa3b2; font-size: 0.85rem; }108
.hint { color: #9aa3b2; font-size: 0.85rem; }@@ -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. **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). **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` (one int driving hit chance and damage), `drops` (`{ itemId, chance }[]`), `sells` (item ID list), and `dialogue` trees. Dialogue nodes use `trigger`, `lines[]` (`{ isPlayer, text }`), and `responses[]` (`{ trigger, text, available? }` where `available` is an optional `(ctx) => boolean`). Response actions (later): start quest, give item, open trade, or start mob AI behaviour. Rendering fields (sprites, gait, flight) stay alongside gameplay fields until content tooling splits them.
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).
194
194
**Code:** `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`
195
195
196
196
## Quests
197
197
198
**Status:** not implemented
199
**Spec:** Quests are obtained from friendly mobs (dialogue action). Each quest has ordered progression states that advance when the player completes a requirement: obtain an item, fire a dialogue trigger, kill a quota of mobs, reach a tile, or interact with a block. Completion may award skill XP and items; if inventory is full, overflow items are sent to the character vault by carrier pigeon.
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.
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 fi70
## 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. **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). **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 changelog76
## Per-chunk changelog@@ -190,13 +190,13 @@ Each entry is a short note on behaviour and where the code lives. Update this fi190
## 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` (one int driving hit chance and damage), `drops` (`{ itemId, chance }[]`), `sells` (item ID list), and `dialogue` trees. Dialogue nodes use `trigger`, `lines[]` (`{ isPlayer, text }`), and `responses[]` (`{ trigger, text, available? }` where `available` is an optional `(ctx) => boolean`). Response actions (later): start quest, give item, open trade, or start mob AI behaviour. Rendering fields (sprites, gait, flight) stay alongside gameplay fields until content tooling splits them. 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). 194
**Code:** `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`194
**Code:** `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`195
195
196
## Quests196
## Quests197
197
198
**Status:** not implemented 198
**Status:** not implemented (design) 199
**Spec:** Quests are obtained from friendly mobs (dialogue action). Each quest has ordered progression states that advance when the player completes a requirement: obtain an item, fire a dialogue trigger, kill a quota of mobs, reach a tile, or interact with a block. Completion may award skill XP and items; if inventory is full, overflow items are sent to the character vault by carrier pigeon. 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. 200
**Code:** —200
**Code:** —201
201
202
## Character logout resume202
## Character logout resume@@ -0,0 +1,281 @@
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.
@@ -0,0 +1,281 @@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 rules5
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. Goals13
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 & identity23
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 IDs31
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 shape48
49
```text50
Quest {51
questId: string52
title: string53
description: string // player-facing log blurb (in-universe)54
steps: Step[] // ordered progression55
rewards?: Reward[] // granted on final step complete56
cancelable?: boolean // default false in v157
}58
```59
60
### 3.1 Steps61
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
```text65
Step {66
stepId: string67
title: string // short log line68
hint?: string // optional guidance69
require: Condition[] // all must pass70
onEnter?: Effect[] // optional (toast, flag) — keep minimal in v171
onComplete?: Effect[] // optional mid-quest grants; prefer final rewards72
}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 state111
112
```text113
CharacterQuest {114
questId115
status: inactive | active | completed | failed // failed unused in v1 unless cancel116
activeStepId: string | null117
completedStepIds: string[]118
counters: { [key: string]: number } // e.g. kill quotas for current step119
startedAt, completedAt120
}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 spawners130
131
Dialogue is authored **per spawner** (humanoid / talkable NPC), not in code mob defs (defs may keep empty `dialogue: []`).132
133
### 5.1 Shape134
135
```text136
DialogueNode {137
trigger: string138
lines: { speaker: "npc" | "player", text: string }[]139
responses: DialogueResponse[]140
}141
142
DialogueResponse {143
label: string // button text144
nextTrigger: string | null // follow-up node trigger; null = end145
require?: DialogueRequirement[] // all must pass to show/enable146
effects?: Effect[] // on choose: startQuest, takeItem, …147
}148
```149
150
### 5.2 Requirements on responses151
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 Runtime163
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** section175
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 start185
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 problems229
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 affordance240
241
Independent of quests; ship with this plan’s commit.242
243
### 9.1 Dirty state244
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 away250
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 button259
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 & safety267
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. Feasibility276
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.