BlueGit

timfa questward

Files

questward / server / src / editor / service.js

service.js

feat: branch quest steps and remember which steps were finished
timfa project_85689633_bot_760517ee9267c86ff1d6c3a0237abf7d · pushed by timfa · 4 weeks ago
25915c58 History
service.js 32.0 KiB Download Raw
1import { groundDefinition, blockDefinition, normalizeGround, normalizeBlock, BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";
2import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
3import { localToTile, chunkKey } from "../world/coordinates.js";
4import { cloneChunkData, createEmptyChunkData, decodeChunkBlob, encodeChunkBlob, normalizeSpawner } from "../world/chunkData.js";
5import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js";
6import { bakeEnclosedMaps } from "../lighting/enclosedBaker.js";
7import { closedNeighborEdges } from "../world/chunkFlags.js";
8import { coerceSettingValue, diffSettings, diffItemSeedValues, allSettingFields, itemSeedMapsEqual } from "../../../shared/definitions/worldSettings.js";
9import { normalizeItemSeedValues } from "../../../shared/shop/pricing.js";
10import { itemDefinition } from "../../../shared/definitions/items.js";
11import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
12import {
13 normalizeStarterLoadout,
14 starterLoadoutsEqual,
15 diffStarterLoadout
16} from "../../../shared/items/starterLoadout.js";
17import {
18 normalizeInitialQuests,
19 initialQuestsEqual,
20 diffInitialQuests
21} from "../../../shared/quests/initialQuests.js";
22import {
23 normalizeEquipmentStatBonuses,
24 diffEquipmentStatBonuses,
25 equipmentStatBonusMapsEqual
26} from "../../../shared/definitions/equipmentStatCategories.js";
27import {
28 normalizeQuestDef,
29 normalizeDialogueTree,
30 questLookupFromRawDefs
31} from "../../../shared/quests/normalize.js";
32import {
33 OVERWORLD_ID,
34 normalizeDimensionId,
35 normalizeDimensionRecord,
36 defaultDimensionRecord,
37 isOverworld,
38 normalizeLightingMode,
39 normalizeSeasonMode
40} from "../../../shared/world/dimensions.js";
41import { MINIMAP_CHUNK_PIXELS, MINIMAP_SPAN_CHUNKS } from "../../../shared/render/chunkMinimap.js";
42
43export class EditorService
44{
45 constructor (worldDb, stateDb = null, minimapCache = null)
46 {
47 this.worldDb = worldDb;
48 this.stateDb = stateDb;
49 this.minimapCache = minimapCache;
50 }
51
52 #editorDisplayName (editorAdminId)
53 {
54 const subject = String(editorAdminId ?? "").trim();
55 if (!subject)
56 { return "unknown"; }
57 const username = this.stateDb?.getAccountBySubject?.(subject)?.username;
58 const trimmed = username != null ? String(username).trim() : "";
59 return trimmed || subject;
60 }
61
62 #enrichChangelog (entries)
63 {
64 return (entries ?? []).map((entry) => ({
65 ...entry,
66 editorDisplayName: this.#editorDisplayName(entry.editor_admin_id)
67 }));
68 }
69
70 #defaultGroundForDimension (dimensionId, revisionId = null)
71 {
72 const rev = revisionId ?? this.worldDb.getEditorRevisionId();
73 const dimId = normalizeDimensionId(dimensionId);
74 const settings = this.worldDb.getLiveSettings();
75 const record = this.worldDb.getDimension(rev, dimId)
76 ?? defaultDimensionRecord(dimId, { defaultGroundTypeId: settings.defaultGroundTypeId });
77 return record.defaultGroundTypeId;
78 }
79
80 loadChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
81 {
82 const dimId = normalizeDimensionId(dimensionId);
83 const revisionId = this.worldDb.getEditorRevisionId();
84 const settings = this.worldDb.getLiveSettings();
85 const defaultGroundTypeId = this.#defaultGroundForDimension(dimId, revisionId);
86 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId, dimId);
87 const data = row
88 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
89 : createEmptyChunkData(defaultGroundTypeId);
90 const isOpen = (x, y) =>
91 {
92 const neighbor = this.worldDb.getChunkVersion(x, y, revisionId, dimId);
93 if (!neighbor)
94 { return false; }
95 return !!decodeChunkBlob(neighbor.data_blob, defaultGroundTypeId, x, y).open;
96 };
97 return {
98 chunkX,
99 chunkY,
100 dimensionId: dimId,
101 revisionId,
102 pendingRevisionId: this.worldDb.getPendingRevisionId(),
103 activeRevisionId: this.worldDb.getActiveRevisionId(),
104 authored: !!row,
105 settings,
106 data,
107 closedEdges: closedNeighborEdges(chunkX, chunkY, isOpen),
108 changelog: this.#enrichChangelog(this.worldDb.listChangelog(chunkX, chunkY, dimId))
109 };
110 }
111
112 saveChunk (chunkX, chunkY, draft, editorAdminId, dimensionId = OVERWORLD_ID)
113 {
114 const dimId = normalizeDimensionId(dimensionId);
115 const previous = this.loadChunk(chunkX, chunkY, dimId);
116 const next = cloneChunkData(previous.data);
117 const defaultGroundTypeId = this.#defaultGroundForDimension(dimId);
118 next.open = !!draft.open;
119 if (Array.isArray(draft.grounds))
120 { next.grounds = draft.grounds.map((ground) => normalizeGround(ground, defaultGroundTypeId)); }
121 if (Array.isArray(draft.blocks))
122 { next.blocks = draft.blocks.map((block) => normalizeBlock(block)); }
123 if (Array.isArray(draft.spawners))
124 { next.spawners = draft.spawners.map((entry) => normalizeSpawner(entry)).filter(Boolean); }
125
126 this.validateSpawnerDialogues(chunkX, chunkY, next.spawners, dimId);
127
128 const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored);
129 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
130 const loadForBake = (x, y) => this.#loadForBake(
131 x, y, revisionId, defaultGroundTypeId, chunkX, chunkY, next, dimId
132 );
133 const baked = bakeLightMaps(
134 chunkX,
135 chunkY,
136 loadForBake,
137 maxDefinitionLightRange(BLOCK_DEFINITIONS, GROUND_DEFINITIONS),
138 dimId
139 );
140 const byKey = new Map();
141 for (const result of baked)
142 { byKey.set(chunkKey(result.chunkX, result.chunkY, dimId), result); }
143
144 const enclosedBaked = bakeEnclosedMaps(chunkX, chunkY, (x, y) =>
145 {
146 const key = chunkKey(x, y, dimId);
147 if (byKey.has(key))
148 { return byKey.get(key).data; }
149 return loadForBake(x, y);
150 }, dimId);
151 for (const result of enclosedBaked)
152 {
153 const key = chunkKey(result.chunkX, result.chunkY, dimId);
154 if (byKey.has(key))
155 { byKey.get(key).data.enclosed = result.data.enclosed; }
156 else
157 { byKey.set(key, result); }
158 }
159
160 for (const result of byKey.values())
161 {
162 const shouldStore = result.chunkX === chunkX && result.chunkY === chunkY
163 || this.worldDb.getChunkVersion(result.chunkX, result.chunkY, revisionId, dimId)
164 || result.data.light.some((value) => value > 0)
165 || (Array.isArray(result.data.enclosed) && result.data.enclosed.some((value) => value > 0));
166
167 if (!shouldStore)
168 { continue; }
169
170 this.worldDb.saveChunkVersion(
171 result.chunkX,
172 result.chunkY,
173 revisionId,
174 result.data.open ? 1 : 0,
175 encodeChunkBlob(result.data),
176 dimId
177 );
178 // Cache is derived from the blob just stored. A failure here must not
179 // fail the save or rewrite chunk rows.
180 this.#cacheMinimap(result.chunkX, result.chunkY, result.data, dimId, defaultGroundTypeId);
181 }
182
183 if (diffEntries.length > 0)
184 { this.worldDb.appendChangelog(chunkX, chunkY, revisionId, editorAdminId, diffEntries, dimId); }
185
186 return this.loadChunk(chunkX, chunkY, dimId);
187 }
188
189 /**
190 * Minimap images for the 25×25 chunk window centred on this chunk.
191 * Empty when no cache is configured (tests that do not exercise the minimap).
192 */
193 minimapWindow (chunkX, chunkY, dimensionId = OVERWORLD_ID)
194 {
195 const dimId = normalizeDimensionId(dimensionId);
196 const centerX = chunkX | 0;
197 const centerY = chunkY | 0;
198 if (!this.minimapCache)
199 {
200 return {
201 dimensionId: dimId,
202 chunkX: centerX,
203 chunkY: centerY,
204 chunkPixels: MINIMAP_CHUNK_PIXELS,
205 span: MINIMAP_SPAN_CHUNKS,
206 chunks: {}
207 };
208 }
209 return this.minimapCache.window(
210 dimId,
211 centerX,
212 centerY,
213 this.worldDb.getEditorRevisionId(),
214 this.#defaultGroundForDimension(dimId)
215 );
216 }
217
218 #cacheMinimap (chunkX, chunkY, data, dimensionId, defaultGroundTypeId)
219 {
220 if (!this.minimapCache)
221 { return; }
222 try
223 {
224 this.minimapCache.write(dimensionId, chunkX, chunkY, data, defaultGroundTypeId);
225 }
226 catch (error)
227 {
228 console.error(
229 `[minimap] cache write failed for ${dimensionId} ${chunkX},${chunkY}:`,
230 error?.message ?? error
231 );
232 }
233 }
234
235 listDimensions ()
236 {
237 const revisionId = this.worldDb.getEditorRevisionId();
238 return {
239 revisionId,
240 pendingRevisionId: this.worldDb.getPendingRevisionId(),
241 activeRevisionId: this.worldDb.getActiveRevisionId(),
242 dimensions: this.worldDb.listDimensions(revisionId)
243 };
244 }
245
246 createDimension (rawId, displayName, editorAdminId)
247 {
248 const trimmed = String(rawId ?? "").trim();
249 if (!trimmed)
250 {
251 const err = new Error("Dimension id is required.");
252 err.userFacing = true;
253 throw err;
254 }
255 const dimensionId = normalizeDimensionId(trimmed);
256 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
257 if (this.worldDb.getDimension(revisionId, dimensionId))
258 {
259 const err = new Error(`Dimension "${dimensionId}" already exists.`);
260 err.userFacing = true;
261 throw err;
262 }
263 const settings = this.worldDb.getLiveSettings();
264 const record = defaultDimensionRecord(dimensionId, {
265 displayName: displayName != null && String(displayName).trim()
266 ? String(displayName).trim()
267 : dimensionId,
268 defaultGroundTypeId: settings.defaultGroundTypeId
269 });
270 this.worldDb.saveDimension(revisionId, record);
271 return this.listDimensions();
272 }
273
274 saveDimension (raw, editorAdminId)
275 {
276 if (!raw || typeof raw !== "object")
277 {
278 const err = new Error("Dimension payload required.");
279 err.userFacing = true;
280 throw err;
281 }
282 const dimensionId = normalizeDimensionId(raw.dimensionId);
283 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
284 const settings = this.worldDb.getLiveSettings();
285 const existing = this.worldDb.getDimension(revisionId, dimensionId)
286 ?? defaultDimensionRecord(dimensionId, { defaultGroundTypeId: settings.defaultGroundTypeId });
287 const next = normalizeDimensionRecord({
288 ...existing,
289 displayName: Object.prototype.hasOwnProperty.call(raw, "displayName")
290 ? raw.displayName
291 : existing.displayName,
292 lightingMode: Object.prototype.hasOwnProperty.call(raw, "lightingMode")
293 ? normalizeLightingMode(raw.lightingMode)
294 : existing.lightingMode,
295 seasonMode: Object.prototype.hasOwnProperty.call(raw, "seasonMode")
296 ? normalizeSeasonMode(raw.seasonMode)
297 : existing.seasonMode,
298 defaultGroundTypeId: Object.prototype.hasOwnProperty.call(raw, "defaultGroundTypeId")
299 ? raw.defaultGroundTypeId
300 : existing.defaultGroundTypeId,
301 deletedAt: existing.deletedAt,
302 purgeAfter: existing.purgeAfter
303 });
304 this.worldDb.saveDimension(revisionId, next);
305 return this.listDimensions();
306 }
307
308 softDeleteDimension (dimensionId, editorAdminId)
309 {
310 const id = normalizeDimensionId(dimensionId);
311 if (isOverworld(id))
312 {
313 const err = new Error("Cannot delete overworld.");
314 err.userFacing = true;
315 throw err;
316 }
317 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
318 const result = this.worldDb.softDeleteDimension(revisionId, id);
319 if (!result.ok)
320 {
321 const err = new Error(result.error ?? "Delete failed.");
322 err.userFacing = true;
323 throw err;
324 }
325 return this.listDimensions();
326 }
327
328 cancelDimensionDeletion (dimensionId, editorAdminId)
329 {
330 const id = normalizeDimensionId(dimensionId);
331 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
332 const result = this.worldDb.cancelDimensionDeletion(revisionId, id);
333 if (!result.ok)
334 {
335 const err = new Error(result.error ?? "Cancel failed.");
336 err.userFacing = true;
337 throw err;
338 }
339 return this.listDimensions();
340 }
341
342 loadSettings ()
343 {
344 return {
345 settings: this.worldDb.getLiveSettings(),
346 changelog: this.#enrichChangelog(this.worldDb.listSettingsChangelog())
347 };
348 }
349
350 loadGlobalChangelog (limit = 250)
351 {
352 return {
353 changelog: this.#enrichChangelog(this.worldDb.listGlobalChangelog(limit))
354 };
355 }
356
357 saveSettings (partial, editorAdminId)
358 {
359 const current = this.worldDb.getLiveSettings();
360 const next = {
361 ...current,
362 itemSeedValues: {
363 ...(current.itemSeedValues && typeof current.itemSeedValues === "object"
364 ? current.itemSeedValues
365 : {})
366 }
367 };
368 for (const field of allSettingFields())
369 {
370 if (!Object.prototype.hasOwnProperty.call(partial, field.key))
371 { continue; }
372 const value = coerceSettingValue(field, partial[field.key]);
373 if (value == null)
374 { continue; }
375 next[field.key] = value;
376 }
377 if (Object.prototype.hasOwnProperty.call(partial, "itemSeedValues"))
378 {
379 next.itemSeedValues = normalizeItemSeedValues(partial.itemSeedValues);
380 }
381 if (Object.prototype.hasOwnProperty.call(partial, "starterEquipment")
382 || Object.prototype.hasOwnProperty.call(partial, "starterInventory"))
383 {
384 const loadout = normalizeStarterLoadout({
385 starterEquipment: Object.prototype.hasOwnProperty.call(partial, "starterEquipment")
386 ? partial.starterEquipment
387 : current.starterEquipment,
388 starterInventory: Object.prototype.hasOwnProperty.call(partial, "starterInventory")
389 ? partial.starterInventory
390 : current.starterInventory
391 });
392 next.starterEquipment = loadout.equipment;
393 next.starterInventory = loadout.inventory;
394 }
395 if (Object.prototype.hasOwnProperty.call(partial, "equipmentStatBonuses"))
396 {
397 next.equipmentStatBonuses = normalizeEquipmentStatBonuses(partial.equipmentStatBonuses);
398 }
399 else
400 {
401 next.equipmentStatBonuses = normalizeEquipmentStatBonuses(current.equipmentStatBonuses);
402 }
403 if (Object.prototype.hasOwnProperty.call(partial, "initialQuests"))
404 { next.initialQuests = normalizeInitialQuests(partial.initialQuests); }
405 else
406 { next.initialQuests = normalizeInitialQuests(current.initialQuests); }
407 const { bullets: scalarBullets, changed } = diffSettings(current, next);
408 const seedBullets = Object.prototype.hasOwnProperty.call(partial, "itemSeedValues")
409 ? diffItemSeedValues(
410 normalizeItemSeedValues(current.itemSeedValues),
411 next.itemSeedValues,
412 (itemId) => itemDefinition(itemId)?.displayName ?? null
413 )
414 : [];
415 if (!itemSeedMapsEqual(current.itemSeedValues, next.itemSeedValues)
416 && Object.prototype.hasOwnProperty.call(partial, "itemSeedValues"))
417 {
418 changed.itemSeedValues = next.itemSeedValues;
419 }
420 const starterChanged = !starterLoadoutsEqual(current, next)
421 && (Object.prototype.hasOwnProperty.call(partial, "starterEquipment")
422 || Object.prototype.hasOwnProperty.call(partial, "starterInventory"));
423 if (starterChanged)
424 {
425 changed.starterEquipment = next.starterEquipment;
426 changed.starterInventory = next.starterInventory;
427 }
428 const starterBullets = starterChanged
429 ? diffStarterLoadout(current, next)
430 : [];
431 const equipmentStatsChanged = Object.prototype.hasOwnProperty.call(partial, "equipmentStatBonuses")
432 && !equipmentStatBonusMapsEqual(current.equipmentStatBonuses, next.equipmentStatBonuses);
433 if (equipmentStatsChanged)
434 { changed.equipmentStatBonuses = next.equipmentStatBonuses; }
435 const equipmentStatBullets = equipmentStatsChanged
436 ? diffEquipmentStatBonuses(
437 current.equipmentStatBonuses,
438 next.equipmentStatBonuses,
439 (itemId) => itemDefinition(itemId)?.displayName ?? null
440 )
441 : [];
442 const initialQuestsChanged = Object.prototype.hasOwnProperty.call(partial, "initialQuests")
443 && !initialQuestsEqual(current.initialQuests, next.initialQuests);
444 if (initialQuestsChanged)
445 { changed.initialQuests = next.initialQuests; }
446 const initialQuestBullets = initialQuestsChanged
447 ? diffInitialQuests(current.initialQuests, next.initialQuests)
448 : [];
449 const bullets = [
450 ...scalarBullets,
451 ...seedBullets,
452 ...starterBullets,
453 ...equipmentStatBullets,
454 ...initialQuestBullets
455 ];
456 if (Object.keys(changed).length === 0)
457 {
458 return {
459 settings: current,
460 changelog: this.#enrichChangelog(this.worldDb.listSettingsChangelog()),
461 changed: {}
462 };
463 }
464 const settings = {
465 ...current,
466 ...changed,
467 itemSeedValues: changed.itemSeedValues
468 ?? normalizeItemSeedValues(current.itemSeedValues)
469 ?? { ...(DEFAULT_WORLD_SETTINGS.itemSeedValues ?? {}) },
470 starterEquipment: changed.starterEquipment ?? current.starterEquipment
471 ?? DEFAULT_WORLD_SETTINGS.starterEquipment,
472 starterInventory: changed.starterInventory ?? current.starterInventory
473 ?? DEFAULT_WORLD_SETTINGS.starterInventory,
474 equipmentStatBonuses: changed.equipmentStatBonuses
475 ?? normalizeEquipmentStatBonuses(current.equipmentStatBonuses),
476 initialQuests: changed.initialQuests
477 ?? normalizeInitialQuests(current.initialQuests)
478 };
479 const normalized = normalizeStarterLoadout(settings);
480 settings.starterEquipment = normalized.equipment;
481 settings.starterInventory = normalized.inventory;
482 this.worldDb.saveLiveSettings(settings, editorAdminId);
483 this.worldDb.appendSettingsChangelog(editorAdminId, bullets);
484 return {
485 settings,
486 changelog: this.#enrichChangelog(this.worldDb.listSettingsChangelog()),
487 changed,
488 diffEntries: bullets
489 };
490 }
491
492 applyPendingRevision ()
493 {
494 return this.worldDb.promotePendingRevision();
495 }
496
497 revisionStatus ()
498 {
499 return {
500 activeRevisionId: this.worldDb.getActiveRevisionId(),
501 pendingRevisionId: this.worldDb.getPendingRevisionId()
502 };
503 }
504
505
506 /** Flat list of authored spawners across all editor-revision chunks. */
507 listSpawners ()
508 {
509 const revisionId = this.worldDb.getEditorRevisionId();
510 const settings = this.worldDb.getLiveSettings();
511 const out = [];
512 const seen = new Set();
513 for (const { chunk_x: cx, chunk_y: cy, dimension_id: dimensionId } of this.worldDb.listChunkCoords(revisionId))
514 {
515 const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);
516 const row = this.worldDb.getChunkVersion(cx, cy, revisionId, dim);
517 if (!row)
518 { continue; }
519 const data = decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, cx, cy);
520 for (const entry of data.spawners ?? [])
521 {
522 const config = entry?.config;
523 const spawnerId = String(config?.spawnerId ?? "").trim();
524 if (!spawnerId || seen.has(spawnerId))
525 { continue; }
526 seen.add(spawnerId);
527 out.push({
528 spawnerId,
529 mobTypeId: config.mobTypeId ?? null,
530 dimensionId: dim,
531 tileX: localToTile(cx, entry.localX),
532 tileY: localToTile(cy, entry.localY)
533 });
534 }
535 }
536 out.sort((a, b) => String(a.spawnerId).localeCompare(String(b.spawnerId)));
537 return out;
538 }
539
540 #questConditionLookup (extraRaw = null)
541 {
542 const revisionId = this.worldDb.getEditorRevisionId();
543 const raws = this.worldDb.listQuestDefs(revisionId);
544 if (extraRaw)
545 { raws.push(extraRaw); }
546 return questLookupFromRawDefs(raws);
547 }
548
549 loadQuests ()
550 {
551 const revisionId = this.worldDb.getEditorRevisionId();
552 const lookup = this.#questConditionLookup();
553 const quests = this.worldDb.listQuestDefs(revisionId).map((raw) => normalizeQuestDef(raw, lookup));
554 return {
555 revisionId,
556 pendingRevisionId: this.worldDb.getPendingRevisionId(),
557 activeRevisionId: this.worldDb.getActiveRevisionId(),
558 quests,
559 spawners: this.listSpawners(),
560 changelog: this.#enrichChangelog(this.worldDb.listQuestChangelog())
561 };
562 }
563
564 saveQuest (raw, editorAdminId)
565 {
566 const lookup = this.#questConditionLookup(raw);
567 const def = normalizeQuestDef(raw, lookup);
568 const revisionId = this.worldDb.getEditorRevisionId();
569 const previousRaw = this.worldDb.getQuestDef(revisionId, def.questId);
570 const previous = previousRaw ? normalizeQuestDef(previousRaw, lookup) : null;
571 const bullets = diffQuests(previous, def);
572 const pendingId = this.worldDb.ensurePendingRevision(editorAdminId);
573 this.worldDb.saveQuestDef(pendingId, def);
574 if (bullets.length > 0)
575 { this.worldDb.appendQuestChangelog(def.questId, pendingId, editorAdminId, bullets); }
576 return this.loadQuests();
577 }
578
579 deleteQuest (questId, editorAdminId)
580 {
581 const id = String(questId);
582 const revisionId = this.worldDb.getEditorRevisionId();
583 const previousRaw = this.worldDb.getQuestDef(revisionId, id);
584 const pendingId = this.worldDb.ensurePendingRevision(editorAdminId);
585 this.worldDb.deleteQuestDef(pendingId, id);
586 if (previousRaw)
587 {
588 const previous = normalizeQuestDef(previousRaw, this.#questConditionLookup());
589 this.worldDb.appendQuestChangelog(id, pendingId, editorAdminId, [
590 `Quest "${previous.title}" (${id}) deleted.`
591 ]);
592 }
593 return this.loadQuests();
594 }
595
596 loadDialogues ()
597 {
598 const revisionId = this.worldDb.getEditorRevisionId();
599 const lookup = this.#questConditionLookup();
600 const trees = this.worldDb.listDialogueTrees(revisionId).map((raw) => normalizeDialogueTree(raw, lookup));
601 const assignmentCounts = this.#countDialogueAssignments(revisionId);
602 return {
603 revisionId,
604 pendingRevisionId: this.worldDb.getPendingRevisionId(),
605 activeRevisionId: this.worldDb.getActiveRevisionId(),
606 dialogues: trees.map((tree) => ({
607 ...tree,
608 assignedSpawnerCount: assignmentCounts.get(tree.dialogueId) ?? 0
609 })),
610 changelog: this.#enrichChangelog(this.worldDb.listDialogueChangelog())
611 };
612 }
613
614 saveDialogue (raw, editorAdminId)
615 {
616 const lookup = this.#questConditionLookup();
617 const tree = normalizeDialogueTree(raw, lookup);
618 const revisionId = this.worldDb.getEditorRevisionId();
619 const previousRaw = this.worldDb.getDialogueTree(revisionId, tree.dialogueId);
620 const previous = previousRaw ? normalizeDialogueTree(previousRaw, lookup) : null;
621 const assignmentCounts = this.#countDialogueAssignments(revisionId);
622 const assigned = assignmentCounts.get(tree.dialogueId) ?? 0;
623 if (tree.unique && assigned > 1)
624 {
625 const err = new Error("Unique dialogue can be assigned to at most one spawner.");
626 err.userFacing = true;
627 throw err;
628 }
629 if (tree.unique && assigned === 1)
630 {
631 const violation = this.#uniqueDialogueMaxAliveViolation(revisionId, tree.dialogueId);
632 if (violation)
633 {
634 const err = new Error(violation);
635 err.userFacing = true;
636 throw err;
637 }
638 }
639 const bullets = diffDialogues(previous, tree);
640 const pendingId = this.worldDb.ensurePendingRevision(editorAdminId);
641 this.worldDb.saveDialogueTree(pendingId, tree);
642 if (bullets.length > 0)
643 { this.worldDb.appendDialogueChangelog(tree.dialogueId, pendingId, editorAdminId, bullets); }
644 return this.loadDialogues();
645 }
646
647 deleteDialogue (dialogueId, editorAdminId)
648 {
649 const id = String(dialogueId);
650 const revisionId = this.worldDb.getEditorRevisionId();
651 const assigned = this.#countDialogueAssignments(revisionId).get(id) ?? 0;
652 if (assigned > 0)
653 {
654 const err = new Error(`Dialogue is still assigned to ${assigned} spawner(s). Unassign first.`);
655 err.userFacing = true;
656 throw err;
657 }
658 const previousRaw = this.worldDb.getDialogueTree(revisionId, id);
659 const pendingId = this.worldDb.ensurePendingRevision(editorAdminId);
660 this.worldDb.deleteDialogueTree(pendingId, id);
661 if (previousRaw)
662 {
663 const previous = normalizeDialogueTree(previousRaw, this.#questConditionLookup());
664 this.worldDb.appendDialogueChangelog(id, pendingId, editorAdminId, [
665 `Dialogue "${previous.label}" (${id}) deleted.`
666 ]);
667 }
668 return this.loadDialogues();
669 }
670
671 /** Validate dialogueId / unique / maxAlive when saving a chunk's spawners. */
672 validateSpawnerDialogues (chunkX, chunkY, spawners, dimensionId = OVERWORLD_ID)
673 {
674 const dimId = normalizeDimensionId(dimensionId);
675 const revisionId = this.worldDb.getEditorRevisionId();
676 const trees = new Map(
677 this.worldDb.listDialogueTrees(revisionId).map((raw) =>
678 {
679 const tree = normalizeDialogueTree(raw, this.#questConditionLookup());
680 return [tree.dialogueId, tree];
681 })
682 );
683 for (const entry of spawners ?? [])
684 {
685 const dialogueId = entry?.config?.dialogueId;
686 if (!dialogueId)
687 { continue; }
688 const tree = trees.get(dialogueId);
689 if (!tree)
690 {
691 const err = new Error(`Unknown dialogue "${dialogueId}" on a spawner.`);
692 err.userFacing = true;
693 throw err;
694 }
695 if (tree.unique && (Math.max(1, Number(entry.config.maxAlive) || 1) !== 1))
696 {
697 const err = new Error(`Unique dialogue "${dialogueId}" requires spawner maxAlive = 1.`);
698 err.userFacing = true;
699 throw err;
700 }
701 }
702 const counts = this.#countDialogueAssignments(revisionId, {
703 chunkX,
704 chunkY,
705 dimensionId: dimId,
706 spawners
707 });
708 for (const [dialogueId, tree] of trees)
709 {
710 const n = counts.get(dialogueId) ?? 0;
711 if (tree.unique && n > 1)
712 {
713 const err = new Error(`Unique dialogue "${dialogueId}" would be on ${n} spawners.`);
714 err.userFacing = true;
715 throw err;
716 }
717 }
718 }
719
720 #countDialogueAssignments (revisionId, replaceChunk = null)
721 {
722 const settings = this.worldDb.getLiveSettings();
723 const counts = new Map();
724 const coords = this.worldDb.listChunkCoords(revisionId);
725 for (const { chunk_x: cx, chunk_y: cy, dimension_id: dimensionId } of coords)
726 {
727 const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);
728 if (
729 replaceChunk
730 && cx === replaceChunk.chunkX
731 && cy === replaceChunk.chunkY
732 && dim === normalizeDimensionId(replaceChunk.dimensionId ?? OVERWORLD_ID)
733 )
734 { continue; }
735 const row = this.worldDb.getChunkVersion(cx, cy, revisionId, dim);
736 if (!row)
737 { continue; }
738 const data = decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, cx, cy);
739 for (const entry of data.spawners ?? [])
740 {
741 const id = entry?.config?.dialogueId;
742 if (!id)
743 { continue; }
744 counts.set(id, (counts.get(id) ?? 0) + 1);
745 }
746 }
747 if (replaceChunk?.spawners)
748 {
749 for (const entry of replaceChunk.spawners)
750 {
751 const id = entry?.config?.dialogueId;
752 if (!id)
753 { continue; }
754 counts.set(id, (counts.get(id) ?? 0) + 1);
755 }
756 }
757 return counts;
758 }
759
760 #uniqueDialogueMaxAliveViolation (revisionId, dialogueId)
761 {
762 const settings = this.worldDb.getLiveSettings();
763 const coords = this.worldDb.listChunkCoords(revisionId);
764 for (const { chunk_x: chunkX, chunk_y: chunkY, dimension_id: dimensionId } of coords)
765 {
766 const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);
767 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId, dim);
768 if (!row)
769 { continue; }
770 const data = decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, chunkX, chunkY);
771 for (const entry of data.spawners ?? [])
772 {
773 if (entry?.config?.dialogueId !== dialogueId)
774 { continue; }
775 const maxAlive = Math.max(1, Number(entry.config.maxAlive) || 1);
776 if (maxAlive !== 1)
777 { return `Unique dialogue "${dialogueId}" requires spawner maxAlive = 1.`; }
778 }
779 }
780 return null;
781 }
782
783 #loadForBake (chunkX, chunkY, revisionId, defaultGroundTypeId, savedX, savedY, savedData, dimensionId = OVERWORLD_ID)
784 {
785 if (chunkX === savedX && chunkY === savedY)
786 { return savedData; }
787
788 const dimId = normalizeDimensionId(dimensionId);
789 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId, dimId);
790 return row
791 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
792 : createEmptyChunkData(defaultGroundTypeId);
793 }
794}
795
796export function diffChunks (chunkX, chunkY, previous, next, previousAuthored)
797{
798 const bullets = [];
799 const prevOpen = previousAuthored ? !!previous.open : false;
800 if (prevOpen !== !!next.open)
801 { bullets.push(next.open ? "Chunk opened." : "Chunk closed."); }
802
803 for (let localY = 0; localY < CHUNK_SIZE; localY++)
804 {
805 for (let localX = 0; localX < CHUNK_SIZE; localX++)
806 {
807 const index = localY * CHUNK_SIZE + localX;
808 const tileX = localToTile(chunkX, localX);
809 const tileY = localToTile(chunkY, localY);
810 const prevGround = normalizeGround(previous.grounds[index]);
811 const nextGround = normalizeGround(next.grounds[index]);
812 if (prevGround.typeId !== nextGround.typeId)
813 {
814 bullets.push(
815 `Ground at ${tileX}, ${tileY} changed from ${nameGround(prevGround.typeId)} to ${nameGround(nextGround.typeId)}.`
816 );
817 }
818 else if ((prevGround.state ?? "") !== (nextGround.state ?? ""))
819 {
820 bullets.push(
821 `Ground ${nameGround(nextGround.typeId)} at ${tileX}, ${tileY} state changed from ${stateLabel(prevGround.state)} to ${stateLabel(nextGround.state)}.`
822 );
823 }
824
825 const prevBlock = normalizeBlock(previous.blocks[index]);
826 const nextBlock = normalizeBlock(next.blocks[index]);
827 const prevId = prevBlock?.typeId ?? null;
828 const nextId = nextBlock?.typeId ?? null;
829 const prevConfig = JSON.stringify(prevBlock?.config ?? null);
830 const nextConfig = JSON.stringify(nextBlock?.config ?? null);
831 if (prevId !== nextId || prevConfig !== nextConfig)
832 {
833 if (prevId == null && nextId != null)
834 { bullets.push(`Block ${nameBlock(nextId)} placed at ${tileX}, ${tileY}.`); }
835 else if (prevId != null && nextId == null)
836 { bullets.push(`Block ${nameBlock(prevId)} removed at ${tileX}, ${tileY}.`); }
837 else
838 { bullets.push(`Block at ${tileX}, ${tileY} changed from ${nameBlock(prevId)} to ${nameBlock(nextId)}.`); }
839 }
840 else if (prevBlock && nextBlock && (prevBlock.state ?? "") !== (nextBlock.state ?? ""))
841 {
842 bullets.push(
843 `Block ${nameBlock(nextId)} at ${tileX}, ${tileY} state changed from ${stateLabel(prevBlock.state)} to ${stateLabel(nextBlock.state)}.`
844 );
845 }
846 }
847 }
848
849 const prevSpawners = indexSpawners(previous.spawners);
850 const nextSpawners = indexSpawners(next.spawners);
851 for (const key of new Set([...prevSpawners.keys(), ...nextSpawners.keys()]))
852 {
853 const prev = prevSpawners.get(key);
854 const cur = nextSpawners.get(key);
855 const [localX, localY] = key.split(",").map(Number);
856 const tileX = localToTile(chunkX, localX);
857 const tileY = localToTile(chunkY, localY);
858 const prevConfig = JSON.stringify(prev?.config ?? null);
859 const nextConfig = JSON.stringify(cur?.config ?? null);
860 if (!prev && cur)
861 { bullets.push(`Spawner (${cur.config.mobTypeId}) placed at ${tileX}, ${tileY}.`); }
862 else if (prev && !cur)
863 { bullets.push(`Spawner removed at ${tileX}, ${tileY}.`); }
864 else if (prevConfig !== nextConfig)
865 { bullets.push(`Spawner at ${tileX}, ${tileY} config changed.`); }
866 }
867 return bullets;
868}
869
870export function diffQuests (previous, next)
871{
872 if (!previous)
873 { return [`Quest "${next.title}" (${next.questId}) created.`]; }
874 if (JSON.stringify(previous) === JSON.stringify(next))
875 { return []; }
876 const bullets = [];
877 if (previous.title !== next.title)
878 { bullets.push(`Title: "${previous.title}" → "${next.title}".`); }
879 if (previous.description !== next.description)
880 { bullets.push("Description changed."); }
881 if (!!previous.cancelable !== !!next.cancelable)
882 { bullets.push(`Cancelable: ${previous.cancelable ? "yes" : "no"} → ${next.cancelable ? "yes" : "no"}.`); }
883 if (JSON.stringify(previous.rewards) !== JSON.stringify(next.rewards))
884 { bullets.push("Quest rewards changed."); }
885
886 const prevSteps = new Map((previous.steps ?? []).map((step) => [step.stepId, step]));
887 const nextSteps = new Map((next.steps ?? []).map((step) => [step.stepId, step]));
888 for (const stepId of new Set([...prevSteps.keys(), ...nextSteps.keys()]))
889 {
890 const prev = prevSteps.get(stepId);
891 const cur = nextSteps.get(stepId);
892 if (!prev && cur)
893 { bullets.push(`Step "${cur.title}" (${stepId}) added.`); }
894 else if (prev && !cur)
895 { bullets.push(`Step "${prev.title}" (${stepId}) removed.`); }
896 else if (JSON.stringify(prev) !== JSON.stringify(cur))
897 { bullets.push(`Step "${cur.title}" (${stepId}) updated.`); }
898 }
899 if (bullets.length === 0)
900 { bullets.push(`Quest "${next.questId}" updated.`); }
901 return bullets;
902}
903
904export function diffDialogues (previous, next)
905{
906 if (!previous)
907 { return [`Dialogue "${next.label}" (${next.dialogueId}) created.`]; }
908 if (JSON.stringify(previous) === JSON.stringify(next))
909 { return []; }
910 const bullets = [];
911 if (previous.label !== next.label)
912 { bullets.push(`Label: "${previous.label}" → "${next.label}".`); }
913 if (!!previous.unique !== !!next.unique)
914 { bullets.push(`Unique: ${previous.unique ? "yes" : "no"} → ${next.unique ? "yes" : "no"}.`); }
915 if (previous.entryStepId !== next.entryStepId)
916 { bullets.push(`Entry step: ${previous.entryStepId} → ${next.entryStepId}.`); }
917
918 const prevSteps = new Map((previous.steps ?? []).map((step) => [step.stepId, step]));
919 const nextSteps = new Map((next.steps ?? []).map((step) => [step.stepId, step]));
920 for (const stepId of new Set([...prevSteps.keys(), ...nextSteps.keys()]))
921 {
922 const prev = prevSteps.get(stepId);
923 const cur = nextSteps.get(stepId);
924 if (!prev && cur)
925 { bullets.push(`Step "${cur.label}" (${stepId}) added.`); }
926 else if (prev && !cur)
927 { bullets.push(`Step "${prev.label}" (${stepId}) removed.`); }
928 else if (JSON.stringify(prev) !== JSON.stringify(cur))
929 { bullets.push(`Step "${cur.label}" (${stepId}) updated.`); }
930 }
931 if (bullets.length === 0)
932 { bullets.push(`Dialogue "${next.dialogueId}" updated.`); }
933 return bullets;
934}
935
936function indexSpawners (spawners)
937{
938 const map = new Map();
939 for (const entry of spawners ?? [])
940 { map.set(`${entry.localX},${entry.localY}`, entry); }
941 return map;
942}
943
944function nameGround (typeId)
945{
946 return groundDefinition(typeId)?.displayName ?? `ground ${typeId}`;
947}
948
949function nameBlock (typeId)
950{
951 return blockDefinition(typeId)?.displayName ?? `block ${typeId}`;
952}
953
954function stateLabel (state)
955{
956 return state || "default";
957}