BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

feat: add sprite average colours and an editor minimap
timfa project_85689633_bot_760517ee9267c86ff1d6c3a0237abf7d · pushed by timfa · 6 weeks ago
8a24eb51 History
main.js 73.1 KiB Download Raw
1import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, STATIC_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2import
3{
4 GROUND_DEFINITIONS,
5 BLOCK_DEFINITIONS,
6 GroundType,
7 BlockType,
8 normalizeGround,
9 normalizeBlock,
10 listPlaceableBlockPaletteEntries
11} from "/shared/definitions/tiles.js";
12import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
13import
14{
15 SeasonId,
16 seasonIdAt,
17 seasonalCycleStates,
18 seasonIdFromVisualState,
19 placeableStatesForType
20} from "/shared/world/season.js";
21import { loadGraphicsSettings } from "/shared/graphics/settings.js";
22import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";
23import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
24import
25 {
26 isItemSpawnerConfig,
27 defaultItemSpawnerConfig,
28 normalizeItemSpawnerConfig,
29 itemSpawnerPreviewSpriteName,
30 itemSpawnerContainerSpriteName
31 } from "/shared/definitions/itemSpawners.js";
32import
33{
34 computeNeighborConnectMask,
35 composeNeighborConnectState,
36 definitionUsesNeighborConnect,
37 neighborConnectBlocksMatch,
38 neighborConnectRefreshTiles,
39 worldTileToChunkLocal
40} from "/shared/world/neighborConnect.js";
41import { GameSocket, defaultSocketUrl } from "../net/socket.js";
42import { fetchAuthStatus, loginUrl, logoutUrl } from "../net/auth.js";
43import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
44import { WorldView } from "../render/worldView.js";
45import { initSettingsModal, initDimensionSettings } from "./settingsModal.js";
46import { initPaletteModal } from "./paletteModal.js";
47import { initPalettePanel } from "./palettePanel.js";
48import { initTileConfigModal } from "./tileConfigModal.js";
49import { initQuestsModal } from "./questsModal.js";
50import { initDialoguesModal } from "./dialoguesModal.js";
51import { initGiftsModal } from "./giftsModal.js";
52import { initDimensionPickerModal } from "./dimensionPickerModal.js";
53import { initEditorMinimap } from "./minimap.js";
54import
55{
56 OVERWORLD_ID,
57 normalizeDimensionId,
58 isOverworld
59} from "/shared/world/dimensions.js";
60import { normalizeDoorConfig } from "/shared/world/doorRequirements.js";
61import
62{
63 editorChunkSaveKey,
64 editorDirtyChunk,
65 editorDraftOwner,
66 sameEditorChunk,
67 shouldApplySelectedEditorChunk
68} from "./saveAck.js";
69
70const game = new Game();
71let socket;
72let scene;
73let editorMinimap = null;
74let minimapRequestTimer = 0;
75let view;
76let draft = null;
77/** @type {string|null} JSON snapshot of last loaded/saved draft (grounds/blocks/spawners/open). */
78let draftBaseline = null;
79/**
80 * Chunk the current `draft` belongs to. Navigation may update `chunkX`/`chunkY`
81 * (viewed chunk) before save/discard; save must still write to this owner.
82 * @type {{ dimensionId: string, chunkX: number, chunkY: number }|null}
83 */
84let draftOwner = null;
85/** @type {ReturnType<typeof cloneDraftContents>|null} In-memory chunk clipboard for copy/paste. */
86let chunkClipboard = null;
87/**
88 * Neighbor chunks whose connect masks were updated while editing the selected chunk.
89 * Key `"chunkX,chunkY"` → `{ open, grounds, blocks, spawners }`.
90 * @type {Map<string, { open: boolean, grounds: object[], blocks: object[], spawners: object[] }>}
91 */
92let dirtyNeighborChunks = new Map();
93/** Spawners for loaded non-selected chunks (needed when saving edge-mask fixes). */
94let neighborSpawnersByChunk = new Map();
95/** @type {{ chunkX: number, chunkY: number, dimensionId?: string }|null} */
96let pendingNavigate = null;
97/** When true, next matching editorChunk after save should navigate to pendingNavigate. */
98let navigateAfterSave = false;
99/** Keys (`dimensionId:chunkX,chunkY`) for in-flight `EDITOR_SAVE_CHUNK` acks. */
100const pendingSaveAcks = new Set();
101let chunkX = 0;
102let chunkY = 0;
103let selectedDimensionId = OVERWORLD_ID;
104/** @type {string|null} */
105let pendingCreatedDimensionId = null;
106/** @type {Map<string, object>} */
107let dimensionsById = new Map();
108let dimensionPicker = null;
109let dimensionSettings = null;
110let tool = { kind: "ground", typeId: GroundType.grass, state: null };
111let settingsModal;
112let paletteModal;
113let palettePanel;
114let tileConfigModal;
115let questsModal;
116let dialoguesModal;
117let giftsModal;
118let catalog = { grounds: {}, blocks: {}, images: [] };
119let imageUrlByName = new Map();
120let hoverLocal = null;
121let editorZoom = null;
122let activeRevisionId = null;
123let pendingRevisionId = null;
124let applyInFlight = false;
125/** @type {string|null} */
126let sessionAuthSubject = null;
127/** True after the first successful SESSION message for this page load. */
128let sessionReady = false;
129/** Display label for #who while reconnecting. */
130let accountWhoLabel = "Editor";
131const EDITOR_DRAFT_STORAGE_PREFIX = "questward-editor-draft:";
132const EDITOR_ZOOM_MIN = 0.25;
133const EDITOR_ZOOM_MAX = 8;
134const EDITOR_ZOOM_STEP = 1.12;
135const CONSOLE_MAX_LINES = 2000;
136
137function $ (id)
138{
139 return document.getElementById(id);
140}
141
142function formatConsoleTime (t)
143{
144 try
145 { return new Date(t).toLocaleTimeString(); }
146 catch
147 { return ""; }
148}
149
150function appendConsoleLine (entry, { scroll = true } = {})
151{
152 const pre = $("editor-console");
153 if (!pre || !entry)
154 { return; }
155 const line = document.createElement("div");
156 const level = entry.level || "info";
157 line.className = `console-${level}`;
158 line.textContent = `[${formatConsoleTime(entry.t)}] ${entry.text ?? ""}`;
159 pre.append(line);
160 while (pre.childElementCount > CONSOLE_MAX_LINES)
161 { pre.firstChild?.remove(); }
162 if (scroll)
163 { pre.scrollTop = pre.scrollHeight; }
164}
165
166function applyConsoleSnapshot (lines)
167{
168 const pre = $("editor-console");
169 if (!pre)
170 { return; }
171 pre.replaceChildren();
172 for (const entry of lines ?? [])
173 { appendConsoleLine(entry, { scroll: false }); }
174 pre.scrollTop = pre.scrollHeight;
175}
176
177function initSidePanelTabs ()
178{
179 const tabs = document.querySelectorAll(".side-panel-tab");
180 const bodies = document.querySelectorAll("[data-side-panel-body]");
181 function activate (name)
182 {
183 for (const tab of tabs)
184 {
185 const on = tab.dataset.sidePanel === name;
186 tab.classList.toggle("active", on);
187 tab.setAttribute("aria-selected", on ? "true" : "false");
188 }
189 for (const body of bodies)
190 { body.hidden = body.dataset.sidePanelBody !== name; }
191 if (name === "console")
192 {
193 const pre = $("editor-console");
194 if (pre)
195 { pre.scrollTop = pre.scrollHeight; }
196 }
197 }
198 for (const tab of tabs)
199 {
200 tab.addEventListener("click", () => activate(tab.dataset.sidePanel));
201 }
202 $("console-clear")?.addEventListener("click", () =>
203 {
204 const pre = $("editor-console");
205 if (pre)
206 { pre.replaceChildren(); }
207 });
208 activate("changelog");
209}
210
211function selectedToolLabel ()
212{
213 if (tool.kind === "erase")
214 { return "Erase block"; }
215 if (tool.kind === "spawner")
216 {
217 if (tool.spawnerKind === "item" || isItemSpawnerConfig(tool))
218 { return "Spawner · Item Spawner"; }
219 const def = mobDefinition(tool.mobTypeId);
220 return `Spawner · ${def?.displayName ?? tool.mobTypeId}`;
221 }
222 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
223 const layer = tool.kind === "ground" ? "ground" : "block";
224 const states = statesForType(catalog, layer, def.key);
225 const state = resolveState(states, tool.state);
226 if (tool.kind === "block" && def.id === BlockType.flower)
227 { return "Flower"; }
228 if (tool.kind === "block" && def.id === BlockType.boulder)
229 {
230 const entry = listPlaceableBlockPaletteEntries(catalog)
231 .find((row) => row.typeId === def.id && row.state === state);
232 if (entry)
233 { return entry.displayName; }
234 }
235 if (states.length > 1)
236 { return `${def.displayName} (${state})`; }
237 return def.displayName;
238}
239
240function notifyToolChanged ()
241{
242 const label = $("tool");
243 if (label)
244 { label.textContent = selectedToolLabel(); }
245 palettePanel?.sync();
246}
247
248function selectTool (next)
249{
250 if (next.kind === "erase")
251 { tool = { kind: "erase" }; }
252 else if (next.kind === "spawner")
253 {
254 if (next.spawnerKind === "item")
255 { tool = { kind: "spawner", spawnerKind: "item" }; }
256 else
257 { tool = { kind: "spawner", mobTypeId: next.mobTypeId }; }
258 }
259 else
260 {
261 const layer = next.kind === "ground" ? "ground" : "block";
262 const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
263 tool = {
264 kind: next.kind,
265 typeId: next.typeId,
266 state: next.state ?? defaultStateForType(catalog, layer, def.key)
267 };
268 }
269 notifyToolChanged();
270}
271
272function placeableToolState ()
273{
274 if (tool.kind === "erase" || tool.kind === "spawner")
275 { return null; }
276 const layer = tool.kind === "ground" ? "ground" : "block";
277 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
278 return resolveState(statesForType(catalog, layer, def.key), tool.state);
279}
280
281function previewFromTool ()
282{
283 if (tool.kind === "erase")
284 { return { block: null }; }
285 if (tool.kind === "spawner")
286 { return {}; }
287 const state = placeableToolState();
288 if (tool.kind === "ground")
289 { return { ground: { typeId: tool.typeId, state } }; }
290 return { block: { typeId: tool.typeId, state, config: null } };
291}
292
293/** Editor map neighborhood (Chebyshev); 2 → 5×5 chunks around the selection. */
294const EDITOR_VIEW_CHUNK_RADIUS = STATIC_CHUNK_RADIUS;
295
296function inEditorView (x, y)
297{
298 return Math.abs(x - chunkX) <= EDITOR_VIEW_CHUNK_RADIUS && Math.abs(y - chunkY) <= EDITOR_VIEW_CHUNK_RADIUS;
299}
300
301function neighborhoodCoords (centerX, centerY)
302{
303 const coords = [];
304 for (let dy = -EDITOR_VIEW_CHUNK_RADIUS; dy <= EDITOR_VIEW_CHUNK_RADIUS; dy++)
305 {
306 for (let dx = -EDITOR_VIEW_CHUNK_RADIUS; dx <= EDITOR_VIEW_CHUNK_RADIUS; dx++)
307 { coords.push({ chunkX: centerX + dx, chunkY: centerY + dy }); }
308 }
309 return coords;
310}
311
312function snapshotFromPayload (payload)
313{
314 return {
315 chunkX: payload.chunkX,
316 chunkY: payload.chunkY,
317 open: payload.data.open,
318 closedEdges: payload.closedEdges,
319 grounds: payload.data.grounds,
320 blocks: payload.data.blocks,
321 light: payload.data.light,
322 enclosed: payload.data.enclosed,
323 entities: []
324 };
325}
326
327function syncSpawnersOverlay (cx, cy, spawners)
328{
329 view.setEditorSpawners(cx, cy, spawners ?? [], (mobTypeId) => mobSpriteName(mobTypeId));
330}
331
332function spawnerAt (localX, localY)
333{
334 return (draft?.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
335}
336
337function draftPersistable ()
338{
339 if (!draft)
340 { return null; }
341 return {
342 open: !!draft.open,
343 grounds: draft.grounds,
344 blocks: draft.blocks,
345 spawners: draft.spawners ?? []
346 };
347}
348
349function isSelectedChunkDirty ()
350{
351 if (!draft || draftBaseline == null)
352 { return false; }
353 return JSON.stringify(draftPersistable()) !== draftBaseline;
354}
355
356function draftStorageKey (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId, subject = sessionAuthSubject)
357{
358 const who = subject ?? "anon";
359 return `${EDITOR_DRAFT_STORAGE_PREFIX}${who}:${normalizeDimensionId(dimensionId)}:${cx},${cy}`;
360}
361
362function viewedChunkOwner ()
363{
364 return editorDraftOwner(selectedDimensionId, chunkX, chunkY);
365}
366
367function persistDirtyDraftBackup ()
368{
369 if (!draft || !isSelectedChunkDirty())
370 { return; }
371 const owner = editorDirtyChunk(draftOwner, viewedChunkOwner());
372 try
373 {
374 const payload = {
375 savedAt: Date.now(),
376 dimensionId: owner.dimensionId,
377 chunkX: owner.chunkX,
378 chunkY: owner.chunkY,
379 authSubject: sessionAuthSubject,
380 open: !!draft.open,
381 grounds: draft.grounds,
382 blocks: draft.blocks,
383 spawners: draft.spawners ?? [],
384 light: draft.light,
385 enclosed: draft.enclosed,
386 baseline: draftBaseline
387 };
388 sessionStorage.setItem(
389 draftStorageKey(owner.chunkX, owner.chunkY, owner.dimensionId),
390 JSON.stringify(payload)
391 );
392 }
393 catch
394 { /* quota / private mode */ }
395}
396
397function clearDraftBackup (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId)
398{
399 try
400 { sessionStorage.removeItem(draftStorageKey(cx, cy, dimensionId)); }
401 catch
402 { /* ignore */ }
403}
404
405function readDraftBackup (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId)
406{
407 try
408 {
409 const raw = sessionStorage.getItem(draftStorageKey(cx, cy, dimensionId));
410 if (!raw)
411 { return null; }
412 const parsed = JSON.parse(raw);
413 if (!parsed || !Array.isArray(parsed.grounds) || !Array.isArray(parsed.blocks))
414 { return null; }
415 return parsed;
416 }
417 catch
418 { return null; }
419}
420
421function applyRestoredDraftBackup (backup)
422{
423 if (!backup || !draft)
424 { return false; }
425 draft.open = !!backup.open;
426 draft.grounds = backup.grounds.map((ground) => normalizeGround(ground));
427 draft.blocks = backup.blocks.map((block) => (block
428 ? { ...block, config: block.config ?? null }
429 : null));
430 const tileCount = CHUNK_SIZE * CHUNK_SIZE;
431 draft.light = Array.isArray(backup.light) && backup.light.length === tileCount
432 ? backup.light.slice()
433 : (draft.light ?? new Array(tileCount).fill(0));
434 draft.enclosed = Array.isArray(backup.enclosed) && backup.enclosed.length === tileCount
435 ? backup.enclosed.slice().map((v) => (v ? 1 : 0))
436 : (draft.enclosed ?? new Array(tileCount).fill(0));
437 draft.spawners = (backup.spawners ?? []).map((entry) => ({
438 localX: entry.localX | 0,
439 localY: entry.localY | 0,
440 config: { ...(entry.config ?? {}) }
441 }));
442 if (typeof backup.baseline === "string")
443 { draftBaseline = backup.baseline; }
444 $("open").checked = draft.open;
445 const existing = view?.chunks.get(chunkKey(chunkX, chunkY));
446 view.applySnapshot({
447 chunkX,
448 chunkY,
449 open: draft.open,
450 closedEdges: existing?.closedEdges,
451 grounds: draft.grounds,
452 blocks: draft.blocks,
453 light: draft.light,
454 enclosed: draft.enclosed,
455 entities: []
456 });
457 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
458 syncSaveButton();
459 return true;
460}
461
462function tryRestoreDraftBackupAfterServerLoad (payload)
463{
464 const dim = normalizeDimensionId(payload.dimensionId ?? selectedDimensionId);
465 const backup = readDraftBackup(payload.chunkX, payload.chunkY, dim);
466 if (!backup)
467 { return false; }
468 const serverPersistable = {
469 open: !!payload.data.open,
470 grounds: payload.data.grounds,
471 blocks: payload.data.blocks,
472 spawners: payload.data.spawners ?? []
473 };
474 const backupPersistable = {
475 open: !!backup.open,
476 grounds: backup.grounds,
477 blocks: backup.blocks,
478 spawners: backup.spawners ?? []
479 };
480 if (JSON.stringify(serverPersistable) === JSON.stringify(backupPersistable))
481 {
482 clearDraftBackup(payload.chunkX, payload.chunkY, dim);
483 return false;
484 }
485 // Treat server payload as the clean baseline so the restored paint stays dirty.
486 draftBaseline = JSON.stringify(serverPersistable);
487 return applyRestoredDraftBackup(backup);
488}
489
490function cloneDraftContents (source)
491{
492 if (!source)
493 { return null; }
494 const tileCount = CHUNK_SIZE * CHUNK_SIZE;
495 return {
496 open: !!source.open,
497 grounds: (source.grounds ?? []).map((ground) => normalizeGround(ground)),
498 blocks: (source.blocks ?? []).map((block) => (block
499 ? {
500 ...block,
501 config: block.config != null ? structuredClone(block.config) : null
502 }
503 : null)),
504 light: Array.isArray(source.light) && source.light.length === tileCount
505 ? source.light.slice()
506 : new Array(tileCount).fill(0),
507 spawners: (source.spawners ?? []).map((entry) => ({
508 localX: entry.localX | 0,
509 localY: entry.localY | 0,
510 config: structuredClone(entry.config ?? {})
511 }))
512 };
513}
514
515function blankChunkContents ()
516{
517 const groundTypeId = dimensionsById.get(selectedDimensionId)?.defaultGroundTypeId
518 ?? GroundType.grass;
519 const tileCount = CHUNK_SIZE * CHUNK_SIZE;
520 return {
521 open: false,
522 grounds: new Array(tileCount).fill(null).map(() => normalizeGround(groundTypeId, groundTypeId)),
523 blocks: new Array(tileCount).fill(null),
524 light: new Array(tileCount).fill(0),
525 spawners: []
526 };
527}
528
529function applyDraftContents (next)
530{
531 if (!draft || !next || isSelectedDimensionSoftDeleted())
532 { return; }
533 clearNeighborEditState();
534 draft.open = !!next.open;
535 draft.grounds = next.grounds.map((ground) => normalizeGround(ground));
536 draft.blocks = next.blocks.map((block) => (block
537 ? { ...block, config: block.config ?? null }
538 : null));
539 draft.light = Array.isArray(next.light) ? next.light.slice() : new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0);
540 draft.enclosed = Array.isArray(next.enclosed)
541 ? next.enclosed.slice().map((v) => (v ? 1 : 0))
542 : new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0);
543 draft.spawners = (next.spawners ?? []).map((entry) => ({
544 localX: entry.localX | 0,
545 localY: entry.localY | 0,
546 config: { ...(entry.config ?? {}) }
547 }));
548 $("open").checked = draft.open;
549 const existing = view?.chunks.get(chunkKey(chunkX, chunkY));
550 view.applySnapshot({
551 chunkX,
552 chunkY,
553 open: draft.open,
554 closedEdges: existing?.closedEdges,
555 grounds: draft.grounds,
556 blocks: draft.blocks,
557 light: draft.light,
558 enclosed: draft.enclosed,
559 entities: []
560 });
561 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
562 afterDraftMutation();
563}
564
565function syncChunkClipboardButtons ()
566{
567 const softDeleted = isSelectedDimensionSoftDeleted();
568 const copyBtn = $("copy-chunk");
569 const pasteBtn = $("paste-chunk");
570 const clearBtn = $("clear-chunk");
571 if (copyBtn)
572 {
573 copyBtn.disabled = !draft || softDeleted;
574 copyBtn.title = softDeleted
575 ? "Cannot copy while this dimension is soft-deleted"
576 : "Copy this chunk into the editor clipboard";
577 }
578 if (pasteBtn)
579 {
580 const canPaste = !!draft && !!chunkClipboard && !softDeleted;
581 pasteBtn.disabled = !canPaste;
582 pasteBtn.title = softDeleted
583 ? "Cannot paste while this dimension is soft-deleted"
584 : chunkClipboard
585 ? "Paste the copied chunk over the current draft (does not save)"
586 : "Copy a chunk first";
587 }
588 if (clearBtn)
589 {
590 clearBtn.disabled = !draft || softDeleted;
591 clearBtn.title = softDeleted
592 ? "Cannot clear while this dimension is soft-deleted"
593 : "Erase this chunk to a blank slate (does not save)";
594 }
595}
596
597function copySelectedChunk ()
598{
599 if (!draft || isSelectedDimensionSoftDeleted())
600 { return; }
601 chunkClipboard = cloneDraftContents(draft);
602 syncChunkClipboardButtons();
603}
604
605function pasteSelectedChunk ()
606{
607 if (!draft || !chunkClipboard || isSelectedDimensionSoftDeleted())
608 { return; }
609 const ok = window.confirm(
610 "This will replace your current chunk entirely with your copied chunk. Are you sure?"
611 );
612 if (!ok)
613 { return; }
614 applyDraftContents(cloneDraftContents(chunkClipboard));
615}
616
617function clearSelectedChunk ()
618{
619 if (!draft || isSelectedDimensionSoftDeleted())
620 { return; }
621 const ok = window.confirm(
622 "this will erase the chunk and reset it to a default blank slate. Are you certain?"
623 );
624 if (!ok)
625 { return; }
626 applyDraftContents(blankChunkContents());
627}
628
629function captureDraftBaseline ()
630{
631 const payload = draftPersistable();
632 draftBaseline = payload ? JSON.stringify(payload) : null;
633 const owner = editorDirtyChunk(draftOwner, viewedChunkOwner());
634 clearDraftBackup(owner.chunkX, owner.chunkY, owner.dimensionId);
635 syncSaveButton();
636}
637
638function discardUnsavedDraft ()
639{
640 const owner = editorDirtyChunk(draftOwner, viewedChunkOwner());
641 clearDraftBackup(owner.chunkX, owner.chunkY, owner.dimensionId);
642 clearNeighborEditState();
643 draft = null;
644 draftBaseline = null;
645 draftOwner = null;
646 syncSaveButton();
647}
648
649function chunkKey (cx, cy)
650{
651 return `${cx},${cy}`;
652}
653
654function isDraftDirty ()
655{
656 if (dirtyNeighborChunks.size > 0)
657 { return true; }
658 return isSelectedChunkDirty();
659}
660
661function syncSaveButton ()
662{
663 const btn = $("save");
664 if (!btn)
665 { return; }
666 const softDeleted = isSelectedDimensionSoftDeleted();
667 const dirty = isDraftDirty();
668 btn.disabled = !dirty || softDeleted;
669 btn.classList.toggle("save-dirty", dirty && !softDeleted);
670 btn.title = softDeleted
671 ? "Cannot save while this dimension is soft-deleted"
672 : dirty
673 ? "Save unsaved chunk changes"
674 : "No unsaved changes";
675 syncChunkClipboardButtons();
676}
677
678function afterDraftMutation ()
679{
680 syncSaveButton();
681 const owner = editorDirtyChunk(draftOwner, viewedChunkOwner());
682 if (isSelectedChunkDirty())
683 { persistDirtyDraftBackup(); }
684 else
685 { clearDraftBackup(owner.chunkX, owner.chunkY, owner.dimensionId); }
686}
687
688function clearNeighborEditState ()
689{
690 dirtyNeighborChunks.clear();
691}
692
693function groundAtWorld (tileX, tileY)
694{
695 const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
696 const index = localY * CHUNK_SIZE + localX;
697 if (cx === chunkX && cy === chunkY && draft)
698 { return draft.grounds[index] ?? null; }
699 const dirty = dirtyNeighborChunks.get(chunkKey(cx, cy));
700 if (dirty)
701 { return dirty.grounds[index] ?? null; }
702 const snapshot = view?.chunks.get(chunkKey(cx, cy));
703 return snapshot?.grounds?.[index] ?? null;
704}
705
706function spawnerAtWorld (tileX, tileY)
707{
708 const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
709 if (cx === chunkX && cy === chunkY && draft)
710 { return spawnerAt(localX, localY); }
711 const dirty = dirtyNeighborChunks.get(chunkKey(cx, cy));
712 if (dirty)
713 { return dirty.spawners?.find((entry) => entry.localX === localX && entry.localY === localY) ?? null; }
714 return (neighborSpawnersByChunk.get(chunkKey(cx, cy)) ?? [])
715 .find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
716}
717
718/** Human-readable summary of authored ground/block/spawner on a world tile. */
719function describeWorldTile (tileX, tileY, dimensionId = selectedDimensionId)
720{
721 const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);
722 if (dim !== selectedDimensionId)
723 {
724 return `Currently editing “${selectedDimensionId}”; switch to “${dim}” to inspect this tile.`;
725 }
726 const { chunkX: cx, chunkY: cy } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
727 const key = chunkKey(cx, cy);
728 const loaded = (cx === chunkX && cy === chunkY && draft)
729 || dirtyNeighborChunks.has(key)
730 || view?.chunks?.has(key);
731 if (!loaded)
732 { return `Chunk (${cx}, ${cy}) not loaded — center on this tile to load it.`; }
733
734 const lines = [];
735 const ground = normalizeGround(groundAtWorld(tileX, tileY));
736 const groundDef = GROUND_DEFINITIONS[ground?.typeId];
737 lines.push(`Ground: ${groundDef?.displayName ?? `type ${ground?.typeId ?? "?"}`}`);
738 const block = normalizeBlock(blockAtWorld(tileX, tileY));
739 if (block)
740 {
741 const blockDef = BLOCK_DEFINITIONS[block.typeId];
742 lines.push(`Block: ${blockDef?.displayName ?? `type ${block.typeId}`}${block.state ? ` (${block.state})` : ""}`);
743 if (block.config && Object.keys(block.config).length)
744 {
745 for (const [keyName, value] of Object.entries(block.config))
746 { lines.push(` ${keyName}: ${value}`); }
747 }
748 }
749 else
750 { lines.push("Block: (none)"); }
751 const spawner = spawnerAtWorld(tileX, tileY);
752 if (spawner)
753 {
754 const config = normalizeSpawnerConfig(spawner.config, spawner.config?.spawnerId);
755 if (isItemSpawnerConfig(config))
756 { lines.push(`Spawner: Item Spawner (${config.spawnerId})`); }
757 else
758 {
759 const mob = mobDefinition(config.mobTypeId);
760 lines.push(`Spawner: ${mob?.displayName ?? config.mobTypeId} (${config.spawnerId})`);
761 }
762 }
763 else
764 { lines.push("Spawner: (none)"); }
765 return lines.join("\n");
766}
767
768/** Pan the editor to a world tile without closing other UI; loads its chunk neighborhood. */
769function centerEditorOnTile (tileX, tileY, dimensionId = selectedDimensionId)
770{
771 const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);
772 const { chunkX: cx, chunkY: cy } = worldTileToChunkLocal(tileX | 0, tileY | 0, CHUNK_SIZE);
773 if (dim !== selectedDimensionId)
774 {
775 if (isDraftDirty())
776 {
777 showUnsavedModal({ chunkX: cx, chunkY: cy, dimensionId: dim });
778 return false;
779 }
780 selectedDimensionId = dim;
781 syncDimensionUi();
782 clearNeighborhoodView();
783 doLoadNeighborhood(cx, cy);
784 }
785 else if (cx !== chunkX || cy !== chunkY)
786 {
787 if (isDraftDirty())
788 {
789 showUnsavedModal({ chunkX: cx, chunkY: cy, dimensionId: selectedDimensionId });
790 return false;
791 }
792 doLoadNeighborhood(cx, cy);
793 }
794 if (!view?.scene)
795 { return true; }
796 const size = view.tileSize();
797 view.followPlayer = false;
798 view.scene.cameraPosition.x = view.scene.real_size.x / 2 - ((tileX | 0) + 0.5) * size;
799 view.scene.cameraPosition.y = view.scene.real_size.y / 2 - ((tileY | 0) + 0.5) * size;
800 view.refreshViewport();
801 updateSelectionBorder();
802 return true;
803}
804
805function blockAtWorld (tileX, tileY)
806{
807 const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
808 if (cx === chunkX && cy === chunkY && draft)
809 { return draft.blocks[localY * CHUNK_SIZE + localX] ?? null; }
810 const dirty = dirtyNeighborChunks.get(chunkKey(cx, cy));
811 if (dirty)
812 { return dirty.blocks[localY * CHUNK_SIZE + localX] ?? null; }
813 const snapshot = view?.chunks.get(chunkKey(cx, cy));
814 return snapshot?.blocks?.[localY * CHUNK_SIZE + localX] ?? null;
815}
816
817function ensureDirtyNeighborChunk (cx, cy)
818{
819 const key = chunkKey(cx, cy);
820 let data = dirtyNeighborChunks.get(key);
821 if (data)
822 { return data; }
823 const snapshot = view?.chunks.get(key);
824 if (!snapshot)
825 { return null; }
826 data = {
827 open: !!snapshot.open,
828 grounds: (snapshot.grounds ?? []).map((ground) => normalizeGround(ground)),
829 blocks: (snapshot.blocks ?? []).map((block) => (block ? { ...block, config: block.config ?? null } : null)),
830 spawners: structuredClone(neighborSpawnersByChunk.get(key) ?? [])
831 };
832 dirtyNeighborChunks.set(key, data);
833 return data;
834}
835
836function writeBlockAtWorld (tileX, tileY, block)
837{
838 const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
839 const index = localY * CHUNK_SIZE + localX;
840 if (cx === chunkX && cy === chunkY && draft)
841 {
842 draft.blocks[index] = block;
843 view.updateAuthoredTile(cx, cy, localX, localY, {
844 ground: draft.grounds[index],
845 block: draft.blocks[index],
846 light: draft.light[index]
847 });
848 return true;
849 }
850 const data = ensureDirtyNeighborChunk(cx, cy);
851 if (!data)
852 { return false; }
853 data.blocks[index] = block;
854 const snapshot = view?.chunks.get(chunkKey(cx, cy));
855 const light = snapshot?.light?.[index];
856 view.updateAuthoredTile(cx, cy, localX, localY, {
857 ground: data.grounds[index],
858 block: data.blocks[index],
859 light
860 });
861 return true;
862}
863
864function showUnsavedModal (target)
865{
866 pendingNavigate = target;
867 $("unsaved-chunk-backdrop").hidden = false;
868 $("unsaved-chunk-modal").hidden = false;
869}
870
871function hideUnsavedModal ()
872{
873 $("unsaved-chunk-backdrop").hidden = true;
874 $("unsaved-chunk-modal").hidden = true;
875}
876
877function saveSelectedChunk ()
878{
879 if (!draft || !isDraftDirty())
880 { return false; }
881 if (isSelectedDimensionSoftDeleted())
882 {
883 $("error").textContent = "Cannot save while this dimension is soft-deleted.";
884 return false;
885 }
886 $("error").textContent = "";
887 $("apply-status").textContent = "";
888 $("apply-status").className = "hint";
889 const target = editorDirtyChunk(draftOwner, viewedChunkOwner());
890 const neighborSaves = [...dirtyNeighborChunks.entries()];
891 clearNeighborEditState();
892 const savedChunks = [{ chunkX: target.chunkX, chunkY: target.chunkY }];
893 pendingSaveAcks.add(editorChunkSaveKey(target.dimensionId, target.chunkX, target.chunkY));
894 socket.send({
895 type: MessageType.editorSaveChunk,
896 chunkX: target.chunkX,
897 chunkY: target.chunkY,
898 dimensionId: target.dimensionId,
899 draft: {
900 open: $("open").checked,
901 grounds: draft.grounds,
902 blocks: draft.blocks,
903 spawners: draft.spawners ?? []
904 }
905 });
906 for (const [key, data] of neighborSaves)
907 {
908 const [cx, cy] = key.split(",").map(Number);
909 savedChunks.push({ chunkX: cx, chunkY: cy });
910 pendingSaveAcks.add(editorChunkSaveKey(target.dimensionId, cx, cy));
911 socket.send({
912 type: MessageType.editorSaveChunk,
913 chunkX: cx,
914 chunkY: cy,
915 dimensionId: target.dimensionId,
916 draft: {
917 open: data.open,
918 grounds: data.grounds,
919 blocks: data.blocks,
920 spawners: data.spawners ?? []
921 }
922 });
923 }
924 view?.bakeNatureTintForChunks?.(savedChunks);
925 requestNeighbors();
926 return true;
927}
928
929function isSelectedDimensionSoftDeleted ()
930{
931 const record = dimensionsById.get(selectedDimensionId);
932 return record?.deletedAt != null;
933}
934
935function formatPurgeHint (record)
936{
937 if (!record?.purgeAfter)
938 { return "Soft-deleted — painting disabled."; }
939 const when = new Date(record.purgeAfter);
940 return `Soft-deleted — purges ${when.toLocaleString()} (painting disabled).`;
941}
942
943function syncDimensionUi ()
944{
945 const record = dimensionsById.get(selectedDimensionId);
946 const softDeleted = record?.deletedAt != null;
947 const hint = $("dimension-purge-hint");
948 if (hint)
949 {
950 hint.hidden = !softDeleted;
951 hint.textContent = softDeleted ? formatPurgeHint(record) : "";
952 }
953 const openToggle = $("open");
954 if (openToggle)
955 { openToggle.disabled = softDeleted; }
956 dimensionPicker?.setValue(selectedDimensionId);
957 dimensionSettings?.refresh();
958 palettePanel?.sync();
959 syncSaveButton();
960}
961
962function applyDimensionsList (payload)
963{
964 const list = Array.isArray(payload?.dimensions) ? payload.dimensions : [];
965 dimensionsById = new Map(list.map((dim) => [dim.dimensionId, dim]));
966 if (!dimensionsById.has(OVERWORLD_ID))
967 {
968 dimensionsById.set(OVERWORLD_ID, {
969 dimensionId: OVERWORLD_ID,
970 displayName: "Overworld",
971 lightingMode: "dayNight",
972 seasonMode: "auto",
973 defaultGroundTypeId: 1,
974 deletedAt: null,
975 purgeAfter: null
976 });
977 }
978 const options = [...dimensionsById.values()].map((dim) => ({
979 id: dim.dimensionId,
980 label: dim.displayName || dim.dimensionId,
981 disabled: dim.deletedAt != null,
982 hint: dim.deletedAt != null ? formatPurgeHint(dim) : null
983 }));
984 dimensionPicker?.setOptions(options);
985 const createdId = pendingCreatedDimensionId;
986 pendingCreatedDimensionId = null;
987 if (createdId && dimensionsById.has(createdId))
988 {
989 setRevisionState({
990 activeRevisionId: payload.activeRevisionId,
991 pendingRevisionId: payload.pendingRevisionId
992 });
993 selectDimension(createdId, { force: true });
994 return;
995 }
996 if (!dimensionsById.has(selectedDimensionId))
997 { selectedDimensionId = OVERWORLD_ID; }
998 setRevisionState({
999 activeRevisionId: payload.activeRevisionId,
1000 pendingRevisionId: payload.pendingRevisionId
1001 });
1002 syncDimensionUi();
1003 if (!isDraftDirty())
1004 { requestChunks(neighborhoodCoords(chunkX, chunkY)); }
1005}
1006
1007function requestDimensions ()
1008{
1009 socket.send({ type: MessageType.editorListDimensions });
1010}
1011
1012function selectDimension (dimensionId, { force = false } = {})
1013{
1014 const nextId = normalizeDimensionId(dimensionId);
1015 if (!force && nextId === selectedDimensionId)
1016 { return; }
1017 if (!force && isDraftDirty())
1018 {
1019 showUnsavedModal({ chunkX, chunkY, dimensionId: nextId });
1020 dimensionPicker?.setValue(selectedDimensionId);
1021 return;
1022 }
1023 selectedDimensionId = nextId;
1024 syncDimensionUi();
1025 clearNeighborhoodView();
1026 doLoadNeighborhood(chunkX, chunkY);
1027}
1028
1029function clearNeighborhoodView ()
1030{
1031 draft = null;
1032 draftBaseline = null;
1033 draftOwner = null;
1034 clearNeighborEditState();
1035 neighborSpawnersByChunk.clear();
1036 if (!view)
1037 { return; }
1038 for (const key of [...view.chunks.keys()])
1039 {
1040 const [x, y] = key.split(",").map(Number);
1041 view.removeChunk(x, y);
1042 }
1043 view.clearEditorSpawners?.();
1044 syncSaveButton();
1045}
1046
1047function paintAt (localX, localY)
1048{
1049 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
1050 { return; }
1051 if (isSelectedDimensionSoftDeleted())
1052 { return; }
1053 const index = localY * CHUNK_SIZE + localX;
1054 const state = placeableToolState();
1055 if (tool.kind === "ground")
1056 { draft.grounds[index] = { typeId: tool.typeId, state }; }
1057 else if (tool.kind === "erase")
1058 {
1059 const removed = draft.blocks[index];
1060 draft.blocks[index] = null;
1061 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
1062 ground: draft.grounds[index],
1063 block: draft.blocks[index],
1064 light: draft.light[index]
1065 });
1066 if (removed && definitionUsesNeighborConnect(BLOCK_DEFINITIONS[removed.typeId]))
1067 { refreshNeighborConnect(localX, localY, removed.typeId); }
1068 afterDraftMutation();
1069 return;
1070 }
1071 else if (tool.kind === "spawner")
1072 {
1073 const existing = spawnerAt(localX, localY);
1074 const spawnerId = existing?.config?.spawnerId
1075 ?? `${normalizeDimensionId(selectedDimensionId)}:${chunkX}:${chunkY}:${index}`;
1076 const config = tool.spawnerKind === "item"
1077 ? normalizeItemSpawnerConfig({
1078 ...defaultItemSpawnerConfig(spawnerId),
1079 ...(isItemSpawnerConfig(existing?.config) ? existing.config : {}),
1080 spawnerId
1081 }, spawnerId)
1082 : normalizeSpawnerConfig({
1083 ...defaultSpawnerConfig(spawnerId, tool.mobTypeId),
1084 ...(existing?.config && !isItemSpawnerConfig(existing.config) ? existing.config : {}),
1085 spawnerId,
1086 mobTypeId: tool.mobTypeId
1087 }, spawnerId);
1088 const entry = { localX, localY, config };
1089 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY);
1090 draft.spawners.push(entry);
1091 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1092 afterDraftMutation();
1093 return;
1094 }
1095 else
1096 {
1097 const def = BLOCK_DEFINITIONS[tool.typeId];
1098 if (def?.id === BlockType.fishingSpot)
1099 {
1100 const groundType = draft.grounds[index]?.typeId;
1101 if (groundType !== GroundType.water && groundType !== GroundType.deepWater)
1102 { return; }
1103 }
1104 let nextState = definitionUsesNeighborConnect(def)
1105 ? composeNeighborConnectState(def, state, 0)
1106 : state;
1107 if (def?.id === BlockType.flower)
1108 { nextState = flowerBlockState(randomFlowerColorId()); }
1109 if (def?.id === BlockType.fishingSpot && !nextState)
1110 { nextState = "fishing-spot"; }
1111 const config = def?.id === BlockType.doorway
1112 ? {
1113 targetDimensionId: selectedDimensionId,
1114 tileX: chunkX * CHUNK_SIZE + localX,
1115 tileY: chunkY * CHUNK_SIZE + localY
1116 }
1117 : (def?.id === BlockType.fishingSpot
1118 ? { fishes: [] }
1119 : null);
1120 if (def?.id === BlockType.doorway && !nextState)
1121 { nextState = "door"; }
1122 draft.blocks[index] = { typeId: tool.typeId, state: nextState, config };
1123 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
1124 ground: draft.grounds[index],
1125 block: draft.blocks[index],
1126 light: draft.light[index]
1127 });
1128 if (definitionUsesNeighborConnect(def))
1129 { refreshNeighborConnect(localX, localY, tool.typeId); }
1130 afterDraftMutation();
1131 return;
1132 }
1133 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
1134 ground: draft.grounds[index],
1135 block: draft.blocks[index],
1136 light: draft.light[index]
1137 });
1138 afterDraftMutation();
1139}
1140
1141/** Recompute neighbor-connect masks around a local tile, including across chunk edges. */
1142function refreshNeighborConnect (localX, localY, typeId)
1143{
1144 const def = BLOCK_DEFINITIONS[typeId];
1145 if (!draft || !definitionUsesNeighborConnect(def))
1146 { return; }
1147 const originTileX = chunkX * CHUNK_SIZE + localX;
1148 const originTileY = chunkY * CHUNK_SIZE + localY;
1149 for (const [tileX, tileY] of neighborConnectRefreshTiles(originTileX, originTileY))
1150 {
1151 const block = blockAtWorld(tileX, tileY);
1152 if (!block || block.typeId !== typeId)
1153 { continue; }
1154 const mask = computeNeighborConnectMask((dx, dy) =>
1155 {
1156 const neighbor = blockAtWorld(tileX + dx, tileY + dy);
1157 return neighborConnectBlocksMatch(block, neighbor, def);
1158 });
1159 const nextState = composeNeighborConnectState(def, block.state, mask);
1160 if (block.state === nextState)
1161 { continue; }
1162 writeBlockAtWorld(tileX, tileY, { ...block, state: nextState });
1163 }
1164}
1165
1166function updateRevisionUI ()
1167{
1168 const applyBtn = $("apply");
1169 $("revision").textContent = `active ${activeRevisionId ?? "?"}` +
1170 (pendingRevisionId ? ` · pending ${pendingRevisionId}` : " · no pending revision");
1171 if (applyBtn)
1172 {
1173 applyBtn.disabled = !pendingRevisionId || applyInFlight;
1174 applyBtn.title = pendingRevisionId
1175 ? "Reload the live world with the pending map revision"
1176 : "Save a chunk first to create a pending revision";
1177 }
1178}
1179
1180function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pending })
1181{
1182 if (active != null)
1183 { activeRevisionId = active; }
1184 pendingRevisionId = pending ?? null;
1185 updateRevisionUI();
1186}
1187
1188function showSelectedChunk (payload, { isSaveAck = false } = {})
1189{
1190 const incoming = editorDraftOwner(
1191 payload.dimensionId ?? selectedDimensionId,
1192 payload.chunkX,
1193 payload.chunkY
1194 );
1195 const keepDirtyDraft = !shouldApplySelectedEditorChunk({
1196 isSaveAck,
1197 isDirty: !!draft && isSelectedChunkDirty(),
1198 incoming,
1199 draftOwner
1200 });
1201 if (!keepDirtyDraft)
1202 {
1203 if (draftOwner && !sameEditorChunk(incoming, draftOwner))
1204 { clearDraftBackup(draftOwner.chunkX, draftOwner.chunkY, draftOwner.dimensionId); }
1205 clearNeighborEditState();
1206 }
1207 if (keepDirtyDraft)
1208 {
1209 setRevisionState({
1210 activeRevisionId: payload.activeRevisionId,
1211 pendingRevisionId: payload.pendingRevisionId
1212 });
1213 $("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)";
1214 syncSaveButton();
1215 return;
1216 }
1217 draft = {
1218 open: payload.data.open,
1219 grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
1220 blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)),
1221 light: payload.data.light.slice(),
1222 enclosed: Array.isArray(payload.data.enclosed)
1223 ? payload.data.enclosed.slice().map((v) => (v ? 1 : 0))
1224 : new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0),
1225 spawners: (payload.data.spawners ?? []).map((entry) => ({
1226 localX: entry.localX,
1227 localY: entry.localY,
1228 config: { ...entry.config }
1229 }))
1230 };
1231 draftOwner = incoming;
1232 $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`;
1233 $("open").checked = draft.open;
1234 setRevisionState({
1235 activeRevisionId: payload.activeRevisionId,
1236 pendingRevisionId: payload.pendingRevisionId
1237 });
1238 $("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)";
1239 const log = $("changelog");
1240 log.innerHTML = "";
1241 for (const entry of payload.changelog ?? [])
1242 {
1243 const item = document.createElement("article");
1244 item.innerHTML = `<header>${entry.editorDisplayName || entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
1245 const list = document.createElement("ul");
1246 for (const bullet of entry.diffEntries)
1247 {
1248 const li = document.createElement("li");
1249 li.textContent = bullet;
1250 list.append(li);
1251 }
1252 item.append(list);
1253 log.append(item);
1254 }
1255 view.applySnapshot(snapshotFromPayload(payload));
1256 syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);
1257 const restored = isSaveAck ? false : tryRestoreDraftBackupAfterServerLoad(payload);
1258 if (!restored)
1259 { captureDraftBaseline(); }
1260 else
1261 { syncSaveButton(); }
1262 if (navigateAfterSave && pendingNavigate)
1263 {
1264 const next = pendingNavigate;
1265 navigateAfterSave = false;
1266 pendingNavigate = null;
1267 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1268 if (nextDim !== selectedDimensionId)
1269 {
1270 selectedDimensionId = nextDim;
1271 syncDimensionUi();
1272 clearNeighborhoodView();
1273 }
1274 doLoadNeighborhood(next.chunkX, next.chunkY);
1275 }
1276}
1277
1278function pruneView ()
1279{
1280 for (const key of [...view.chunks.keys()])
1281 {
1282 const [x, y] = key.split(",").map(Number);
1283 if (!inEditorView(x, y))
1284 {
1285 view.removeChunk(x, y);
1286 neighborSpawnersByChunk.delete(key);
1287 dirtyNeighborChunks.delete(key);
1288 }
1289 }
1290}
1291
1292function frameNeighborhood ()
1293{
1294 const size = view.tileSize();
1295 view.followPlayer = false;
1296 const centerX = (chunkX + 0.5) * CHUNK_SIZE * size;
1297 const centerY = (chunkY + 0.5) * CHUNK_SIZE * size;
1298 view.scene.cameraPosition.x = view.scene.real_size.x / 2 - centerX;
1299 view.scene.cameraPosition.y = view.scene.real_size.y / 2 - centerY;
1300 view.refreshViewport();
1301 updateSelectionBorder();
1302}
1303
1304function updateSelectionBorder ()
1305{
1306 const border = $("selection-border");
1307 const canvas = scene?.canvas;
1308 if (!border || !canvas)
1309 { return; }
1310
1311 const rect = canvas.getBoundingClientRect();
1312 const size = view.tileSize();
1313 const chunkPx = CHUNK_SIZE * size;
1314 const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x;
1315 const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y;
1316 border.style.left = `${rect.left + screenLeft}px`;
1317 border.style.top = `${rect.top + screenTop}px`;
1318 border.style.width = `${chunkPx}px`;
1319 border.style.height = `${chunkPx}px`;
1320}
1321
1322function layoutScene ()
1323{
1324 const header = document.querySelector("body > header");
1325 const aside = $("editor-tools");
1326 const sidePanels = $("side-panels") || $("changelog-wrap");
1327 const top = header.offsetHeight;
1328 aside.style.top = `${top}px`;
1329 sidePanels.style.top = `${top}px`;
1330 const left = aside.offsetWidth;
1331 const right = sidePanels.offsetWidth;
1332 const width = Math.max(64, window.innerWidth - left - right);
1333 const height = Math.max(64, window.innerHeight - top);
1334 scene.position.x = left;
1335 scene.position.y = top;
1336 scene.size.x = width;
1337 scene.size.y = height;
1338 scene.g_fixSize();
1339 useNearestNeighbour(scene, game.images);
1340 const fit = Math.min(width, height) / (CHUNK_SIZE * (EDITOR_VIEW_CHUNK_RADIUS * 2 + 1) * SPRITE_SIZE_PX);
1341 if (editorZoom == null)
1342 { editorZoom = fit; }
1343 else
1344 { editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, editorZoom)); }
1345 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
1346 frameNeighborhood();
1347}
1348
1349function zoomEditor (direction)
1350{
1351 if (!view)
1352 { return; }
1353 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
1354 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
1355 scheduleEditorZoom();
1356}
1357
1358let editorZoomRaf = 0;
1359function scheduleEditorZoom ()
1360{
1361 if (editorZoomRaf)
1362 { return; }
1363 editorZoomRaf = requestAnimationFrame(() =>
1364 {
1365 editorZoomRaf = 0;
1366 if (!view)
1367 { return; }
1368 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
1369 frameNeighborhood();
1370 });
1371}
1372
1373function requestChunks (coords)
1374{
1375 if (!socket?.socket || socket.socket.readyState !== WebSocket.OPEN)
1376 { return; }
1377 for (const coord of coords)
1378 {
1379 try
1380 {
1381 socket.send({
1382 type: MessageType.editorLoadChunk,
1383 chunkX: coord.chunkX,
1384 chunkY: coord.chunkY,
1385 dimensionId: selectedDimensionId
1386 });
1387 }
1388 catch (_)
1389 { break; }
1390 }
1391}
1392
1393function doLoadNeighborhood (x, y)
1394{
1395 chunkX = x;
1396 chunkY = y;
1397 $("coords").textContent = `${chunkX}, ${chunkY}`;
1398 requestChunks(neighborhoodCoords(x, y));
1399 requestEditorMinimap();
1400}
1401
1402function requestEditorMinimap ()
1403{
1404 editorMinimap?.setCenter();
1405 if (minimapRequestTimer)
1406 { return; }
1407 minimapRequestTimer = setTimeout(() =>
1408 {
1409 minimapRequestTimer = 0;
1410 if (!socket?.socket || socket.socket.readyState !== WebSocket.OPEN)
1411 { return; }
1412 socket.send({
1413 type: MessageType.editorRequestMinimap,
1414 chunkX,
1415 chunkY,
1416 dimensionId: selectedDimensionId
1417 });
1418 }, 40);
1419}
1420
1421function loadNeighborhood (x, y)
1422{
1423 if ((x !== chunkX || y !== chunkY) && isDraftDirty())
1424 {
1425 showUnsavedModal({ chunkX: x, chunkY: y, dimensionId: selectedDimensionId });
1426 return;
1427 }
1428 doLoadNeighborhood(x, y);
1429}
1430
1431function requestNeighbors ()
1432{
1433 requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
1434}
1435
1436function anyModalOpen ()
1437{
1438 return settingsModal?.isOpen()
1439 || paletteModal?.isOpen()
1440 || tileConfigModal?.isOpen()
1441 || questsModal?.isOpen()
1442 || dialoguesModal?.isOpen()
1443 || giftsModal?.isOpen()
1444 || dimensionPicker?.isOpen()
1445 || !$("unsaved-chunk-modal")?.hidden
1446 || !$("global-changelog-modal")?.hidden
1447 || !$("dimension-picker-modal")?.hidden;
1448}
1449
1450function updateHoverStatus (local)
1451{
1452 const el = $("hover-status-text");
1453 if (!el)
1454 { return; }
1455 if (!local)
1456 {
1457 el.textContent = "Hover a tile for coordinates";
1458 return;
1459 }
1460 const hoverChunkX = local.chunkX ?? Math.floor(local.tileX / CHUNK_SIZE);
1461 const hoverChunkY = local.chunkY ?? Math.floor(local.tileY / CHUNK_SIZE);
1462 el.textContent = `Tile (${local.tileX}, ${local.tileY}) · Chunk (${hoverChunkX}, ${hoverChunkY})`;
1463}
1464
1465function updateTooltip (local, options = {})
1466{
1467 if (!options.keepStatus)
1468 { updateHoverStatus(local); }
1469 const tip = $("tile-tooltip");
1470 if (!tip || !local || !draft)
1471 {
1472 if (tip)
1473 { tip.hidden = true; }
1474 view?.clearSpawnRangeHighlight();
1475 return;
1476 }
1477 const block = normalizeBlock(draft.blocks[local.y * CHUNK_SIZE + local.x]);
1478 const spawner = spawnerAt(local.x, local.y);
1479 const lines = [];
1480 if (block)
1481 {
1482 const def = BLOCK_DEFINITIONS[block.typeId];
1483 lines.push(def?.displayName ?? `Block ${block.typeId}`);
1484 if (block.config && Object.keys(block.config).length)
1485 {
1486 for (const [key, value] of Object.entries(block.config))
1487 { lines.push(`${key}: ${value}`); }
1488 }
1489 }
1490 if (spawner)
1491 {
1492 const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId);
1493 if (isItemSpawnerConfig(config))
1494 {
1495 lines.push("Spawner · Item Spawner");
1496 lines.push(`appearance: ${config.appearance}`);
1497 lines.push(`items: ${(config.items ?? []).length}`);
1498 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
1499 lines.push(`respawn: ${config.respawnDelaySeconds}s`);
1500 lines.push(`id: ${config.spawnerId}`);
1501 view.setSpawnRangeHighlight(
1502 local.tileX,
1503 local.tileY,
1504 config.spawnRangeTiles,
1505 config.spawnRangeTiles
1506 );
1507 }
1508 else
1509 {
1510 const mob = mobDefinition(config.mobTypeId);
1511 lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`);
1512 lines.push(`maxAlive: ${config.maxAlive}`);
1513 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
1514 lines.push(`wanderRange: ${config.maxWanderRangeTiles}`);
1515 lines.push(`id: ${config.spawnerId}`);
1516 view.setSpawnRangeHighlight(
1517 local.tileX,
1518 local.tileY,
1519 config.spawnRangeTiles,
1520 config.maxWanderRangeTiles
1521 );
1522 }
1523 }
1524 else
1525 { view.clearSpawnRangeHighlight(); }
1526 if (!lines.length)
1527 {
1528 tip.hidden = true;
1529 return;
1530 }
1531 tip.hidden = false;
1532 tip.textContent = lines.join("\n");
1533 const canvas = scene.canvas;
1534 const rect = canvas.getBoundingClientRect();
1535 const size = view.tileSize();
1536 const screenX = local.tileX * size + scene.cameraPosition.x + rect.left + size;
1537 const screenY = local.tileY * size + scene.cameraPosition.y + rect.top;
1538 tip.style.left = `${screenX}px`;
1539 tip.style.top = `${screenY}px`;
1540}
1541
1542async function main ()
1543{
1544 editorMinimap = initEditorMinimap({
1545 canvas: $("editor-minimap"),
1546 caption: $("editor-minimap-caption"),
1547 getCenter ()
1548 {
1549 return { chunkX, chunkY, dimensionId: selectedDimensionId };
1550 },
1551 onChunkClick (x, y)
1552 {
1553 loadNeighborhood(x, y);
1554 }
1555 });
1556
1557 const authStatus = await fetchAuthStatus();
1558 const signIn = document.getElementById("auth-sign-in");
1559 const signOut = document.getElementById("auth-sign-out");
1560 if (signIn)
1561 {
1562 signIn.hidden = !!authStatus?.authenticated;
1563 signIn.href = loginUrl("/editor");
1564 }
1565 if (signOut)
1566 {
1567 signOut.hidden = !authStatus?.authenticated;
1568 signOut.href = logoutUrl("/editor");
1569 }
1570 if (!authStatus.authenticated)
1571 {
1572 $("who").textContent = "Sign in required";
1573 $("error").textContent = "Sign in with your Tim Falken account to use the world editor.";
1574 return;
1575 }
1576
1577 const accountLabel = authStatus.username ?? authStatus.authSubject ?? "Signed in";
1578 $("who").textContent = `${accountLabel} · loading sprites…`;
1579
1580 catalog = await loadSpriteCatalog();
1581 imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));
1582 await preloadCatalogImages(game, catalog, {
1583 onProgress ({ loaded, total })
1584 {
1585 $("who").textContent = `${accountLabel} · loading sprites ${loaded}/${total}`;
1586 }
1587 });
1588 applySpriteSheets(game.images, catalog);
1589 scene = new Scene(250, 56, 64, 64);
1590 scene.backgroundColor.r = 0;
1591 scene.backgroundColor.g = 0;
1592 scene.backgroundColor.b = 0;
1593 game.loadScene(scene);
1594 view = new WorldView(game, scene, catalog);
1595 view.followPlayer = false;
1596 view.natureTintEnabled = false;
1597 view.setGraphicsPrefs(loadGraphicsSettings());
1598 syncSeasonControls(view.worldSeason ?? seasonIdAt());
1599 layoutScene();
1600
1601 function editorImageUrl (name)
1602 {
1603 const sprite = game.images[name];
1604 const html = sprite?.g_image;
1605 if (html && typeof html.toDataURL === "function")
1606 {
1607 try
1608 { return html.toDataURL("image/png"); }
1609 catch (_)
1610 { /* fall through */ }
1611 }
1612 return imageUrlByName.get(name) ?? null;
1613 }
1614
1615 const paletteOptions = {
1616 catalog,
1617 imageUrlFor: editorImageUrl,
1618 getSelection: () => tool,
1619 getDimensionId: () => selectedDimensionId,
1620 onSelect (next)
1621 {
1622 selectTool(next);
1623 }
1624 };
1625 palettePanel = initPalettePanel(paletteOptions);
1626 paletteModal = initPaletteModal(paletteOptions);
1627 selectTool(tool);
1628
1629 tileConfigModal = initTileConfigModal({
1630 socket: {
1631 send (payload)
1632 {
1633 socket?.send(payload);
1634 }
1635 },
1636 MessageType,
1637 getDialogues: () => dialoguesModal?.getDialogues?.() ?? [],
1638 getQuests: () => questsModal?.getQuests?.() ?? [],
1639 describeWorldTile,
1640 centerEditorOnTile,
1641 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
1642 id: dim.dimensionId,
1643 label: dim.displayName || dim.dimensionId,
1644 disabled: !!dim.deletedAt,
1645 hint: dim.deletedAt ? "soft-deleted" : undefined
1646 })),
1647 onSave (ctx, config)
1648 {
1649 if (!draft)
1650 { return; }
1651 if (ctx.kind === "doorway")
1652 {
1653 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1654 draft.blocks[index] = {
1655 typeId: BlockType.doorway,
1656 state: config.state || "door",
1657 config: {
1658 targetDimensionId: normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID),
1659 tileX: Number(config.tileX) || 0,
1660 tileY: Number(config.tileY) || 0
1661 }
1662 };
1663 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1664 ground: draft.grounds[index],
1665 block: draft.blocks[index],
1666 light: draft.light[index]
1667 });
1668 afterDraftMutation();
1669 return;
1670 }
1671 if (ctx.kind === "door")
1672 {
1673 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1674 const existing = draft.blocks[index];
1675 if (!existing || existing.typeId !== BlockType.door)
1676 { return; }
1677 const prev = existing.config && typeof existing.config === "object" ? { ...existing.config } : {};
1678 const nextConfig = normalizeDoorConfig({
1679 ...prev,
1680 when: config.when,
1681 blockedMessage: config.blockedMessage
1682 });
1683 draft.blocks[index] = {
1684 typeId: BlockType.door,
1685 state: existing.state,
1686 config: nextConfig
1687 };
1688 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1689 ground: draft.grounds[index],
1690 block: draft.blocks[index],
1691 light: draft.light[index]
1692 });
1693 afterDraftMutation();
1694 return;
1695 }
1696 if (ctx.kind === "fishing-spot")
1697 {
1698 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1699 const existing = draft.blocks[index];
1700 draft.blocks[index] = {
1701 typeId: BlockType.fishingSpot,
1702 state: existing?.state === "exhausted" ? "exhausted" : "fishing-spot",
1703 config: { fishes: [...(config.fishes ?? [])] }
1704 };
1705 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1706 ground: draft.grounds[index],
1707 block: draft.blocks[index],
1708 light: draft.light[index]
1709 });
1710 afterDraftMutation();
1711 return;
1712 }
1713 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1714 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
1715 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1716 afterDraftMutation();
1717 },
1718 onRemove (ctx)
1719 {
1720 if (!draft)
1721 { return; }
1722 if (ctx.kind === "door")
1723 {
1724 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1725 const existing = draft.blocks[index];
1726 if (!existing || existing.typeId !== BlockType.door)
1727 { return; }
1728 const prev = existing.config && typeof existing.config === "object" ? { ...existing.config } : {};
1729 delete prev.when;
1730 delete prev.requirements;
1731 delete prev.blockedMessage;
1732 delete prev.denyMessage;
1733 draft.blocks[index] = {
1734 typeId: BlockType.door,
1735 state: existing.state,
1736 config: normalizeDoorConfig(prev)
1737 };
1738 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1739 ground: draft.grounds[index],
1740 block: draft.blocks[index],
1741 light: draft.light[index]
1742 });
1743 afterDraftMutation();
1744 return;
1745 }
1746 if (ctx.kind === "doorway")
1747 {
1748 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1749 draft.blocks[index] = null;
1750 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1751 ground: draft.grounds[index],
1752 block: draft.blocks[index],
1753 light: draft.light[index]
1754 });
1755 afterDraftMutation();
1756 return;
1757 }
1758 if (ctx.kind === "fishing-spot")
1759 {
1760 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1761 draft.blocks[index] = null;
1762 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1763 ground: draft.grounds[index],
1764 block: draft.blocks[index],
1765 light: draft.light[index]
1766 });
1767 afterDraftMutation();
1768 return;
1769 }
1770 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1771 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1772 afterDraftMutation();
1773 }
1774 });
1775
1776 const ticker = new GameObject(0, 0, null, 10);
1777 ticker.update = (dt) =>
1778 {
1779 hoverLocal = null;
1780 const canvas = scene.canvas;
1781 const rect = canvas.getBoundingClientRect();
1782 const mouseX = GameInput.mousePosition.x - rect.left;
1783 const mouseY = GameInput.mousePosition.y - rect.top;
1784 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
1785 if (overCanvas && draft && !anyModalOpen())
1786 {
1787 const tile = view.screenToTile(mouseX, mouseY);
1788 const localX = tile.tileX - chunkX * CHUNK_SIZE;
1789 const localY = tile.tileY - chunkY * CHUNK_SIZE;
1790 const hoverChunkX = Math.floor(tile.tileX / CHUNK_SIZE);
1791 const hoverChunkY = Math.floor(tile.tileY / CHUNK_SIZE);
1792 updateHoverStatus({
1793 tileX: tile.tileX,
1794 tileY: tile.tileY,
1795 x: ((tile.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1796 y: ((tile.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1797 chunkX: hoverChunkX,
1798 chunkY: hoverChunkY
1799 });
1800 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
1801 {
1802 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
1803 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
1804 updateTooltip(hoverLocal);
1805 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
1806 { paintAt(localX, localY); }
1807 }
1808 else
1809 {
1810 hoverLocal = null;
1811 view.clearTilePreview();
1812 updateTooltip(null, { keepStatus: true });
1813 }
1814 }
1815 else
1816 {
1817 view.clearTilePreview();
1818 updateTooltip(null);
1819 }
1820 view.update(dt);
1821 frameNeighborhood();
1822 };
1823 scene.addObject(ticker);
1824 window.addEventListener("resize", layoutScene);
1825
1826 accountWhoLabel = accountLabel;
1827 $("who").textContent = `${accountLabel} · connecting…`;
1828
1829 function setWhoConnected (label, isAdmin)
1830 {
1831 accountWhoLabel = label;
1832 $("who").textContent = `${label}${isAdmin ? " · admin" : " · not admin"}`;
1833 }
1834
1835 function resubscribeEditorSession ({ reloadMap })
1836 {
1837 socket.send({ type: MessageType.editorLoadSettings });
1838 socket.send({ type: MessageType.editorLoadGameAdmins });
1839 socket.send({ type: MessageType.editorConsoleSubscribe });
1840 requestDimensions();
1841 if (reloadMap)
1842 {
1843 loadNeighborhood(chunkX, chunkY);
1844 return;
1845 }
1846 const coords = neighborhoodCoords(chunkX, chunkY).filter((coord) =>
1847 {
1848 if (coord.chunkX === chunkX && coord.chunkY === chunkY)
1849 { return !draft || !isSelectedChunkDirty(); }
1850 return !dirtyNeighborChunks.has(chunkKey(coord.chunkX, coord.chunkY));
1851 });
1852 requestChunks(coords);
1853 syncSaveButton();
1854 }
1855
1856 socket = new GameSocket(defaultSocketUrl(), (message) =>
1857 {
1858 if (message.type === MessageType.session)
1859 {
1860 const wasReady = sessionReady;
1861 sessionAuthSubject = message.authSubject ?? null;
1862 sessionReady = true;
1863 socket.notifySessionEstablished();
1864 const label = message.username ?? message.authSubject ?? "Unknown";
1865 setWhoConnected(label, !!message.isAdmin);
1866 if (!message.isAdmin)
1867 {
1868 $("error").textContent = "Admin access required.";
1869 return;
1870 }
1871 $("error").textContent = "";
1872 const restartBtn = document.getElementById("editor-restart-now");
1873 if (restartBtn)
1874 {
1875 restartBtn.hidden = false;
1876 restartBtn.disabled = false;
1877 }
1878 resubscribeEditorSession({ reloadMap: !wasReady });
1879 }
1880 else if (message.type === MessageType.editorSettings
1881 || message.type === MessageType.editorGameAdmins)
1882 { settingsModal.handleMessage(message); }
1883 else if (message.type === MessageType.editorConsoleSnapshot)
1884 { applyConsoleSnapshot(message.lines); }
1885 else if (message.type === MessageType.editorConsoleLine)
1886 { appendConsoleLine(message.line); }
1887 else if (message.type === MessageType.editorDimensions)
1888 {
1889 applyDimensionsList(message);
1890 }
1891 else if (message.type === MessageType.editorQuests)
1892 {
1893 questsModal?.handleMessage(message);
1894 settingsModal?.handleMessage(message);
1895 dialoguesModal?.handleMessage(message);
1896 tileConfigModal?.handleMessage(message);
1897 }
1898 else if (message.type === MessageType.editorDialogues)
1899 {
1900 dialoguesModal?.handleMessage(message);
1901 tileConfigModal?.handleMessage(message);
1902 questsModal?.handleMessage(message);
1903 }
1904 else if (message.type === MessageType.editorGiftCharacters
1905 || message.type === MessageType.editorGiftSent)
1906 { giftsModal?.handleMessage(message); }
1907 else if (message.type === MessageType.editorGlobalChangelog)
1908 { renderGlobalChangelog(message.changelog ?? []); }
1909 else if (message.type === MessageType.editorMinimap)
1910 { editorMinimap?.apply(message); }
1911 else if (message.type === MessageType.editorChunk)
1912 {
1913 const msgDim = normalizeDimensionId(message.dimensionId ?? selectedDimensionId);
1914 if (msgDim !== selectedDimensionId)
1915 { return; }
1916 const isSaveAck = pendingSaveAcks.delete(
1917 editorChunkSaveKey(msgDim, message.chunkX, message.chunkY)
1918 );
1919 if (isSaveAck)
1920 { requestEditorMinimap(); }
1921 if (message.settings)
1922 { view.setSettings(message.settings); }
1923 if (!inEditorView(message.chunkX, message.chunkY))
1924 { return; }
1925 if (message.chunkX === chunkX && message.chunkY === chunkY)
1926 { showSelectedChunk(message, { isSaveAck }); }
1927 else
1928 {
1929 const key = chunkKey(message.chunkX, message.chunkY);
1930 neighborSpawnersByChunk.set(key, message.data.spawners ?? []);
1931 if (!dirtyNeighborChunks.has(key))
1932 {
1933 view.applySnapshot(snapshotFromPayload(message));
1934 syncSpawnersOverlay(message.chunkX, message.chunkY, message.data.spawners);
1935 }
1936 }
1937 pruneView();
1938 }
1939 else if (message.type === MessageType.editorRevisionApplied)
1940 {
1941 applyInFlight = false;
1942 setRevisionState({
1943 activeRevisionId: message.activeRevisionId,
1944 pendingRevisionId: message.pendingRevisionId
1945 });
1946 const status = $("apply-status");
1947 status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`;
1948 status.className = "hint ok";
1949 requestDimensions();
1950 requestChunks(neighborhoodCoords(chunkX, chunkY));
1951 }
1952 else if (message.type === MessageType.forceLogout)
1953 {
1954 $("who").textContent = "Server restarting…";
1955 $("error").textContent = message.reason || "Server shutting down.";
1956 }
1957 else if (message.type === MessageType.error)
1958 {
1959 $("error").textContent = message.message;
1960 if (giftsModal?.isOpen())
1961 { giftsModal.handleError?.(message.message); }
1962 pendingCreatedDimensionId = null;
1963 pendingSaveAcks.clear();
1964 navigateAfterSave = false;
1965 dimensionPicker?.setValue(selectedDimensionId);
1966 if (applyInFlight)
1967 {
1968 applyInFlight = false;
1969 $("apply-status").textContent = "";
1970 $("apply-status").className = "hint";
1971 updateRevisionUI();
1972 }
1973 }
1974 }, {
1975 autoReconnect: true,
1976 onOpen ()
1977 {
1978 if (sessionReady)
1979 { $("who").textContent = `${accountWhoLabel} · reconnected, waiting for session…`; }
1980 },
1981 onReconnecting ({ attempt, delayMs })
1982 {
1983 $("who").textContent = `${accountWhoLabel} · reconnecting…`;
1984 if (sessionReady)
1985 {
1986 $("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept."
1987 + ` (attempt ${attempt}, retry in ${Math.round(delayMs / 100) / 10}s)`;
1988 }
1989 },
1990 onClose (event)
1991 {
1992 if (event.code === 1000)
1993 { return; }
1994 const authOrRestart = {
1995 4401: "Sign in expired or missing. Use Sign out, then sign in again.",
1996 1011: "Server could not verify your account with auth.timfalken.com.",
1997 1001: "Server is restarting. Reload this page in a moment."
1998 };
1999 if (authOrRestart[event.code])
2000 {
2001 sessionReady = false;
2002 $("who").textContent = "Connection failed";
2003 $("error").textContent = authOrRestart[event.code];
2004 return;
2005 }
2006 if (sessionReady)
2007 {
2008 $("who").textContent = `${accountWhoLabel} · reconnecting…`;
2009 $("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept.";
2010 persistDirtyDraftBackup();
2011 return;
2012 }
2013 const reasons = {
2014 1006: "Connection dropped before the editor session started."
2015 };
2016 const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`;
2017 $("who").textContent = "Connection failed";
2018 $("error").textContent = detail;
2019 },
2020 onError ()
2021 {
2022 if (sessionReady)
2023 {
2024 $("who").textContent = `${accountWhoLabel} · reconnecting…`;
2025 $("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept.";
2026 return;
2027 }
2028 $("who").textContent = "Connection failed";
2029 $("error").textContent = "Could not open a live connection to the server.";
2030 }
2031 });
2032 settingsModal = initSettingsModal({
2033 socket,
2034 MessageType,
2035 getAuthSubject: () => sessionAuthSubject,
2036 onApplied (settings)
2037 {
2038 view.setSettings(settings);
2039 },
2040 onPreviewNight (hour)
2041 {
2042 view.nightPreview = hour;
2043 $("night").value = String(hour);
2044 $("night-label").textContent = Number(hour).toFixed(1);
2045 }
2046 });
2047 dimensionPicker = initDimensionPickerModal({
2048 onSelect (id)
2049 {
2050 selectDimension(id);
2051 },
2052 onCreate (rawId, displayName)
2053 {
2054 const id = normalizeDimensionId(rawId);
2055 $("error").textContent = "";
2056 pendingCreatedDimensionId = id;
2057 socket.send({
2058 type: MessageType.editorCreateDimension,
2059 dimensionId: id,
2060 displayName: displayName ?? rawId.trim()
2061 });
2062 }
2063 });
2064 dimensionPicker.setOptions([{
2065 id: OVERWORLD_ID,
2066 label: "Overworld"
2067 }]);
2068 dimensionPicker.setValue(OVERWORLD_ID);
2069 dimensionSettings = initDimensionSettings({
2070 socket,
2071 MessageType,
2072 GROUND_DEFINITIONS,
2073 OVERWORLD_ID,
2074 getSelectedDimensionId: () => selectedDimensionId,
2075 getDimensionRecord: (id) => dimensionsById.get(id) ?? null,
2076 isOverworld
2077 });
2078
2079function collectEditorSpawners ()
2080{
2081 const byId = new Map();
2082 function add (row)
2083 {
2084 const id = String(row?.spawnerId ?? "").trim();
2085 if (!id)
2086 { return; }
2087 byId.set(id, {
2088 spawnerId: id,
2089 mobTypeId: row.mobTypeId ?? null,
2090 dimensionId: row.dimensionId ?? OVERWORLD_ID,
2091 tileX: row.tileX | 0,
2092 tileY: row.tileY | 0
2093 });
2094 }
2095 for (const row of questsModal?.getServerSpawners?.() ?? [])
2096 { add(row); }
2097 function addChunk (cx, cy, dim, spawners)
2098 {
2099 for (const entry of spawners ?? [])
2100 {
2101 const config = normalizeSpawnerConfig(entry.config, entry.config?.spawnerId);
2102 if (isItemSpawnerConfig(config))
2103 { continue; }
2104 add({
2105 spawnerId: config.spawnerId,
2106 mobTypeId: config.mobTypeId,
2107 dimensionId: dim,
2108 tileX: cx * CHUNK_SIZE + (entry.localX | 0),
2109 tileY: cy * CHUNK_SIZE + (entry.localY | 0)
2110 });
2111 }
2112 }
2113 if (draft)
2114 { addChunk(chunkX, chunkY, selectedDimensionId, draft.spawners); }
2115 for (const [key, data] of dirtyNeighborChunks)
2116 {
2117 const [cx, cy] = key.split(",").map(Number);
2118 if (!Number.isFinite(cx) || !Number.isFinite(cy))
2119 { continue; }
2120 addChunk(cx, cy, selectedDimensionId, data.spawners);
2121 }
2122 for (const [key, spawners] of neighborSpawnersByChunk)
2123 {
2124 const [cx, cy] = key.split(",").map(Number);
2125 if (!Number.isFinite(cx) || !Number.isFinite(cy))
2126 { continue; }
2127 addChunk(cx, cy, selectedDimensionId, spawners);
2128 }
2129 return [...byId.values()].sort((a, b) => a.spawnerId.localeCompare(b.spawnerId));
2130}
2131
2132 questsModal = initQuestsModal({
2133 socket,
2134 MessageType,
2135 describeWorldTile,
2136 centerEditorOnTile,
2137 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
2138 id: dim.dimensionId,
2139 label: dim.displayName || dim.dimensionId,
2140 disabled: dim.deletedAt != null,
2141 hint: dim.deletedAt != null ? "soft-deleted" : null
2142 })),
2143 getSpawnerOptions: (mobTypeId) => collectEditorSpawners().filter((row) =>
2144 !mobTypeId || String(row.mobTypeId) === String(mobTypeId)
2145 )
2146 });
2147 dialoguesModal = initDialoguesModal({
2148 socket,
2149 MessageType,
2150 describeWorldTile,
2151 centerEditorOnTile,
2152 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
2153 id: dim.dimensionId,
2154 label: dim.displayName || dim.dimensionId,
2155 disabled: dim.deletedAt != null,
2156 hint: dim.deletedAt != null ? "soft-deleted" : null
2157 })),
2158 getSpawnerOptions: (mobTypeId) => collectEditorSpawners().filter((row) =>
2159 !mobTypeId || String(row.mobTypeId) === String(mobTypeId)
2160 )
2161 });
2162 giftsModal = initGiftsModal({ socket, MessageType });
2163 initSidePanelTabs();
2164 game.startGame();
2165 useNearestNeighbour(scene, game.images);
2166 try
2167 { await socket.connect(); }
2168 catch (error)
2169 {
2170 // autoReconnect keeps retrying; surface the first failure without aborting the editor UI
2171 if (!sessionReady)
2172 {
2173 $("who").textContent = "Connection failed";
2174 $("error").textContent = error?.message || "Could not open a live connection to the server.";
2175 }
2176 }
2177}
2178
2179$("tool").textContent = selectedToolLabel();
2180$("tool-erase").addEventListener("click", () =>
2181{
2182 selectTool({ kind: "erase" });
2183});
2184
2185$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
2186$("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1));
2187$("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY));
2188$("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
2189$("copy-chunk")?.addEventListener("click", () => copySelectedChunk());
2190$("paste-chunk")?.addEventListener("click", () => pasteSelectedChunk());
2191$("clear-chunk")?.addEventListener("click", () => clearSelectedChunk());
2192
2193function isTypingTarget (target)
2194{
2195 if (!(target instanceof Element))
2196 { return false; }
2197 const tag = target.tagName;
2198 if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT")
2199 { return true; }
2200 return !!target.closest("[contenteditable='true']");
2201}
2202
2203window.addEventListener("keydown", (event) =>
2204{
2205 if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey)
2206 { return; }
2207 if (anyModalOpen() || isTypingTarget(event.target))
2208 { return; }
2209 if (event.key === "ArrowUp")
2210 {
2211 event.preventDefault();
2212 loadNeighborhood(chunkX, chunkY - 1);
2213 }
2214 else if (event.key === "ArrowDown")
2215 {
2216 event.preventDefault();
2217 loadNeighborhood(chunkX, chunkY + 1);
2218 }
2219 else if (event.key === "ArrowLeft")
2220 {
2221 event.preventDefault();
2222 loadNeighborhood(chunkX - 1, chunkY);
2223 }
2224 else if (event.key === "ArrowRight")
2225 {
2226 event.preventDefault();
2227 loadNeighborhood(chunkX + 1, chunkY);
2228 }
2229});
2230$("open").addEventListener("change", () =>
2231{
2232 if (isSelectedDimensionSoftDeleted())
2233 {
2234 $("open").checked = !!draft?.open;
2235 return;
2236 }
2237 if (draft)
2238 {
2239 draft.open = $("open").checked;
2240 view.setChunkOpen(chunkX, chunkY, draft.open);
2241 afterDraftMutation();
2242 }
2243});
2244$("save").addEventListener("click", () =>
2245{
2246 saveSelectedChunk();
2247});
2248$("unsaved-chunk-cancel")?.addEventListener("click", () =>
2249{
2250 pendingNavigate = null;
2251 navigateAfterSave = false;
2252 hideUnsavedModal();
2253});
2254$("unsaved-chunk-backdrop")?.addEventListener("click", () =>
2255{
2256 pendingNavigate = null;
2257 navigateAfterSave = false;
2258 hideUnsavedModal();
2259});
2260$("unsaved-chunk-discard")?.addEventListener("click", () =>
2261{
2262 const next = pendingNavigate;
2263 hideUnsavedModal();
2264 pendingNavigate = null;
2265 navigateAfterSave = false;
2266 discardUnsavedDraft();
2267 if (!next)
2268 { return; }
2269 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
2270 if (nextDim !== selectedDimensionId)
2271 {
2272 selectedDimensionId = nextDim;
2273 syncDimensionUi();
2274 clearNeighborhoodView();
2275 }
2276 doLoadNeighborhood(next.chunkX, next.chunkY);
2277});
2278$("unsaved-chunk-save")?.addEventListener("click", () =>
2279{
2280 hideUnsavedModal();
2281 if (!pendingNavigate)
2282 { return; }
2283 navigateAfterSave = true;
2284 if (!saveSelectedChunk())
2285 {
2286 navigateAfterSave = false;
2287 const next = pendingNavigate;
2288 pendingNavigate = null;
2289 if (next)
2290 {
2291 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
2292 if (nextDim !== selectedDimensionId)
2293 {
2294 selectedDimensionId = nextDim;
2295 syncDimensionUi();
2296 clearNeighborhoodView();
2297 }
2298 doLoadNeighborhood(next.chunkX, next.chunkY);
2299 }
2300 }
2301});
2302$("apply").addEventListener("click", () =>
2303{
2304 if (!pendingRevisionId || applyInFlight)
2305 { return; }
2306 $("error").textContent = "";
2307 const status = $("apply-status");
2308 status.textContent = "Applying…";
2309 status.className = "hint";
2310 applyInFlight = true;
2311 updateRevisionUI();
2312 socket.send({ type: MessageType.editorApplyRevision });
2313});
2314document.getElementById("editor-restart-now")?.addEventListener("click", () =>
2315{
2316 if (!socket)
2317 { return; }
2318 const ok = window.confirm(
2319 "Restart the server now?\n\nAll players and editor sessions will disconnect. "
2320 + "systemd will start a fresh process and pull the latest code from git."
2321 );
2322 if (!ok)
2323 { return; }
2324 const restartBtn = document.getElementById("editor-restart-now");
2325 if (restartBtn)
2326 { restartBtn.disabled = true; }
2327 $("who").textContent = "Restarting server…";
2328 $("error").textContent = "";
2329 socket.send({ type: MessageType.editorRestartNow });
2330});
2331$("night").addEventListener("input", () =>
2332{
2333 view.nightPreview = Number($("night").value);
2334 $("night-label").textContent = view.nightPreview.toFixed(1);
2335});
2336$("season").addEventListener("change", () =>
2337{
2338 applySeasonPreview($("season").value);
2339});
2340
2341function showGlobalChangelog (visible)
2342{
2343 const backdrop = $("global-changelog-backdrop");
2344 const modal = $("global-changelog-modal");
2345 if (backdrop)
2346 { backdrop.hidden = !visible; }
2347 if (modal)
2348 { modal.hidden = !visible; }
2349}
2350
2351function renderGlobalChangelog (changelog)
2352{
2353 const log = $("global-changelog");
2354 if (!log)
2355 { return; }
2356 log.innerHTML = "";
2357 if (!changelog.length)
2358 {
2359 log.innerHTML = "<p class=\"hint\">No edits logged yet.</p>";
2360 return;
2361 }
2362 const kindLabel = {
2363 chunk: "Chunk",
2364 settings: "Settings",
2365 quest: "Quest",
2366 dialogue: "Dialogue"
2367 };
2368 for (const entry of changelog)
2369 {
2370 const item = document.createElement("article");
2371 const who = entry.editorDisplayName || entry.editor_admin_id;
2372 const kind = kindLabel[entry.kind] || entry.kind || "Edit";
2373 const scope = entry.scope ? ` · ${entry.scope}` : "";
2374 item.innerHTML = `<header>${kind}${scope} · ${who} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
2375 const list = document.createElement("ul");
2376 for (const bullet of entry.diffEntries ?? [])
2377 {
2378 const li = document.createElement("li");
2379 li.textContent = bullet;
2380 list.append(li);
2381 }
2382 item.append(list);
2383 log.append(item);
2384 }
2385 log.scrollTop = 0;
2386}
2387
2388document.getElementById("open-global-changelog")?.addEventListener("click", () =>
2389{
2390 const log = $("global-changelog");
2391 if (log)
2392 { log.innerHTML = "<p class=\"hint\">Loading…</p>"; }
2393 showGlobalChangelog(true);
2394 socket.send({ type: MessageType.editorLoadGlobalChangelog });
2395});
2396document.getElementById("global-changelog-close")?.addEventListener("click", () => showGlobalChangelog(false));
2397document.getElementById("global-changelog-backdrop")?.addEventListener("click", () => showGlobalChangelog(false));
2398
2399function syncSeasonControls (season)
2400{
2401 const next = season === SeasonId.spring
2402 || season === SeasonId.fall
2403 || season === SeasonId.winter
2404 || season === SeasonId.summer
2405 ? season
2406 : seasonIdAt();
2407 $("season").value = next;
2408 view?.setWorldSeason(next);
2409}
2410
2411function applySeasonPreview (season)
2412{
2413 syncSeasonControls(season);
2414}
2415
2416function cycleToolState (direction)
2417{
2418 if (tool.kind === "erase" || tool.kind === "spawner")
2419 { return; }
2420 const layer = tool.kind === "ground" ? "ground" : "block";
2421 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
2422 if (definitionUsesNeighborConnect(def))
2423 { return; }
2424 if (tool.kind === "block" && def?.id === BlockType.flower)
2425 { return; }
2426 const allStates = statesForType(catalog, layer, def.key);
2427 const seasonal = seasonalCycleStates(allStates);
2428 const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
2429 if (states.length < 2)
2430 { return; }
2431 tool.state = cycleState(states, tool.state, direction);
2432 notifyToolChanged();
2433 const season = seasonIdFromVisualState(tool.state);
2434 if (season)
2435 { applySeasonPreview(season); }
2436 if (!draft || !hoverLocal)
2437 { return; }
2438 const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;
2439 if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId)
2440 { paintAt(hoverLocal.x, hoverLocal.y); }
2441 else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId)
2442 { paintAt(hoverLocal.x, hoverLocal.y); }
2443}
2444
2445document.addEventListener("wheel", (event) =>
2446{
2447 if (!scene?.canvas || anyModalOpen())
2448 { return; }
2449 const rect = scene.canvas.getBoundingClientRect();
2450 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
2451 { return; }
2452 event.preventDefault();
2453 if (event.shiftKey)
2454 {
2455 cycleToolState(event.deltaY < 0 ? 1 : -1);
2456 if (hoverLocal)
2457 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
2458 return;
2459 }
2460 zoomEditor(event.deltaY < 0 ? 1 : -1);
2461}, { passive: false });
2462
2463document.addEventListener("contextmenu", (event) =>
2464{
2465 if (!scene?.canvas || anyModalOpen() || !draft)
2466 { return; }
2467 const rect = scene.canvas.getBoundingClientRect();
2468 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
2469 { return; }
2470 event.preventDefault();
2471 const tile = view.screenToTile(event.clientX - rect.left, event.clientY - rect.top);
2472 const localX = tile.tileX - chunkX * CHUNK_SIZE;
2473 const localY = tile.tileY - chunkY * CHUNK_SIZE;
2474 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
2475 { return; }
2476 const spawner = spawnerAt(localX, localY);
2477 if (spawner)
2478 {
2479 const ctx = {
2480 localX,
2481 localY,
2482 tileX: tile.tileX,
2483 tileY: tile.tileY,
2484 config: { ...spawner.config }
2485 };
2486 if (isItemSpawnerConfig(spawner.config))
2487 { tileConfigModal.openItemSpawner(ctx); }
2488 else
2489 { tileConfigModal.openSpawner(ctx); }
2490 return;
2491 }
2492 const index = localY * CHUNK_SIZE + localX;
2493 const block = draft.blocks[index];
2494 if (block?.typeId === BlockType.doorway)
2495 {
2496 tileConfigModal.openDoorway({
2497 localX,
2498 localY,
2499 tileX: tile.tileX,
2500 tileY: tile.tileY,
2501 state: block.state ?? "door",
2502 config: block.config ? { ...block.config } : {}
2503 });
2504 return;
2505 }
2506 if (block?.typeId === BlockType.door)
2507 {
2508 tileConfigModal.openDoor({
2509 localX,
2510 localY,
2511 tileX: tile.tileX,
2512 tileY: tile.tileY,
2513 state: block.state,
2514 config: block.config ? { ...block.config } : {}
2515 });
2516 return;
2517 }
2518 if (block?.typeId === BlockType.fishingSpot)
2519 {
2520 tileConfigModal.openFishingSpot({
2521 localX,
2522 localY,
2523 tileX: tile.tileX,
2524 tileY: tile.tileY,
2525 config: block.config ? { ...block.config } : { fishes: [] }
2526 });
2527 }
2528});
2529
2530main().catch((error) =>
2531{
2532 $("error").textContent = error.message;
2533 console.error(error);
2534});