BlueGit

timfa questward

Files

questward / server / src / editor / service.js

service.js

service.js 30.1 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
451 /** Flat list of authored spawners across all editor-revision chunks. */
452 listSpawners ()
453 {
454 const revisionId = this.worldDb.getEditorRevisionId();
455 const settings = this.worldDb.getLiveSettings();
456 const out = [];
457 const seen = new Set();
458 for (const { chunk_x: cx, chunk_y: cy, dimension_id: dimensionId } of this.worldDb.listChunkCoords(revisionId))
459 {
460 const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);
461 const row = this.worldDb.getChunkVersion(cx, cy, revisionId, dim);
462 if (!row)
463 { continue; }
464 const data = decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, cx, cy);
465 for (const entry of data.spawners ?? [])
466 {
467 const config = entry?.config;
468 const spawnerId = String(config?.spawnerId ?? "").trim();
469 if (!spawnerId || seen.has(spawnerId))
470 { continue; }
471 seen.add(spawnerId);
472 out.push({
473 spawnerId,
474 mobTypeId: config.mobTypeId ?? null,
475 dimensionId: dim,
476 tileX: localToTile(cx, entry.localX),
477 tileY: localToTile(cy, entry.localY)
478 });
479 }
480 }
481 out.sort((a, b) => String(a.spawnerId).localeCompare(String(b.spawnerId)));
482 return out;
483 }
484
485 loadQuests ()
486 {
487 const revisionId = this.worldDb.getEditorRevisionId();
488 const quests = this.worldDb.listQuestDefs(revisionId).map((raw) => normalizeQuestDef(raw));
489 return {
490 revisionId,
491 pendingRevisionId: this.worldDb.getPendingRevisionId(),
492 activeRevisionId: this.worldDb.getActiveRevisionId(),
493 quests,
494 spawners: this.listSpawners(),
495 changelog: this.#enrichChangelog(this.worldDb.listQuestChangelog())
496 };
497 }
498
499 saveQuest (raw, editorAdminId)
500 {
501 const def = normalizeQuestDef(raw);
502 const revisionId = this.worldDb.getEditorRevisionId();
503 const previousRaw = this.worldDb.getQuestDef(revisionId, def.questId);
504 const previous = previousRaw ? normalizeQuestDef(previousRaw) : null;
505 const bullets = diffQuests(previous, def);
506 const pendingId = this.worldDb.ensurePendingRevision(editorAdminId);
507 this.worldDb.saveQuestDef(pendingId, def);
508 if (bullets.length > 0)
509 { this.worldDb.appendQuestChangelog(def.questId, pendingId, editorAdminId, bullets); }
510 return this.loadQuests();
511 }
512
513 deleteQuest (questId, editorAdminId)
514 {
515 const id = String(questId);
516 const revisionId = this.worldDb.getEditorRevisionId();
517 const previousRaw = this.worldDb.getQuestDef(revisionId, id);
518 const pendingId = this.worldDb.ensurePendingRevision(editorAdminId);
519 this.worldDb.deleteQuestDef(pendingId, id);
520 if (previousRaw)
521 {
522 const previous = normalizeQuestDef(previousRaw);
523 this.worldDb.appendQuestChangelog(id, pendingId, editorAdminId, [
524 `Quest "${previous.title}" (${id}) deleted.`
525 ]);
526 }
527 return this.loadQuests();
528 }
529
530 loadDialogues ()
531 {
532 const revisionId = this.worldDb.getEditorRevisionId();
533 const trees = this.worldDb.listDialogueTrees(revisionId).map((raw) => normalizeDialogueTree(raw));
534 const assignmentCounts = this.#countDialogueAssignments(revisionId);
535 return {
536 revisionId,
537 pendingRevisionId: this.worldDb.getPendingRevisionId(),
538 activeRevisionId: this.worldDb.getActiveRevisionId(),
539 dialogues: trees.map((tree) => ({
540 ...tree,
541 assignedSpawnerCount: assignmentCounts.get(tree.dialogueId) ?? 0
542 })),
543 changelog: this.#enrichChangelog(this.worldDb.listDialogueChangelog())
544 };
545 }
546
547 saveDialogue (raw, editorAdminId)
548 {
549 const tree = normalizeDialogueTree(raw);
550 const revisionId = this.worldDb.getEditorRevisionId();
551 const previousRaw = this.worldDb.getDialogueTree(revisionId, tree.dialogueId);
552 const previous = previousRaw ? normalizeDialogueTree(previousRaw) : null;
553 const assignmentCounts = this.#countDialogueAssignments(revisionId);
554 const assigned = assignmentCounts.get(tree.dialogueId) ?? 0;
555 if (tree.unique && assigned > 1)
556 {
557 const err = new Error("Unique dialogue can be assigned to at most one spawner.");
558 err.userFacing = true;
559 throw err;
560 }
561 if (tree.unique && assigned === 1)
562 {
563 const violation = this.#uniqueDialogueMaxAliveViolation(revisionId, tree.dialogueId);
564 if (violation)
565 {
566 const err = new Error(violation);
567 err.userFacing = true;
568 throw err;
569 }
570 }
571 const bullets = diffDialogues(previous, tree);
572 const pendingId = this.worldDb.ensurePendingRevision(editorAdminId);
573 this.worldDb.saveDialogueTree(pendingId, tree);
574 if (bullets.length > 0)
575 { this.worldDb.appendDialogueChangelog(tree.dialogueId, pendingId, editorAdminId, bullets); }
576 return this.loadDialogues();
577 }
578
579 deleteDialogue (dialogueId, editorAdminId)
580 {
581 const id = String(dialogueId);
582 const revisionId = this.worldDb.getEditorRevisionId();
583 const assigned = this.#countDialogueAssignments(revisionId).get(id) ?? 0;
584 if (assigned > 0)
585 {
586 const err = new Error(`Dialogue is still assigned to ${assigned} spawner(s). Unassign first.`);
587 err.userFacing = true;
588 throw err;
589 }
590 const previousRaw = this.worldDb.getDialogueTree(revisionId, id);
591 const pendingId = this.worldDb.ensurePendingRevision(editorAdminId);
592 this.worldDb.deleteDialogueTree(pendingId, id);
593 if (previousRaw)
594 {
595 const previous = normalizeDialogueTree(previousRaw);
596 this.worldDb.appendDialogueChangelog(id, pendingId, editorAdminId, [
597 `Dialogue "${previous.label}" (${id}) deleted.`
598 ]);
599 }
600 return this.loadDialogues();
601 }
602
603 /** Validate dialogueId / unique / maxAlive when saving a chunk's spawners. */
604 validateSpawnerDialogues (chunkX, chunkY, spawners, dimensionId = OVERWORLD_ID)
605 {
606 const dimId = normalizeDimensionId(dimensionId);
607 const revisionId = this.worldDb.getEditorRevisionId();
608 const trees = new Map(
609 this.worldDb.listDialogueTrees(revisionId).map((raw) =>
610 {
611 const tree = normalizeDialogueTree(raw);
612 return [tree.dialogueId, tree];
613 })
614 );
615 for (const entry of spawners ?? [])
616 {
617 const dialogueId = entry?.config?.dialogueId;
618 if (!dialogueId)
619 { continue; }
620 const tree = trees.get(dialogueId);
621 if (!tree)
622 {
623 const err = new Error(`Unknown dialogue "${dialogueId}" on a spawner.`);
624 err.userFacing = true;
625 throw err;
626 }
627 if (tree.unique && (Math.max(1, Number(entry.config.maxAlive) || 1) !== 1))
628 {
629 const err = new Error(`Unique dialogue "${dialogueId}" requires spawner maxAlive = 1.`);
630 err.userFacing = true;
631 throw err;
632 }
633 }
634 const counts = this.#countDialogueAssignments(revisionId, {
635 chunkX,
636 chunkY,
637 dimensionId: dimId,
638 spawners
639 });
640 for (const [dialogueId, tree] of trees)
641 {
642 const n = counts.get(dialogueId) ?? 0;
643 if (tree.unique && n > 1)
644 {
645 const err = new Error(`Unique dialogue "${dialogueId}" would be on ${n} spawners.`);
646 err.userFacing = true;
647 throw err;
648 }
649 }
650 }
651
652 #countDialogueAssignments (revisionId, replaceChunk = null)
653 {
654 const settings = this.worldDb.getLiveSettings();
655 const counts = new Map();
656 const coords = this.worldDb.listChunkCoords(revisionId);
657 for (const { chunk_x: cx, chunk_y: cy, dimension_id: dimensionId } of coords)
658 {
659 const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);
660 if (
661 replaceChunk
662 && cx === replaceChunk.chunkX
663 && cy === replaceChunk.chunkY
664 && dim === normalizeDimensionId(replaceChunk.dimensionId ?? OVERWORLD_ID)
665 )
666 { continue; }
667 const row = this.worldDb.getChunkVersion(cx, cy, revisionId, dim);
668 if (!row)
669 { continue; }
670 const data = decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, cx, cy);
671 for (const entry of data.spawners ?? [])
672 {
673 const id = entry?.config?.dialogueId;
674 if (!id)
675 { continue; }
676 counts.set(id, (counts.get(id) ?? 0) + 1);
677 }
678 }
679 if (replaceChunk?.spawners)
680 {
681 for (const entry of replaceChunk.spawners)
682 {
683 const id = entry?.config?.dialogueId;
684 if (!id)
685 { continue; }
686 counts.set(id, (counts.get(id) ?? 0) + 1);
687 }
688 }
689 return counts;
690 }
691
692 #uniqueDialogueMaxAliveViolation (revisionId, dialogueId)
693 {
694 const settings = this.worldDb.getLiveSettings();
695 const coords = this.worldDb.listChunkCoords(revisionId);
696 for (const { chunk_x: chunkX, chunk_y: chunkY, dimension_id: dimensionId } of coords)
697 {
698 const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);
699 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId, dim);
700 if (!row)
701 { continue; }
702 const data = decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, chunkX, chunkY);
703 for (const entry of data.spawners ?? [])
704 {
705 if (entry?.config?.dialogueId !== dialogueId)
706 { continue; }
707 const maxAlive = Math.max(1, Number(entry.config.maxAlive) || 1);
708 if (maxAlive !== 1)
709 { return `Unique dialogue "${dialogueId}" requires spawner maxAlive = 1.`; }
710 }
711 }
712 return null;
713 }
714
715 #loadForBake (chunkX, chunkY, revisionId, defaultGroundTypeId, savedX, savedY, savedData, dimensionId = OVERWORLD_ID)
716 {
717 if (chunkX === savedX && chunkY === savedY)
718 { return savedData; }
719
720 const dimId = normalizeDimensionId(dimensionId);
721 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId, dimId);
722 return row
723 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
724 : createEmptyChunkData(defaultGroundTypeId);
725 }
726}
727
728export function diffChunks (chunkX, chunkY, previous, next, previousAuthored)
729{
730 const bullets = [];
731 const prevOpen = previousAuthored ? !!previous.open : false;
732 if (prevOpen !== !!next.open)
733 { bullets.push(next.open ? "Chunk opened." : "Chunk closed."); }
734
735 for (let localY = 0; localY < CHUNK_SIZE; localY++)
736 {
737 for (let localX = 0; localX < CHUNK_SIZE; localX++)
738 {
739 const index = localY * CHUNK_SIZE + localX;
740 const tileX = localToTile(chunkX, localX);
741 const tileY = localToTile(chunkY, localY);
742 const prevGround = normalizeGround(previous.grounds[index]);
743 const nextGround = normalizeGround(next.grounds[index]);
744 if (prevGround.typeId !== nextGround.typeId)
745 {
746 bullets.push(
747 `Ground at ${tileX}, ${tileY} changed from ${nameGround(prevGround.typeId)} to ${nameGround(nextGround.typeId)}.`
748 );
749 }
750 else if ((prevGround.state ?? "") !== (nextGround.state ?? ""))
751 {
752 bullets.push(
753 `Ground ${nameGround(nextGround.typeId)} at ${tileX}, ${tileY} state changed from ${stateLabel(prevGround.state)} to ${stateLabel(nextGround.state)}.`
754 );
755 }
756
757 const prevBlock = normalizeBlock(previous.blocks[index]);
758 const nextBlock = normalizeBlock(next.blocks[index]);
759 const prevId = prevBlock?.typeId ?? null;
760 const nextId = nextBlock?.typeId ?? null;
761 const prevConfig = JSON.stringify(prevBlock?.config ?? null);
762 const nextConfig = JSON.stringify(nextBlock?.config ?? null);
763 if (prevId !== nextId || prevConfig !== nextConfig)
764 {
765 if (prevId == null && nextId != null)
766 { bullets.push(`Block ${nameBlock(nextId)} placed at ${tileX}, ${tileY}.`); }
767 else if (prevId != null && nextId == null)
768 { bullets.push(`Block ${nameBlock(prevId)} removed at ${tileX}, ${tileY}.`); }
769 else
770 { bullets.push(`Block at ${tileX}, ${tileY} changed from ${nameBlock(prevId)} to ${nameBlock(nextId)}.`); }
771 }
772 else if (prevBlock && nextBlock && (prevBlock.state ?? "") !== (nextBlock.state ?? ""))
773 {
774 bullets.push(
775 `Block ${nameBlock(nextId)} at ${tileX}, ${tileY} state changed from ${stateLabel(prevBlock.state)} to ${stateLabel(nextBlock.state)}.`
776 );
777 }
778 }
779 }
780
781 const prevSpawners = indexSpawners(previous.spawners);
782 const nextSpawners = indexSpawners(next.spawners);
783 for (const key of new Set([...prevSpawners.keys(), ...nextSpawners.keys()]))
784 {
785 const prev = prevSpawners.get(key);
786 const cur = nextSpawners.get(key);
787 const [localX, localY] = key.split(",").map(Number);
788 const tileX = localToTile(chunkX, localX);
789 const tileY = localToTile(chunkY, localY);
790 const prevConfig = JSON.stringify(prev?.config ?? null);
791 const nextConfig = JSON.stringify(cur?.config ?? null);
792 if (!prev && cur)
793 { bullets.push(`Spawner (${cur.config.mobTypeId}) placed at ${tileX}, ${tileY}.`); }
794 else if (prev && !cur)
795 { bullets.push(`Spawner removed at ${tileX}, ${tileY}.`); }
796 else if (prevConfig !== nextConfig)
797 { bullets.push(`Spawner at ${tileX}, ${tileY} config changed.`); }
798 }
799 return bullets;
800}
801
802export function diffQuests (previous, next)
803{
804 if (!previous)
805 { return [`Quest "${next.title}" (${next.questId}) created.`]; }
806 if (JSON.stringify(previous) === JSON.stringify(next))
807 { return []; }
808 const bullets = [];
809 if (previous.title !== next.title)
810 { bullets.push(`Title: "${previous.title}" → "${next.title}".`); }
811 if (previous.description !== next.description)
812 { bullets.push("Description changed."); }
813 if (!!previous.cancelable !== !!next.cancelable)
814 { bullets.push(`Cancelable: ${previous.cancelable ? "yes" : "no"} → ${next.cancelable ? "yes" : "no"}.`); }
815 if (JSON.stringify(previous.rewards) !== JSON.stringify(next.rewards))
816 { bullets.push("Quest rewards changed."); }
817
818 const prevSteps = new Map((previous.steps ?? []).map((step) => [step.stepId, step]));
819 const nextSteps = new Map((next.steps ?? []).map((step) => [step.stepId, step]));
820 for (const stepId of new Set([...prevSteps.keys(), ...nextSteps.keys()]))
821 {
822 const prev = prevSteps.get(stepId);
823 const cur = nextSteps.get(stepId);
824 if (!prev && cur)
825 { bullets.push(`Step "${cur.title}" (${stepId}) added.`); }
826 else if (prev && !cur)
827 { bullets.push(`Step "${prev.title}" (${stepId}) removed.`); }
828 else if (JSON.stringify(prev) !== JSON.stringify(cur))
829 { bullets.push(`Step "${cur.title}" (${stepId}) updated.`); }
830 }
831 if (bullets.length === 0)
832 { bullets.push(`Quest "${next.questId}" updated.`); }
833 return bullets;
834}
835
836export function diffDialogues (previous, next)
837{
838 if (!previous)
839 { return [`Dialogue "${next.label}" (${next.dialogueId}) created.`]; }
840 if (JSON.stringify(previous) === JSON.stringify(next))
841 { return []; }
842 const bullets = [];
843 if (previous.label !== next.label)
844 { bullets.push(`Label: "${previous.label}" → "${next.label}".`); }
845 if (!!previous.unique !== !!next.unique)
846 { bullets.push(`Unique: ${previous.unique ? "yes" : "no"} → ${next.unique ? "yes" : "no"}.`); }
847 if (previous.entryStepId !== next.entryStepId)
848 { bullets.push(`Entry step: ${previous.entryStepId} → ${next.entryStepId}.`); }
849
850 const prevSteps = new Map((previous.steps ?? []).map((step) => [step.stepId, step]));
851 const nextSteps = new Map((next.steps ?? []).map((step) => [step.stepId, step]));
852 for (const stepId of new Set([...prevSteps.keys(), ...nextSteps.keys()]))
853 {
854 const prev = prevSteps.get(stepId);
855 const cur = nextSteps.get(stepId);
856 if (!prev && cur)
857 { bullets.push(`Step "${cur.label}" (${stepId}) added.`); }
858 else if (prev && !cur)
859 { bullets.push(`Step "${prev.label}" (${stepId}) removed.`); }
860 else if (JSON.stringify(prev) !== JSON.stringify(cur))
861 { bullets.push(`Step "${cur.label}" (${stepId}) updated.`); }
862 }
863 if (bullets.length === 0)
864 { bullets.push(`Dialogue "${next.dialogueId}" updated.`); }
865 return bullets;
866}
867
868function indexSpawners (spawners)
869{
870 const map = new Map();
871 for (const entry of spawners ?? [])
872 { map.set(`${entry.localX},${entry.localY}`, entry); }
873 return map;
874}
875
876function nameGround (typeId)
877{
878 return groundDefinition(typeId)?.displayName ?? `ground ${typeId}`;
879}
880
881function nameBlock (typeId)
882{
883 return blockDefinition(typeId)?.displayName ?? `block ${typeId}`;
884}
885
886function stateLabel (state)
887{
888 return state || "default";
889}