BlueGit

timfa questward

Files

questward / server / src / editor / service.js

service.js

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