BlueGit

timfa questward

Files

questward / server / src / editor / service.js

service.js

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