BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

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