BlueGit

timfa questward

Files

questward / server / src / editor / service.js

service.js

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