BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

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