BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

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