BlueGit

timfa questward

Files

questward / server / src / editor / service.js

service.js

lots of things
timfa Tim Falken · pushed by timfa · 2 months ago
07a95f71 History
service.js 22.0 KiB Download Raw
1import { groundDefinition, blockDefinition, normalizeGround, normalizeBlock } 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 { BLOCK_DEFINITIONS } from "../../../shared/definitions/tiles.js";
6import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.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 normalizeEquipmentStatBonuses,
19 diffEquipmentStatBonuses,
20 equipmentStatBonusMapsEqual
21} from "../../../shared/definitions/equipmentStatCategories.js";
22import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js";
23import {
24 OVERWORLD_ID,
25 normalizeDimensionId,
26 normalizeDimensionRecord,
27 defaultDimensionRecord,
28 isOverworld,
29 normalizeLightingMode,
30 normalizeSeasonMode
31} from "../../../shared/world/dimensions.js";
32
33export class EditorService
34{
35 constructor (worldDb)
36 {
37 this.worldDb = worldDb;
38 }
39
40 #defaultGroundForDimension (dimensionId, revisionId = null)
41 {
42 const rev = revisionId ?? this.worldDb.getEditorRevisionId();
43 const dimId = normalizeDimensionId(dimensionId);
44 const settings = this.worldDb.getLiveSettings();
45 const record = this.worldDb.getDimension(rev, dimId)
46 ?? defaultDimensionRecord(dimId, { defaultGroundTypeId: settings.defaultGroundTypeId });
47 return record.defaultGroundTypeId;
48 }
49
50 loadChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
51 {
52 const dimId = normalizeDimensionId(dimensionId);
53 const revisionId = this.worldDb.getEditorRevisionId();
54 const settings = this.worldDb.getLiveSettings();
55 const defaultGroundTypeId = this.#defaultGroundForDimension(dimId, revisionId);
56 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId, dimId);
57 const data = row
58 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
59 : createEmptyChunkData(defaultGroundTypeId);
60 const isOpen = (x, y) =>
61 {
62 const neighbor = this.worldDb.getChunkVersion(x, y, revisionId, dimId);
63 if (!neighbor)
64 { return false; }
65 return !!decodeChunkBlob(neighbor.data_blob, defaultGroundTypeId, x, y).open;
66 };
67 return {
68 chunkX,
69 chunkY,
70 dimensionId: dimId,
71 revisionId,
72 pendingRevisionId: this.worldDb.getPendingRevisionId(),
73 activeRevisionId: this.worldDb.getActiveRevisionId(),
74 authored: !!row,
75 settings,
76 data,
77 closedEdges: closedNeighborEdges(chunkX, chunkY, isOpen),
78 changelog: this.worldDb.listChangelog(chunkX, chunkY, dimId)
79 };
80 }
81
82 saveChunk (chunkX, chunkY, draft, editorAdminId, dimensionId = OVERWORLD_ID)
83 {
84 const dimId = normalizeDimensionId(dimensionId);
85 const previous = this.loadChunk(chunkX, chunkY, dimId);
86 const next = cloneChunkData(previous.data);
87 const defaultGroundTypeId = this.#defaultGroundForDimension(dimId);
88 next.open = !!draft.open;
89 if (Array.isArray(draft.grounds))
90 { next.grounds = draft.grounds.map((ground) => normalizeGround(ground, defaultGroundTypeId)); }
91 if (Array.isArray(draft.blocks))
92 { next.blocks = draft.blocks.map((block) => normalizeBlock(block)); }
93 if (Array.isArray(draft.spawners))
94 { next.spawners = draft.spawners.map((entry) => normalizeSpawner(entry)).filter(Boolean); }
95
96 this.validateSpawnerDialogues(chunkX, chunkY, next.spawners);
97
98 const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored);
99 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
100 const baked = bakeLightMaps(
101 chunkX,
102 chunkY,
103 (x, y) => this.#loadForBake(x, y, revisionId, defaultGroundTypeId, chunkX, chunkY, next, dimId),
104 maxDefinitionLightRange(BLOCK_DEFINITIONS)
105 );
106
107 for (const result of baked)
108 {
109 const shouldStore = result.chunkX === chunkX && result.chunkY === chunkY
110 || this.worldDb.getChunkVersion(result.chunkX, result.chunkY, revisionId, dimId)
111 || result.data.light.some((value) => value > 0);
112
113 if (!shouldStore)
114 { continue; }
115
116 this.worldDb.saveChunkVersion(
117 result.chunkX,
118 result.chunkY,
119 revisionId,
120 result.data.open ? 1 : 0,
121 encodeChunkBlob(result.data),
122 dimId
123 );
124 }
125
126 if (diffEntries.length > 0)
127 { this.worldDb.appendChangelog(chunkX, chunkY, revisionId, editorAdminId, diffEntries, dimId); }
128
129 return this.loadChunk(chunkX, chunkY, dimId);
130 }
131
132 listDimensions ()
133 {
134 const revisionId = this.worldDb.getEditorRevisionId();
135 return {
136 revisionId,
137 pendingRevisionId: this.worldDb.getPendingRevisionId(),
138 activeRevisionId: this.worldDb.getActiveRevisionId(),
139 dimensions: this.worldDb.listDimensions(revisionId)
140 };
141 }
142
143 createDimension (rawId, displayName, editorAdminId)
144 {
145 const trimmed = String(rawId ?? "").trim();
146 if (!trimmed)
147 {
148 const err = new Error("Dimension id is required.");
149 err.userFacing = true;
150 throw err;
151 }
152 const dimensionId = normalizeDimensionId(trimmed);
153 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
154 if (this.worldDb.getDimension(revisionId, dimensionId))
155 {
156 const err = new Error(`Dimension "${dimensionId}" already exists.`);
157 err.userFacing = true;
158 throw err;
159 }
160 const settings = this.worldDb.getLiveSettings();
161 const record = defaultDimensionRecord(dimensionId, {
162 displayName: displayName != null && String(displayName).trim()
163 ? String(displayName).trim()
164 : dimensionId,
165 defaultGroundTypeId: settings.defaultGroundTypeId
166 });
167 this.worldDb.saveDimension(revisionId, record);
168 return this.listDimensions();
169 }
170
171 saveDimension (raw, editorAdminId)
172 {
173 if (!raw || typeof raw !== "object")
174 {
175 const err = new Error("Dimension payload required.");
176 err.userFacing = true;
177 throw err;
178 }
179 const dimensionId = normalizeDimensionId(raw.dimensionId);
180 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
181 const settings = this.worldDb.getLiveSettings();
182 const existing = this.worldDb.getDimension(revisionId, dimensionId)
183 ?? defaultDimensionRecord(dimensionId, { defaultGroundTypeId: settings.defaultGroundTypeId });
184 const next = normalizeDimensionRecord({
185 ...existing,
186 displayName: Object.prototype.hasOwnProperty.call(raw, "displayName")
187 ? raw.displayName
188 : existing.displayName,
189 lightingMode: Object.prototype.hasOwnProperty.call(raw, "lightingMode")
190 ? normalizeLightingMode(raw.lightingMode)
191 : existing.lightingMode,
192 seasonMode: Object.prototype.hasOwnProperty.call(raw, "seasonMode")
193 ? normalizeSeasonMode(raw.seasonMode)
194 : existing.seasonMode,
195 defaultGroundTypeId: Object.prototype.hasOwnProperty.call(raw, "defaultGroundTypeId")
196 ? raw.defaultGroundTypeId
197 : existing.defaultGroundTypeId,
198 deletedAt: existing.deletedAt,
199 purgeAfter: existing.purgeAfter
200 });
201 this.worldDb.saveDimension(revisionId, next);
202 return this.listDimensions();
203 }
204
205 softDeleteDimension (dimensionId, editorAdminId)
206 {
207 const id = normalizeDimensionId(dimensionId);
208 if (isOverworld(id))
209 {
210 const err = new Error("Cannot delete overworld.");
211 err.userFacing = true;
212 throw err;
213 }
214 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
215 const result = this.worldDb.softDeleteDimension(revisionId, id);
216 if (!result.ok)
217 {
218 const err = new Error(result.error ?? "Delete failed.");
219 err.userFacing = true;
220 throw err;
221 }
222 return this.listDimensions();
223 }
224
225 cancelDimensionDeletion (dimensionId, editorAdminId)
226 {
227 const id = normalizeDimensionId(dimensionId);
228 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
229 const result = this.worldDb.cancelDimensionDeletion(revisionId, id);
230 if (!result.ok)
231 {
232 const err = new Error(result.error ?? "Cancel failed.");
233 err.userFacing = true;
234 throw err;
235 }
236 return this.listDimensions();
237 }
238
239 loadSettings ()
240 {
241 return {
242 settings: this.worldDb.getLiveSettings(),
243 changelog: this.worldDb.listSettingsChangelog()
244 };
245 }
246
247 saveSettings (partial, editorAdminId)
248 {
249 const current = this.worldDb.getLiveSettings();
250 const next = {
251 ...current,
252 itemSeedValues: {
253 ...(current.itemSeedValues && typeof current.itemSeedValues === "object"
254 ? current.itemSeedValues
255 : {})
256 }
257 };
258 for (const field of allSettingFields())
259 {
260 if (!Object.prototype.hasOwnProperty.call(partial, field.key))
261 { continue; }
262 const value = coerceSettingValue(field, partial[field.key]);
263 if (value == null)
264 { continue; }
265 next[field.key] = value;
266 }
267 if (Object.prototype.hasOwnProperty.call(partial, "itemSeedValues"))
268 {
269 next.itemSeedValues = normalizeItemSeedValues(partial.itemSeedValues);
270 }
271 if (Object.prototype.hasOwnProperty.call(partial, "starterEquipment")
272 || Object.prototype.hasOwnProperty.call(partial, "starterInventory"))
273 {
274 const loadout = normalizeStarterLoadout({
275 starterEquipment: Object.prototype.hasOwnProperty.call(partial, "starterEquipment")
276 ? partial.starterEquipment
277 : current.starterEquipment,
278 starterInventory: Object.prototype.hasOwnProperty.call(partial, "starterInventory")
279 ? partial.starterInventory
280 : current.starterInventory
281 });
282 next.starterEquipment = loadout.equipment;
283 next.starterInventory = loadout.inventory;
284 }
285 if (Object.prototype.hasOwnProperty.call(partial, "equipmentStatBonuses"))
286 {
287 next.equipmentStatBonuses = normalizeEquipmentStatBonuses(partial.equipmentStatBonuses);
288 }
289 else
290 {
291 next.equipmentStatBonuses = normalizeEquipmentStatBonuses(current.equipmentStatBonuses);
292 }
293 const { bullets: scalarBullets, changed } = diffSettings(current, next);
294 const seedBullets = Object.prototype.hasOwnProperty.call(partial, "itemSeedValues")
295 ? diffItemSeedValues(
296 normalizeItemSeedValues(current.itemSeedValues),
297 next.itemSeedValues,
298 (itemId) => itemDefinition(itemId)?.displayName ?? null
299 )
300 : [];
301 if (!itemSeedMapsEqual(current.itemSeedValues, next.itemSeedValues)
302 && Object.prototype.hasOwnProperty.call(partial, "itemSeedValues"))
303 {
304 changed.itemSeedValues = next.itemSeedValues;
305 }
306 const starterChanged = !starterLoadoutsEqual(current, next)
307 && (Object.prototype.hasOwnProperty.call(partial, "starterEquipment")
308 || Object.prototype.hasOwnProperty.call(partial, "starterInventory"));
309 if (starterChanged)
310 {
311 changed.starterEquipment = next.starterEquipment;
312 changed.starterInventory = next.starterInventory;
313 }
314 const starterBullets = starterChanged
315 ? diffStarterLoadout(current, next)
316 : [];
317 const equipmentStatsChanged = Object.prototype.hasOwnProperty.call(partial, "equipmentStatBonuses")
318 && !equipmentStatBonusMapsEqual(current.equipmentStatBonuses, next.equipmentStatBonuses);
319 if (equipmentStatsChanged)
320 { changed.equipmentStatBonuses = next.equipmentStatBonuses; }
321 const equipmentStatBullets = equipmentStatsChanged
322 ? diffEquipmentStatBonuses(
323 current.equipmentStatBonuses,
324 next.equipmentStatBonuses,
325 (itemId) => itemDefinition(itemId)?.displayName ?? null
326 )
327 : [];
328 const bullets = [...scalarBullets, ...seedBullets, ...starterBullets, ...equipmentStatBullets];
329 if (Object.keys(changed).length === 0)
330 {
331 return {
332 settings: current,
333 changelog: this.worldDb.listSettingsChangelog(),
334 changed: {}
335 };
336 }
337 const settings = {
338 ...current,
339 ...changed,
340 itemSeedValues: changed.itemSeedValues
341 ?? normalizeItemSeedValues(current.itemSeedValues)
342 ?? { ...(DEFAULT_WORLD_SETTINGS.itemSeedValues ?? {}) },
343 starterEquipment: changed.starterEquipment ?? current.starterEquipment
344 ?? DEFAULT_WORLD_SETTINGS.starterEquipment,
345 starterInventory: changed.starterInventory ?? current.starterInventory
346 ?? DEFAULT_WORLD_SETTINGS.starterInventory,
347 equipmentStatBonuses: changed.equipmentStatBonuses
348 ?? normalizeEquipmentStatBonuses(current.equipmentStatBonuses)
349 };
350 const normalized = normalizeStarterLoadout(settings);
351 settings.starterEquipment = normalized.equipment;
352 settings.starterInventory = normalized.inventory;
353 this.worldDb.saveLiveSettings(settings, editorAdminId);
354 this.worldDb.appendSettingsChangelog(editorAdminId, bullets);
355 return {
356 settings,
357 changelog: this.worldDb.listSettingsChangelog(),
358 changed,
359 diffEntries: bullets
360 };
361 }
362
363 applyPendingRevision ()
364 {
365 return this.worldDb.promotePendingRevision();
366 }
367
368 revisionStatus ()
369 {
370 return {
371 activeRevisionId: this.worldDb.getActiveRevisionId(),
372 pendingRevisionId: this.worldDb.getPendingRevisionId()
373 };
374 }
375
376 loadQuests ()
377 {
378 const revisionId = this.worldDb.getEditorRevisionId();
379 const quests = this.worldDb.listQuestDefs(revisionId).map((raw) => normalizeQuestDef(raw));
380 return {
381 revisionId,
382 pendingRevisionId: this.worldDb.getPendingRevisionId(),
383 activeRevisionId: this.worldDb.getActiveRevisionId(),
384 quests
385 };
386 }
387
388 saveQuest (raw, editorAdminId)
389 {
390 const def = normalizeQuestDef(raw);
391 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
392 this.worldDb.saveQuestDef(revisionId, def);
393 return this.loadQuests();
394 }
395
396 deleteQuest (questId, editorAdminId)
397 {
398 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
399 this.worldDb.deleteQuestDef(revisionId, String(questId));
400 return this.loadQuests();
401 }
402
403 loadDialogues ()
404 {
405 const revisionId = this.worldDb.getEditorRevisionId();
406 const trees = this.worldDb.listDialogueTrees(revisionId).map((raw) => normalizeDialogueTree(raw));
407 const assignmentCounts = this.#countDialogueAssignments(revisionId);
408 return {
409 revisionId,
410 pendingRevisionId: this.worldDb.getPendingRevisionId(),
411 activeRevisionId: this.worldDb.getActiveRevisionId(),
412 dialogues: trees.map((tree) => ({
413 ...tree,
414 assignedSpawnerCount: assignmentCounts.get(tree.dialogueId) ?? 0
415 }))
416 };
417 }
418
419 saveDialogue (raw, editorAdminId)
420 {
421 const tree = normalizeDialogueTree(raw);
422 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
423 const assignmentCounts = this.#countDialogueAssignments(revisionId);
424 const assigned = assignmentCounts.get(tree.dialogueId) ?? 0;
425 if (tree.unique && assigned > 1)
426 {
427 const err = new Error("Unique dialogue can be assigned to at most one spawner.");
428 err.userFacing = true;
429 throw err;
430 }
431 if (tree.unique && assigned === 1)
432 {
433 const violation = this.#uniqueDialogueMaxAliveViolation(revisionId, tree.dialogueId);
434 if (violation)
435 {
436 const err = new Error(violation);
437 err.userFacing = true;
438 throw err;
439 }
440 }
441 this.worldDb.saveDialogueTree(revisionId, tree);
442 return this.loadDialogues();
443 }
444
445 deleteDialogue (dialogueId, editorAdminId)
446 {
447 const id = String(dialogueId);
448 const revisionId = this.worldDb.getEditorRevisionId();
449 const assigned = this.#countDialogueAssignments(revisionId).get(id) ?? 0;
450 if (assigned > 0)
451 {
452 const err = new Error(`Dialogue is still assigned to ${assigned} spawner(s). Unassign first.`);
453 err.userFacing = true;
454 throw err;
455 }
456 const pendingId = this.worldDb.ensurePendingRevision(editorAdminId);
457 this.worldDb.deleteDialogueTree(pendingId, id);
458 return this.loadDialogues();
459 }
460
461 /** Validate dialogueId / unique / maxAlive when saving a chunk's spawners. */
462 validateSpawnerDialogues (chunkX, chunkY, spawners)
463 {
464 const revisionId = this.worldDb.getEditorRevisionId();
465 const trees = new Map(
466 this.worldDb.listDialogueTrees(revisionId).map((raw) =>
467 {
468 const tree = normalizeDialogueTree(raw);
469 return [tree.dialogueId, tree];
470 })
471 );
472 for (const entry of spawners ?? [])
473 {
474 const dialogueId = entry?.config?.dialogueId;
475 if (!dialogueId)
476 { continue; }
477 const tree = trees.get(dialogueId);
478 if (!tree)
479 {
480 const err = new Error(`Unknown dialogue "${dialogueId}" on a spawner.`);
481 err.userFacing = true;
482 throw err;
483 }
484 if (tree.unique && (Math.max(1, Number(entry.config.maxAlive) || 1) !== 1))
485 {
486 const err = new Error(`Unique dialogue "${dialogueId}" requires spawner maxAlive = 1.`);
487 err.userFacing = true;
488 throw err;
489 }
490 }
491 const counts = this.#countDialogueAssignments(revisionId, { chunkX, chunkY, spawners });
492 for (const [dialogueId, tree] of trees)
493 {
494 const n = counts.get(dialogueId) ?? 0;
495 if (tree.unique && n > 1)
496 {
497 const err = new Error(`Unique dialogue "${dialogueId}" would be on ${n} spawners.`);
498 err.userFacing = true;
499 throw err;
500 }
501 }
502 }
503
504 #countDialogueAssignments (revisionId, replaceChunk = null)
505 {
506 const settings = this.worldDb.getLiveSettings();
507 const counts = new Map();
508 const coords = this.worldDb.listChunkCoords(revisionId);
509 for (const { chunk_x: cx, chunk_y: cy } of coords)
510 {
511 if (replaceChunk && cx === replaceChunk.chunkX && cy === replaceChunk.chunkY)
512 { continue; }
513 const row = this.worldDb.getChunkVersion(cx, cy, revisionId);
514 if (!row)
515 { continue; }
516 const data = decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, cx, cy);
517 for (const entry of data.spawners ?? [])
518 {
519 const id = entry?.config?.dialogueId;
520 if (!id)
521 { continue; }
522 counts.set(id, (counts.get(id) ?? 0) + 1);
523 }
524 }
525 if (replaceChunk?.spawners)
526 {
527 for (const entry of replaceChunk.spawners)
528 {
529 const id = entry?.config?.dialogueId;
530 if (!id)
531 { continue; }
532 counts.set(id, (counts.get(id) ?? 0) + 1);
533 }
534 }
535 return counts;
536 }
537
538 #uniqueDialogueMaxAliveViolation (revisionId, dialogueId)
539 {
540 const settings = this.worldDb.getLiveSettings();
541 const coords = this.worldDb.listChunkCoords(revisionId);
542 for (const { chunk_x: chunkX, chunk_y: chunkY } of coords)
543 {
544 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
545 if (!row)
546 { continue; }
547 const data = decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, chunkX, chunkY);
548 for (const entry of data.spawners ?? [])
549 {
550 if (entry?.config?.dialogueId !== dialogueId)
551 { continue; }
552 const maxAlive = Math.max(1, Number(entry.config.maxAlive) || 1);
553 if (maxAlive !== 1)
554 { return `Unique dialogue "${dialogueId}" requires spawner maxAlive = 1.`; }
555 }
556 }
557 return null;
558 }
559
560 #loadForBake (chunkX, chunkY, revisionId, defaultGroundTypeId, savedX, savedY, savedData, dimensionId = OVERWORLD_ID)
561 {
562 if (chunkX === savedX && chunkY === savedY)
563 { return savedData; }
564
565 const dimId = normalizeDimensionId(dimensionId);
566 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId, dimId);
567 return row
568 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
569 : createEmptyChunkData(defaultGroundTypeId);
570 }
571}
572
573export function diffChunks (chunkX, chunkY, previous, next, previousAuthored)
574{
575 const bullets = [];
576 const prevOpen = previousAuthored ? !!previous.open : false;
577 if (prevOpen !== !!next.open)
578 { bullets.push(next.open ? "Chunk opened." : "Chunk closed."); }
579
580 for (let localY = 0; localY < CHUNK_SIZE; localY++)
581 {
582 for (let localX = 0; localX < CHUNK_SIZE; localX++)
583 {
584 const index = localY * CHUNK_SIZE + localX;
585 const tileX = localToTile(chunkX, localX);
586 const tileY = localToTile(chunkY, localY);
587 const prevGround = normalizeGround(previous.grounds[index]);
588 const nextGround = normalizeGround(next.grounds[index]);
589 if (prevGround.typeId !== nextGround.typeId)
590 {
591 bullets.push(
592 `Ground at ${tileX}, ${tileY} changed from ${nameGround(prevGround.typeId)} to ${nameGround(nextGround.typeId)}.`
593 );
594 }
595 else if ((prevGround.state ?? "") !== (nextGround.state ?? ""))
596 {
597 bullets.push(
598 `Ground ${nameGround(nextGround.typeId)} at ${tileX}, ${tileY} state changed from ${stateLabel(prevGround.state)} to ${stateLabel(nextGround.state)}.`
599 );
600 }
601
602 const prevBlock = normalizeBlock(previous.blocks[index]);
603 const nextBlock = normalizeBlock(next.blocks[index]);
604 const prevId = prevBlock?.typeId ?? null;
605 const nextId = nextBlock?.typeId ?? null;
606 const prevConfig = JSON.stringify(prevBlock?.config ?? null);
607 const nextConfig = JSON.stringify(nextBlock?.config ?? null);
608 if (prevId !== nextId || prevConfig !== nextConfig)
609 {
610 if (prevId == null && nextId != null)
611 { bullets.push(`Block ${nameBlock(nextId)} placed at ${tileX}, ${tileY}.`); }
612 else if (prevId != null && nextId == null)
613 { bullets.push(`Block ${nameBlock(prevId)} removed at ${tileX}, ${tileY}.`); }
614 else
615 { bullets.push(`Block at ${tileX}, ${tileY} changed from ${nameBlock(prevId)} to ${nameBlock(nextId)}.`); }
616 }
617 else if (prevBlock && nextBlock && (prevBlock.state ?? "") !== (nextBlock.state ?? ""))
618 {
619 bullets.push(
620 `Block ${nameBlock(nextId)} at ${tileX}, ${tileY} state changed from ${stateLabel(prevBlock.state)} to ${stateLabel(nextBlock.state)}.`
621 );
622 }
623 }
624 }
625
626 const prevSpawners = indexSpawners(previous.spawners);
627 const nextSpawners = indexSpawners(next.spawners);
628 for (const key of new Set([...prevSpawners.keys(), ...nextSpawners.keys()]))
629 {
630 const prev = prevSpawners.get(key);
631 const cur = nextSpawners.get(key);
632 const [localX, localY] = key.split(",").map(Number);
633 const tileX = localToTile(chunkX, localX);
634 const tileY = localToTile(chunkY, localY);
635 const prevConfig = JSON.stringify(prev?.config ?? null);
636 const nextConfig = JSON.stringify(cur?.config ?? null);
637 if (!prev && cur)
638 { bullets.push(`Spawner (${cur.config.mobTypeId}) placed at ${tileX}, ${tileY}.`); }
639 else if (prev && !cur)
640 { bullets.push(`Spawner removed at ${tileX}, ${tileY}.`); }
641 else if (prevConfig !== nextConfig)
642 { bullets.push(`Spawner at ${tileX}, ${tileY} config changed.`); }
643 }
644 return bullets;
645}
646
647function indexSpawners (spawners)
648{
649 const map = new Map();
650 for (const entry of spawners ?? [])
651 { map.set(`${entry.localX},${entry.localY}`, entry); }
652 return map;
653}
654
655function nameGround (typeId)
656{
657 return groundDefinition(typeId)?.displayName ?? `ground ${typeId}`;
658}
659
660function nameBlock (typeId)
661{
662 return blockDefinition(typeId)?.displayName ?? `block ${typeId}`;
663}
664
665function stateLabel (state)
666{
667 return state || "default";
668}