BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

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