BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

main.js 41.3 KiB Download Raw
1import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_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} from "/shared/world/neighborConnect.js";
31import { GameSocket, defaultSocketUrl } from "../net/socket.js";
32import { fetchAuthStatus, loginUrl, logoutUrl } from "../net/auth.js";
33import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour, suppressFrameworkImageLoadedLogs } from "../render/sprites.js";
34
35suppressFrameworkImageLoadedLogs();
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 { createDimensionCombobox } from "./dimensionCombobox.js";
43import
44{
45 OVERWORLD_ID,
46 normalizeDimensionId,
47 isOverworld
48} from "/shared/world/dimensions.js";
49
50const game = new Game();
51let socket;
52let scene;
53let view;
54let draft = null;
55/** @type {string|null} JSON snapshot of last loaded/saved draft (grounds/blocks/spawners/open). */
56let draftBaseline = null;
57/** @type {{ chunkX: number, chunkY: number, dimensionId?: string }|null} */
58let pendingNavigate = null;
59/** When true, next matching editorChunk after save should navigate to pendingNavigate. */
60let navigateAfterSave = false;
61let chunkX = 0;
62let chunkY = 0;
63let selectedDimensionId = OVERWORLD_ID;
64/** @type {string|null} */
65let pendingCreatedDimensionId = null;
66/** @type {Map<string, object>} */
67let dimensionsById = new Map();
68let dimensionCombo = null;
69let dimensionSettings = null;
70let tool = { kind: "ground", typeId: GroundType.grass, state: null };
71let settingsModal;
72let paletteModal;
73let tileConfigModal;
74let questsModal;
75let dialoguesModal;
76let catalog = { grounds: {}, blocks: {}, images: [] };
77let imageUrlByName = new Map();
78let hoverLocal = null;
79let editorZoom = null;
80let activeRevisionId = null;
81let pendingRevisionId = null;
82let applyInFlight = false;
83/** @type {string|null} */
84let sessionAuthSubject = null;
85const EDITOR_ZOOM_MIN = 0.25;
86const EDITOR_ZOOM_MAX = 8;
87const EDITOR_ZOOM_STEP = 1.12;
88const CONSOLE_MAX_LINES = 2000;
89
90function $ (id)
91{
92 return document.getElementById(id);
93}
94
95function formatConsoleTime (t)
96{
97 try
98 { return new Date(t).toLocaleTimeString(); }
99 catch
100 { return ""; }
101}
102
103function appendConsoleLine (entry, { scroll = true } = {})
104{
105 const pre = $("editor-console");
106 if (!pre || !entry)
107 { return; }
108 const line = document.createElement("div");
109 const level = entry.level || "info";
110 line.className = `console-${level}`;
111 line.textContent = `[${formatConsoleTime(entry.t)}] ${entry.text ?? ""}`;
112 pre.append(line);
113 while (pre.childElementCount > CONSOLE_MAX_LINES)
114 { pre.firstChild?.remove(); }
115 if (scroll)
116 { pre.scrollTop = pre.scrollHeight; }
117}
118
119function applyConsoleSnapshot (lines)
120{
121 const pre = $("editor-console");
122 if (!pre)
123 { return; }
124 pre.replaceChildren();
125 for (const entry of lines ?? [])
126 { appendConsoleLine(entry, { scroll: false }); }
127 pre.scrollTop = pre.scrollHeight;
128}
129
130function initSidePanelTabs ()
131{
132 const tabs = document.querySelectorAll(".side-panel-tab");
133 const bodies = document.querySelectorAll("[data-side-panel-body]");
134 function activate (name)
135 {
136 for (const tab of tabs)
137 {
138 const on = tab.dataset.sidePanel === name;
139 tab.classList.toggle("active", on);
140 tab.setAttribute("aria-selected", on ? "true" : "false");
141 }
142 for (const body of bodies)
143 { body.hidden = body.dataset.sidePanelBody !== name; }
144 if (name === "console")
145 {
146 const pre = $("editor-console");
147 if (pre)
148 { pre.scrollTop = pre.scrollHeight; }
149 }
150 }
151 for (const tab of tabs)
152 {
153 tab.addEventListener("click", () => activate(tab.dataset.sidePanel));
154 }
155 $("console-clear")?.addEventListener("click", () =>
156 {
157 const pre = $("editor-console");
158 if (pre)
159 { pre.replaceChildren(); }
160 });
161 activate("changelog");
162}
163
164function selectedToolLabel ()
165{
166 if (tool.kind === "erase")
167 { return "Erase block"; }
168 if (tool.kind === "spawner")
169 {
170 const def = mobDefinition(tool.mobTypeId);
171 return `Spawner · ${def?.displayName ?? tool.mobTypeId}`;
172 }
173 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
174 const layer = tool.kind === "ground" ? "ground" : "block";
175 const states = statesForType(catalog, layer, def.key);
176 const state = resolveState(states, tool.state);
177 if (tool.kind === "block" && def.id === BlockType.flower)
178 { return "Flower"; }
179 if (tool.kind === "block" && def.id === BlockType.boulder)
180 {
181 const entry = listPlaceableBlockPaletteEntries(catalog)
182 .find((row) => row.typeId === def.id && row.state === state);
183 if (entry)
184 { return entry.displayName; }
185 }
186 if (states.length > 1)
187 { return `${def.displayName} (${state})`; }
188 return def.displayName;
189}
190
191function selectTool (next)
192{
193 if (next.kind === "erase")
194 {
195 tool = { kind: "erase" };
196 return;
197 }
198 if (next.kind === "spawner")
199 {
200 tool = { kind: "spawner", mobTypeId: next.mobTypeId };
201 return;
202 }
203 const layer = next.kind === "ground" ? "ground" : "block";
204 const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
205 tool = {
206 kind: next.kind,
207 typeId: next.typeId,
208 state: next.state ?? defaultStateForType(catalog, layer, def.key)
209 };
210}
211
212function placeableToolState ()
213{
214 if (tool.kind === "erase" || tool.kind === "spawner")
215 { return null; }
216 const layer = tool.kind === "ground" ? "ground" : "block";
217 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
218 return resolveState(statesForType(catalog, layer, def.key), tool.state);
219}
220
221function previewFromTool ()
222{
223 if (tool.kind === "erase")
224 { return { block: null }; }
225 if (tool.kind === "spawner")
226 { return {}; }
227 const state = placeableToolState();
228 if (tool.kind === "ground")
229 { return { ground: { typeId: tool.typeId, state } }; }
230 return { block: { typeId: tool.typeId, state, config: null } };
231}
232
233function inEditorView (x, y)
234{
235 return Math.abs(x - chunkX) <= VISIBLE_CHUNK_RADIUS && Math.abs(y - chunkY) <= VISIBLE_CHUNK_RADIUS;
236}
237
238function neighborhoodCoords (centerX, centerY)
239{
240 const coords = [];
241 for (let dy = -VISIBLE_CHUNK_RADIUS; dy <= VISIBLE_CHUNK_RADIUS; dy++)
242 {
243 for (let dx = -VISIBLE_CHUNK_RADIUS; dx <= VISIBLE_CHUNK_RADIUS; dx++)
244 { coords.push({ chunkX: centerX + dx, chunkY: centerY + dy }); }
245 }
246 return coords;
247}
248
249function snapshotFromPayload (payload)
250{
251 return {
252 chunkX: payload.chunkX,
253 chunkY: payload.chunkY,
254 open: payload.data.open,
255 closedEdges: payload.closedEdges,
256 grounds: payload.data.grounds,
257 blocks: payload.data.blocks,
258 light: payload.data.light,
259 entities: []
260 };
261}
262
263function syncSpawnersOverlay (cx, cy, spawners)
264{
265 view.setEditorSpawners(cx, cy, spawners ?? [], (mobTypeId) => mobSpriteName(mobTypeId));
266}
267
268function spawnerAt (localX, localY)
269{
270 return (draft?.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
271}
272
273function draftPersistable ()
274{
275 if (!draft)
276 { return null; }
277 return {
278 open: !!draft.open,
279 grounds: draft.grounds,
280 blocks: draft.blocks,
281 spawners: draft.spawners ?? []
282 };
283}
284
285function captureDraftBaseline ()
286{
287 const payload = draftPersistable();
288 draftBaseline = payload ? JSON.stringify(payload) : null;
289 syncSaveButton();
290}
291
292function isDraftDirty ()
293{
294 if (!draft || draftBaseline == null)
295 { return false; }
296 return JSON.stringify(draftPersistable()) !== draftBaseline;
297}
298
299function syncSaveButton ()
300{
301 const btn = $("save");
302 if (!btn)
303 { return; }
304 const softDeleted = isSelectedDimensionSoftDeleted();
305 const dirty = isDraftDirty();
306 btn.disabled = !dirty || softDeleted;
307 btn.classList.toggle("save-dirty", dirty && !softDeleted);
308 btn.title = softDeleted
309 ? "Cannot save while this dimension is soft-deleted"
310 : dirty
311 ? "Save unsaved chunk changes"
312 : "No unsaved changes";
313}
314
315function afterDraftMutation ()
316{
317 syncSaveButton();
318}
319
320function showUnsavedModal (target)
321{
322 pendingNavigate = target;
323 $("unsaved-chunk-backdrop").hidden = false;
324 $("unsaved-chunk-modal").hidden = false;
325}
326
327function hideUnsavedModal ()
328{
329 $("unsaved-chunk-backdrop").hidden = true;
330 $("unsaved-chunk-modal").hidden = true;
331}
332
333function saveSelectedChunk ()
334{
335 if (!draft || !isDraftDirty())
336 { return false; }
337 if (isSelectedDimensionSoftDeleted())
338 {
339 $("error").textContent = "Cannot save while this dimension is soft-deleted.";
340 return false;
341 }
342 $("error").textContent = "";
343 $("apply-status").textContent = "";
344 $("apply-status").className = "hint";
345 socket.send({
346 type: MessageType.editorSaveChunk,
347 chunkX,
348 chunkY,
349 dimensionId: selectedDimensionId,
350 draft: {
351 open: $("open").checked,
352 grounds: draft.grounds,
353 blocks: draft.blocks,
354 spawners: draft.spawners ?? []
355 }
356 });
357 requestNeighbors();
358 return true;
359}
360
361function isSelectedDimensionSoftDeleted ()
362{
363 const record = dimensionsById.get(selectedDimensionId);
364 return record?.deletedAt != null;
365}
366
367function formatPurgeHint (record)
368{
369 if (!record?.purgeAfter)
370 { return "Soft-deleted — painting disabled."; }
371 const when = new Date(record.purgeAfter);
372 return `Soft-deleted — purges ${when.toLocaleString()} (painting disabled).`;
373}
374
375function syncDimensionUi ()
376{
377 const record = dimensionsById.get(selectedDimensionId);
378 const softDeleted = record?.deletedAt != null;
379 const hint = $("dimension-purge-hint");
380 if (hint)
381 {
382 hint.hidden = !softDeleted;
383 hint.textContent = softDeleted ? formatPurgeHint(record) : "";
384 }
385 const openToggle = $("open");
386 if (openToggle)
387 { openToggle.disabled = softDeleted; }
388 dimensionCombo?.setValue(selectedDimensionId);
389 dimensionSettings?.refresh();
390 syncSaveButton();
391}
392
393function applyDimensionsList (payload)
394{
395 const list = Array.isArray(payload?.dimensions) ? payload.dimensions : [];
396 dimensionsById = new Map(list.map((dim) => [dim.dimensionId, dim]));
397 if (!dimensionsById.has(OVERWORLD_ID))
398 {
399 dimensionsById.set(OVERWORLD_ID, {
400 dimensionId: OVERWORLD_ID,
401 displayName: "Overworld",
402 lightingMode: "dayNight",
403 seasonMode: "auto",
404 defaultGroundTypeId: 1,
405 deletedAt: null,
406 purgeAfter: null
407 });
408 }
409 const options = [...dimensionsById.values()].map((dim) => ({
410 id: dim.dimensionId,
411 label: dim.displayName || dim.dimensionId,
412 disabled: dim.deletedAt != null,
413 hint: dim.deletedAt != null ? formatPurgeHint(dim) : null
414 }));
415 dimensionCombo?.setOptions(options);
416 const createdId = pendingCreatedDimensionId;
417 pendingCreatedDimensionId = null;
418 if (createdId && dimensionsById.has(createdId))
419 {
420 setRevisionState({
421 activeRevisionId: payload.activeRevisionId,
422 pendingRevisionId: payload.pendingRevisionId
423 });
424 selectDimension(createdId, { force: true });
425 return;
426 }
427 if (!dimensionsById.has(selectedDimensionId))
428 { selectedDimensionId = OVERWORLD_ID; }
429 setRevisionState({
430 activeRevisionId: payload.activeRevisionId,
431 pendingRevisionId: payload.pendingRevisionId
432 });
433 syncDimensionUi();
434 if (!isDraftDirty())
435 { requestChunks(neighborhoodCoords(chunkX, chunkY)); }
436}
437
438function requestDimensions ()
439{
440 socket.send({ type: MessageType.editorListDimensions });
441}
442
443function selectDimension (dimensionId, { force = false } = {})
444{
445 const nextId = normalizeDimensionId(dimensionId);
446 if (!force && nextId === selectedDimensionId)
447 { return; }
448 if (!force && isDraftDirty())
449 {
450 showUnsavedModal({ chunkX, chunkY, dimensionId: nextId });
451 dimensionCombo?.setValue(selectedDimensionId);
452 return;
453 }
454 selectedDimensionId = nextId;
455 syncDimensionUi();
456 clearNeighborhoodView();
457 doLoadNeighborhood(chunkX, chunkY);
458}
459
460function clearNeighborhoodView ()
461{
462 draft = null;
463 draftBaseline = null;
464 if (!view)
465 { return; }
466 for (const key of [...view.chunks.keys()])
467 {
468 const [x, y] = key.split(",").map(Number);
469 view.removeChunk(x, y);
470 }
471 view.clearEditorSpawners?.();
472 syncSaveButton();
473}
474
475function paintAt (localX, localY)
476{
477 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
478 { return; }
479 if (isSelectedDimensionSoftDeleted())
480 { return; }
481 const index = localY * CHUNK_SIZE + localX;
482 const state = placeableToolState();
483 if (tool.kind === "ground")
484 { draft.grounds[index] = { typeId: tool.typeId, state }; }
485 else if (tool.kind === "erase")
486 {
487 const removed = draft.blocks[index];
488 draft.blocks[index] = null;
489 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
490 ground: draft.grounds[index],
491 block: draft.blocks[index],
492 light: draft.light[index]
493 });
494 if (removed && definitionUsesNeighborConnect(BLOCK_DEFINITIONS[removed.typeId]))
495 { refreshNeighborConnect(localX, localY, removed.typeId); }
496 afterDraftMutation();
497 return;
498 }
499 else if (tool.kind === "spawner")
500 {
501 const existing = spawnerAt(localX, localY);
502 const spawnerId = existing?.config?.spawnerId ?? `${chunkX}:${chunkY}:${index}`;
503 const entry = {
504 localX,
505 localY,
506 config: normalizeSpawnerConfig({
507 ...defaultSpawnerConfig(spawnerId, tool.mobTypeId),
508 ...(existing?.config ?? {}),
509 spawnerId,
510 mobTypeId: tool.mobTypeId
511 }, spawnerId)
512 };
513 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY);
514 draft.spawners.push(entry);
515 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
516 afterDraftMutation();
517 return;
518 }
519 else
520 {
521 const def = BLOCK_DEFINITIONS[tool.typeId];
522 let nextState = definitionUsesNeighborConnect(def)
523 ? composeNeighborConnectState(def, state, 0)
524 : state;
525 if (def?.id === BlockType.flower)
526 { nextState = flowerBlockState(randomFlowerColorId()); }
527 const config = def?.id === BlockType.doorway
528 ? {
529 targetDimensionId: selectedDimensionId,
530 tileX: chunkX * CHUNK_SIZE + localX,
531 tileY: chunkY * CHUNK_SIZE + localY
532 }
533 : null;
534 if (def?.id === BlockType.doorway && !nextState)
535 { nextState = "door"; }
536 draft.blocks[index] = { typeId: tool.typeId, state: nextState, config };
537 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
538 ground: draft.grounds[index],
539 block: draft.blocks[index],
540 light: draft.light[index]
541 });
542 if (definitionUsesNeighborConnect(def))
543 { refreshNeighborConnect(localX, localY, tool.typeId); }
544 afterDraftMutation();
545 return;
546 }
547 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
548 ground: draft.grounds[index],
549 block: draft.blocks[index],
550 light: draft.light[index]
551 });
552 afterDraftMutation();
553}
554
555/** Recompute neighbor-connect masks for a type around a local tile (same chunk). */
556function refreshNeighborConnect (localX, localY, typeId)
557{
558 const def = BLOCK_DEFINITIONS[typeId];
559 if (!draft || !definitionUsesNeighborConnect(def))
560 { return; }
561 const cells = [[localX, localY]];
562 for (const [dx, dy] of [[0, -1], [1, 0], [0, 1], [-1, 0]])
563 { cells.push([localX + dx, localY + dy]); }
564 for (const [lx, ly] of cells)
565 {
566 if (lx < 0 || ly < 0 || lx >= CHUNK_SIZE || ly >= CHUNK_SIZE)
567 { continue; }
568 const index = ly * CHUNK_SIZE + lx;
569 const block = draft.blocks[index];
570 if (!block || block.typeId !== typeId)
571 { continue; }
572 const mask = computeNeighborConnectMask((dx, dy) =>
573 {
574 const nx = lx + dx;
575 const ny = ly + dy;
576 if (nx < 0 || ny < 0 || nx >= CHUNK_SIZE || ny >= CHUNK_SIZE)
577 { return false; }
578 const neighbor = draft.blocks[ny * CHUNK_SIZE + nx];
579 return neighborConnectBlocksMatch(block, neighbor, def);
580 });
581 block.state = composeNeighborConnectState(def, block.state, mask);
582 view.updateAuthoredTile(chunkX, chunkY, lx, ly, {
583 ground: draft.grounds[index],
584 block: draft.blocks[index],
585 light: draft.light[index]
586 });
587 }
588}
589
590function updateRevisionUI ()
591{
592 const applyBtn = $("apply");
593 $("revision").textContent = `active ${activeRevisionId ?? "?"}` +
594 (pendingRevisionId ? ` · pending ${pendingRevisionId}` : " · no pending revision");
595 if (applyBtn)
596 {
597 applyBtn.disabled = !pendingRevisionId || applyInFlight;
598 applyBtn.title = pendingRevisionId
599 ? "Reload the live world with the pending map revision"
600 : "Save a chunk first to create a pending revision";
601 }
602}
603
604function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pending })
605{
606 if (active != null)
607 { activeRevisionId = active; }
608 pendingRevisionId = pending ?? null;
609 updateRevisionUI();
610}
611
612function showSelectedChunk (payload)
613{
614 draft = {
615 open: payload.data.open,
616 grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
617 blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)),
618 light: payload.data.light.slice(),
619 spawners: (payload.data.spawners ?? []).map((entry) => ({
620 localX: entry.localX,
621 localY: entry.localY,
622 config: { ...entry.config }
623 }))
624 };
625 $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`;
626 $("open").checked = draft.open;
627 setRevisionState({
628 activeRevisionId: payload.activeRevisionId,
629 pendingRevisionId: payload.pendingRevisionId
630 });
631 $("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)";
632 const log = $("changelog");
633 log.innerHTML = "";
634 for (const entry of payload.changelog ?? [])
635 {
636 const item = document.createElement("article");
637 item.innerHTML = `<header>${entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
638 const list = document.createElement("ul");
639 for (const bullet of entry.diffEntries)
640 {
641 const li = document.createElement("li");
642 li.textContent = bullet;
643 list.append(li);
644 }
645 item.append(list);
646 log.append(item);
647 }
648 view.applySnapshot(snapshotFromPayload(payload));
649 syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);
650 captureDraftBaseline();
651 if (navigateAfterSave && pendingNavigate)
652 {
653 const next = pendingNavigate;
654 navigateAfterSave = false;
655 pendingNavigate = null;
656 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
657 if (nextDim !== selectedDimensionId)
658 {
659 selectedDimensionId = nextDim;
660 syncDimensionUi();
661 clearNeighborhoodView();
662 }
663 doLoadNeighborhood(next.chunkX, next.chunkY);
664 }
665}
666
667function pruneView ()
668{
669 for (const key of [...view.chunks.keys()])
670 {
671 const [x, y] = key.split(",").map(Number);
672 if (!inEditorView(x, y))
673 { view.removeChunk(x, y); }
674 }
675}
676
677function frameNeighborhood ()
678{
679 const size = view.tileSize();
680 view.followPlayer = false;
681 const centerX = (chunkX + 0.5) * CHUNK_SIZE * size;
682 const centerY = (chunkY + 0.5) * CHUNK_SIZE * size;
683 view.scene.cameraPosition.x = view.scene.real_size.x / 2 - centerX;
684 view.scene.cameraPosition.y = view.scene.real_size.y / 2 - centerY;
685 updateSelectionBorder();
686}
687
688function updateSelectionBorder ()
689{
690 const border = $("selection-border");
691 const canvas = scene?.canvas;
692 if (!border || !canvas)
693 { return; }
694
695 const rect = canvas.getBoundingClientRect();
696 const size = view.tileSize();
697 const chunkPx = CHUNK_SIZE * size;
698 const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x;
699 const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y;
700 border.style.left = `${rect.left + screenLeft}px`;
701 border.style.top = `${rect.top + screenTop}px`;
702 border.style.width = `${chunkPx}px`;
703 border.style.height = `${chunkPx}px`;
704}
705
706function layoutScene ()
707{
708 const header = document.querySelector("body > header");
709 const aside = document.querySelector("body > aside");
710 const sidePanels = $("side-panels") || $("changelog-wrap");
711 const top = header.offsetHeight;
712 aside.style.top = `${top}px`;
713 sidePanels.style.top = `${top}px`;
714 const left = aside.offsetWidth;
715 const right = sidePanels.offsetWidth;
716 const width = Math.max(64, window.innerWidth - left - right);
717 const height = Math.max(64, window.innerHeight - top);
718 scene.position.x = left;
719 scene.position.y = top;
720 scene.size.x = width;
721 scene.size.y = height;
722 scene.g_fixSize();
723 useNearestNeighbour(scene, game.images);
724 const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX);
725 if (editorZoom == null)
726 { editorZoom = fit; }
727 else
728 { editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, editorZoom)); }
729 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
730 frameNeighborhood();
731}
732
733function zoomEditor (direction)
734{
735 if (!view)
736 { return; }
737 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
738 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
739 scheduleEditorZoom();
740}
741
742let editorZoomRaf = 0;
743function scheduleEditorZoom ()
744{
745 if (editorZoomRaf)
746 { return; }
747 editorZoomRaf = requestAnimationFrame(() =>
748 {
749 editorZoomRaf = 0;
750 if (!view)
751 { return; }
752 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
753 frameNeighborhood();
754 });
755}
756
757function requestChunks (coords)
758{
759 if (!socket?.socket || socket.socket.readyState !== WebSocket.OPEN)
760 { return; }
761 for (const coord of coords)
762 {
763 try
764 {
765 socket.send({
766 type: MessageType.editorLoadChunk,
767 chunkX: coord.chunkX,
768 chunkY: coord.chunkY,
769 dimensionId: selectedDimensionId
770 });
771 }
772 catch (_)
773 { break; }
774 }
775}
776
777function doLoadNeighborhood (x, y)
778{
779 chunkX = x;
780 chunkY = y;
781 $("coords").textContent = `${chunkX}, ${chunkY}`;
782 requestChunks(neighborhoodCoords(x, y));
783}
784
785function loadNeighborhood (x, y)
786{
787 if ((x !== chunkX || y !== chunkY) && isDraftDirty())
788 {
789 showUnsavedModal({ chunkX: x, chunkY: y, dimensionId: selectedDimensionId });
790 return;
791 }
792 doLoadNeighborhood(x, y);
793}
794
795function requestNeighbors ()
796{
797 requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
798}
799
800function anyModalOpen ()
801{
802 return settingsModal?.isOpen()
803 || paletteModal?.isOpen()
804 || tileConfigModal?.isOpen()
805 || questsModal?.isOpen()
806 || dialoguesModal?.isOpen()
807 || !$("unsaved-chunk-modal")?.hidden;
808}
809
810function updateHoverStatus (local)
811{
812 const el = $("hover-status-text");
813 if (!el)
814 { return; }
815 if (!local)
816 {
817 el.textContent = "Hover a tile for coordinates";
818 return;
819 }
820 const hoverChunkX = local.chunkX ?? Math.floor(local.tileX / CHUNK_SIZE);
821 const hoverChunkY = local.chunkY ?? Math.floor(local.tileY / CHUNK_SIZE);
822 el.textContent = `Tile (${local.tileX}, ${local.tileY}) · Chunk (${hoverChunkX}, ${hoverChunkY})`;
823}
824
825function updateTooltip (local, options = {})
826{
827 if (!options.keepStatus)
828 { updateHoverStatus(local); }
829 const tip = $("tile-tooltip");
830 if (!tip || !local || !draft)
831 {
832 if (tip)
833 { tip.hidden = true; }
834 view?.clearSpawnRangeHighlight();
835 return;
836 }
837 const block = normalizeBlock(draft.blocks[local.y * CHUNK_SIZE + local.x]);
838 const spawner = spawnerAt(local.x, local.y);
839 const lines = [];
840 if (block)
841 {
842 const def = BLOCK_DEFINITIONS[block.typeId];
843 lines.push(def?.displayName ?? `Block ${block.typeId}`);
844 if (block.config && Object.keys(block.config).length)
845 {
846 for (const [key, value] of Object.entries(block.config))
847 { lines.push(`${key}: ${value}`); }
848 }
849 }
850 if (spawner)
851 {
852 const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId);
853 const mob = mobDefinition(config.mobTypeId);
854 lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`);
855 lines.push(`maxAlive: ${config.maxAlive}`);
856 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
857 lines.push(`wanderRange: ${config.maxWanderRangeTiles}`);
858 lines.push(`id: ${config.spawnerId}`);
859 view.setSpawnRangeHighlight(
860 local.tileX,
861 local.tileY,
862 config.spawnRangeTiles,
863 config.maxWanderRangeTiles
864 );
865 }
866 else
867 { view.clearSpawnRangeHighlight(); }
868 if (!lines.length)
869 {
870 tip.hidden = true;
871 return;
872 }
873 tip.hidden = false;
874 tip.textContent = lines.join("\n");
875 const canvas = scene.canvas;
876 const rect = canvas.getBoundingClientRect();
877 const size = view.tileSize();
878 const screenX = local.tileX * size + scene.cameraPosition.x + rect.left + size;
879 const screenY = local.tileY * size + scene.cameraPosition.y + rect.top;
880 tip.style.left = `${screenX}px`;
881 tip.style.top = `${screenY}px`;
882}
883
884async function main ()
885{
886 const authStatus = await fetchAuthStatus();
887 const signIn = document.getElementById("auth-sign-in");
888 const signOut = document.getElementById("auth-sign-out");
889 if (signIn)
890 {
891 signIn.hidden = !!authStatus?.authenticated;
892 signIn.href = loginUrl("/editor");
893 }
894 if (signOut)
895 {
896 signOut.hidden = !authStatus?.authenticated;
897 signOut.href = logoutUrl("/editor");
898 }
899 if (!authStatus.authenticated)
900 {
901 $("who").textContent = "Sign in required";
902 $("error").textContent = "Sign in with your Tim Falken account to use the world editor.";
903 return;
904 }
905
906 const accountLabel = authStatus.username ?? authStatus.email ?? authStatus.authSubject ?? "Signed in";
907 $("who").textContent = `${accountLabel} · loading sprites…`;
908
909 catalog = await loadSpriteCatalog();
910 imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));
911 await preloadCatalogImages(game, catalog, {
912 onProgress ({ loaded, total })
913 {
914 $("who").textContent = `${accountLabel} · loading sprites ${loaded}/${total}`;
915 }
916 });
917 applySpriteSheets(game.images, catalog);
918 scene = new Scene(250, 56, 64, 64);
919 game.loadScene(scene);
920 view = new WorldView(game, scene, catalog);
921 view.followPlayer = false;
922 view.setGraphicsPrefs(loadGraphicsSettings());
923 syncSeasonControls(view.worldSeason ?? seasonIdAt());
924 layoutScene();
925 selectTool(tool);
926 $("tool").textContent = selectedToolLabel();
927
928 paletteModal = initPaletteModal({
929 catalog,
930 imageUrlFor (name)
931 {
932 const sprite = game.images[name];
933 const html = sprite?.g_image;
934 if (html && typeof html.toDataURL === "function")
935 {
936 try
937 { return html.toDataURL("image/png"); }
938 catch (_)
939 { /* fall through */ }
940 }
941 return imageUrlByName.get(name) ?? null;
942 },
943 onSelect (next)
944 {
945 selectTool(next);
946 $("tool").textContent = selectedToolLabel();
947 }
948 });
949
950 tileConfigModal = initTileConfigModal({
951 socket: {
952 send (payload)
953 {
954 socket?.send(payload);
955 }
956 },
957 MessageType,
958 getDialogues: () => dialoguesModal?.getDialogues?.() ?? [],
959 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
960 id: dim.dimensionId,
961 label: dim.displayName || dim.dimensionId,
962 disabled: !!dim.deletedAt,
963 hint: dim.deletedAt ? "soft-deleted" : undefined
964 })),
965 onSave (ctx, config)
966 {
967 if (!draft)
968 { return; }
969 if (ctx.kind === "doorway")
970 {
971 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
972 draft.blocks[index] = {
973 typeId: BlockType.doorway,
974 state: config.state || "door",
975 config: {
976 targetDimensionId: normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID),
977 tileX: Number(config.tileX) || 0,
978 tileY: Number(config.tileY) || 0
979 }
980 };
981 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
982 ground: draft.grounds[index],
983 block: draft.blocks[index],
984 light: draft.light[index]
985 });
986 afterDraftMutation();
987 return;
988 }
989 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
990 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
991 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
992 afterDraftMutation();
993 },
994 onRemove (ctx)
995 {
996 if (!draft)
997 { return; }
998 if (ctx.kind === "doorway")
999 {
1000 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1001 draft.blocks[index] = null;
1002 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1003 ground: draft.grounds[index],
1004 block: draft.blocks[index],
1005 light: draft.light[index]
1006 });
1007 afterDraftMutation();
1008 return;
1009 }
1010 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1011 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1012 afterDraftMutation();
1013 }
1014 });
1015
1016 const ticker = new GameObject(0, 0, null, 10);
1017 ticker.update = (dt) =>
1018 {
1019 hoverLocal = null;
1020 const canvas = scene.canvas;
1021 const rect = canvas.getBoundingClientRect();
1022 const mouseX = GameInput.mousePosition.x - rect.left;
1023 const mouseY = GameInput.mousePosition.y - rect.top;
1024 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
1025 if (overCanvas && draft && !anyModalOpen())
1026 {
1027 const tile = view.screenToTile(mouseX, mouseY);
1028 const localX = tile.tileX - chunkX * CHUNK_SIZE;
1029 const localY = tile.tileY - chunkY * CHUNK_SIZE;
1030 const hoverChunkX = Math.floor(tile.tileX / CHUNK_SIZE);
1031 const hoverChunkY = Math.floor(tile.tileY / CHUNK_SIZE);
1032 updateHoverStatus({
1033 tileX: tile.tileX,
1034 tileY: tile.tileY,
1035 x: ((tile.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1036 y: ((tile.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1037 chunkX: hoverChunkX,
1038 chunkY: hoverChunkY
1039 });
1040 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
1041 {
1042 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
1043 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
1044 updateTooltip(hoverLocal);
1045 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
1046 { paintAt(localX, localY); }
1047 }
1048 else
1049 {
1050 hoverLocal = null;
1051 view.clearTilePreview();
1052 updateTooltip(null, { keepStatus: true });
1053 }
1054 }
1055 else
1056 {
1057 view.clearTilePreview();
1058 updateTooltip(null);
1059 }
1060 view.update(dt);
1061 frameNeighborhood();
1062 };
1063 scene.addObject(ticker);
1064 window.addEventListener("resize", layoutScene);
1065
1066 $("who").textContent = `${accountLabel} · connecting…`;
1067
1068 socket = new GameSocket(defaultSocketUrl(), (message) =>
1069 {
1070 if (message.type === MessageType.session)
1071 {
1072 sessionAuthSubject = message.authSubject ?? null;
1073 const label = message.username ?? message.authSubject ?? "Unknown";
1074 $("who").textContent = `${label}${message.isAdmin ? " · admin" : " · not admin"}`;
1075 if (!message.isAdmin)
1076 {
1077 $("error").textContent = "Admin access required.";
1078 return;
1079 }
1080 $("error").textContent = "";
1081 const restartBtn = document.getElementById("editor-restart-now");
1082 if (restartBtn)
1083 {
1084 restartBtn.hidden = false;
1085 restartBtn.disabled = false;
1086 }
1087 socket.send({ type: MessageType.editorLoadSettings });
1088 socket.send({ type: MessageType.editorLoadGameAdmins });
1089 socket.send({ type: MessageType.editorConsoleSubscribe });
1090 requestDimensions();
1091 loadNeighborhood(0, 0);
1092 }
1093 else if (message.type === MessageType.editorSettings
1094 || message.type === MessageType.editorGameAdmins)
1095 { settingsModal.handleMessage(message); }
1096 else if (message.type === MessageType.editorConsoleSnapshot)
1097 { applyConsoleSnapshot(message.lines); }
1098 else if (message.type === MessageType.editorConsoleLine)
1099 { appendConsoleLine(message.line); }
1100 else if (message.type === MessageType.editorDimensions)
1101 {
1102 applyDimensionsList(message);
1103 }
1104 else if (message.type === MessageType.editorQuests)
1105 { questsModal?.handleMessage(message); }
1106 else if (message.type === MessageType.editorDialogues)
1107 {
1108 dialoguesModal?.handleMessage(message);
1109 tileConfigModal?.handleMessage(message);
1110 }
1111 else if (message.type === MessageType.editorChunk)
1112 {
1113 const msgDim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
1114 if (msgDim !== selectedDimensionId)
1115 { return; }
1116 if (message.settings)
1117 { view.setSettings(message.settings); }
1118 if (!inEditorView(message.chunkX, message.chunkY))
1119 { return; }
1120 if (message.chunkX === chunkX && message.chunkY === chunkY)
1121 { showSelectedChunk(message); }
1122 else
1123 {
1124 view.applySnapshot(snapshotFromPayload(message));
1125 syncSpawnersOverlay(message.chunkX, message.chunkY, message.data.spawners);
1126 }
1127 pruneView();
1128 }
1129 else if (message.type === MessageType.editorRevisionApplied)
1130 {
1131 applyInFlight = false;
1132 setRevisionState({
1133 activeRevisionId: message.activeRevisionId,
1134 pendingRevisionId: message.pendingRevisionId
1135 });
1136 const status = $("apply-status");
1137 status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`;
1138 status.className = "hint ok";
1139 requestDimensions();
1140 requestChunks(neighborhoodCoords(chunkX, chunkY));
1141 }
1142 else if (message.type === MessageType.forceLogout)
1143 {
1144 $("who").textContent = "Server restarting…";
1145 $("error").textContent = message.reason || "Server shutting down.";
1146 }
1147 else if (message.type === MessageType.error)
1148 {
1149 $("error").textContent = message.message;
1150 pendingCreatedDimensionId = null;
1151 navigateAfterSave = false;
1152 dimensionCombo?.setValue(selectedDimensionId);
1153 if (applyInFlight)
1154 {
1155 applyInFlight = false;
1156 $("apply-status").textContent = "";
1157 $("apply-status").className = "hint";
1158 updateRevisionUI();
1159 }
1160 }
1161 }, {
1162 onClose (event)
1163 {
1164 if (event.code === 1000)
1165 { return; }
1166 const reasons = {
1167 4401: "Sign in expired or missing. Use Sign out, then sign in again.",
1168 1011: "Server could not verify your account with auth.timfalken.com.",
1169 1006: "Connection dropped before the editor session started.",
1170 1001: "Server is restarting. Reload this page in a moment."
1171 };
1172 const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`;
1173 $("who").textContent = "Connection failed";
1174 $("error").textContent = detail;
1175 },
1176 onError ()
1177 {
1178 $("who").textContent = "Connection failed";
1179 $("error").textContent = "Could not open a live connection to the server.";
1180 }
1181 });
1182 settingsModal = initSettingsModal({
1183 socket,
1184 MessageType,
1185 getAuthSubject: () => sessionAuthSubject,
1186 onApplied (settings)
1187 {
1188 view.setSettings(settings);
1189 },
1190 onPreviewNight (hour)
1191 {
1192 view.nightPreview = hour;
1193 $("night").value = String(hour);
1194 $("night-label").textContent = Number(hour).toFixed(1);
1195 }
1196 });
1197 dimensionCombo = createDimensionCombobox({
1198 root: $("dimension-combo"),
1199 allowCreate: true,
1200 placeholder: "Search or create dimension…",
1201 onSelect (id)
1202 {
1203 selectDimension(id);
1204 },
1205 onCreate (rawId)
1206 {
1207 const id = normalizeDimensionId(rawId);
1208 $("error").textContent = "";
1209 pendingCreatedDimensionId = id;
1210 socket.send({
1211 type: MessageType.editorCreateDimension,
1212 dimensionId: id,
1213 displayName: rawId.trim()
1214 });
1215 }
1216 });
1217 dimensionCombo.setOptions([{
1218 id: OVERWORLD_ID,
1219 label: "Overworld"
1220 }]);
1221 dimensionCombo.setValue(OVERWORLD_ID);
1222 dimensionSettings = initDimensionSettings({
1223 socket,
1224 MessageType,
1225 GROUND_DEFINITIONS,
1226 OVERWORLD_ID,
1227 getSelectedDimensionId: () => selectedDimensionId,
1228 getDimensionRecord: (id) => dimensionsById.get(id) ?? null,
1229 isOverworld
1230 });
1231 questsModal = initQuestsModal({ socket, MessageType });
1232 dialoguesModal = initDialoguesModal({ socket, MessageType });
1233 initSidePanelTabs();
1234 game.startGame();
1235 useNearestNeighbour(scene, game.images);
1236 await socket.connect();
1237}
1238
1239$("tool").textContent = selectedToolLabel();
1240$("tool-erase").addEventListener("click", () =>
1241{
1242 selectTool({ kind: "erase" });
1243 $("tool").textContent = selectedToolLabel();
1244});
1245
1246$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
1247$("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1));
1248$("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY));
1249$("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
1250$("open").addEventListener("change", () =>
1251{
1252 if (isSelectedDimensionSoftDeleted())
1253 {
1254 $("open").checked = !!draft?.open;
1255 return;
1256 }
1257 if (draft)
1258 {
1259 draft.open = $("open").checked;
1260 view.setChunkOpen(chunkX, chunkY, draft.open);
1261 afterDraftMutation();
1262 }
1263});
1264$("save").addEventListener("click", () =>
1265{
1266 saveSelectedChunk();
1267});
1268$("unsaved-chunk-cancel")?.addEventListener("click", () =>
1269{
1270 pendingNavigate = null;
1271 navigateAfterSave = false;
1272 hideUnsavedModal();
1273});
1274$("unsaved-chunk-backdrop")?.addEventListener("click", () =>
1275{
1276 pendingNavigate = null;
1277 navigateAfterSave = false;
1278 hideUnsavedModal();
1279});
1280$("unsaved-chunk-discard")?.addEventListener("click", () =>
1281{
1282 const next = pendingNavigate;
1283 hideUnsavedModal();
1284 pendingNavigate = null;
1285 navigateAfterSave = false;
1286 if (!next)
1287 { return; }
1288 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1289 if (nextDim !== selectedDimensionId)
1290 {
1291 selectedDimensionId = nextDim;
1292 syncDimensionUi();
1293 clearNeighborhoodView();
1294 }
1295 doLoadNeighborhood(next.chunkX, next.chunkY);
1296});
1297$("unsaved-chunk-save")?.addEventListener("click", () =>
1298{
1299 hideUnsavedModal();
1300 if (!pendingNavigate)
1301 { return; }
1302 navigateAfterSave = true;
1303 if (!saveSelectedChunk())
1304 {
1305 navigateAfterSave = false;
1306 const next = pendingNavigate;
1307 pendingNavigate = null;
1308 if (next)
1309 {
1310 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1311 if (nextDim !== selectedDimensionId)
1312 {
1313 selectedDimensionId = nextDim;
1314 syncDimensionUi();
1315 clearNeighborhoodView();
1316 }
1317 doLoadNeighborhood(next.chunkX, next.chunkY);
1318 }
1319 }
1320});
1321$("apply").addEventListener("click", () =>
1322{
1323 if (!pendingRevisionId || applyInFlight)
1324 { return; }
1325 $("error").textContent = "";
1326 const status = $("apply-status");
1327 status.textContent = "Applying…";
1328 status.className = "hint";
1329 applyInFlight = true;
1330 updateRevisionUI();
1331 socket.send({ type: MessageType.editorApplyRevision });
1332});
1333document.getElementById("editor-restart-now")?.addEventListener("click", () =>
1334{
1335 if (!socket)
1336 { return; }
1337 const ok = window.confirm(
1338 "Restart the server now?\n\nAll players and editor sessions will disconnect. "
1339 + "systemd will start a fresh process and pull the latest code from git."
1340 );
1341 if (!ok)
1342 { return; }
1343 const restartBtn = document.getElementById("editor-restart-now");
1344 if (restartBtn)
1345 { restartBtn.disabled = true; }
1346 $("who").textContent = "Restarting server…";
1347 $("error").textContent = "";
1348 socket.send({ type: MessageType.editorRestartNow });
1349});
1350$("night").addEventListener("input", () =>
1351{
1352 view.nightPreview = Number($("night").value);
1353 $("night-label").textContent = view.nightPreview.toFixed(1);
1354});
1355$("season").addEventListener("change", () =>
1356{
1357 applySeasonPreview($("season").value);
1358});
1359
1360function syncSeasonControls (season)
1361{
1362 const next = season === SeasonId.spring
1363 || season === SeasonId.fall
1364 || season === SeasonId.winter
1365 || season === SeasonId.summer
1366 ? season
1367 : seasonIdAt();
1368 $("season").value = next;
1369 view?.setWorldSeason(next);
1370}
1371
1372function applySeasonPreview (season)
1373{
1374 syncSeasonControls(season);
1375}
1376
1377function cycleToolState (direction)
1378{
1379 if (tool.kind === "erase" || tool.kind === "spawner")
1380 { return; }
1381 const layer = tool.kind === "ground" ? "ground" : "block";
1382 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
1383 if (definitionUsesNeighborConnect(def))
1384 { return; }
1385 if (tool.kind === "block" && def?.id === BlockType.flower)
1386 { return; }
1387 const allStates = statesForType(catalog, layer, def.key);
1388 const seasonal = seasonalCycleStates(allStates);
1389 const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
1390 if (states.length < 2)
1391 { return; }
1392 tool.state = cycleState(states, tool.state, direction);
1393 $("tool").textContent = selectedToolLabel();
1394 const season = seasonIdFromVisualState(tool.state);
1395 if (season)
1396 { applySeasonPreview(season); }
1397 if (!draft || !hoverLocal)
1398 { return; }
1399 const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;
1400 if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId)
1401 { paintAt(hoverLocal.x, hoverLocal.y); }
1402 else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId)
1403 { paintAt(hoverLocal.x, hoverLocal.y); }
1404}
1405
1406document.addEventListener("wheel", (event) =>
1407{
1408 if (!scene?.canvas || anyModalOpen())
1409 { return; }
1410 const rect = scene.canvas.getBoundingClientRect();
1411 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
1412 { return; }
1413 event.preventDefault();
1414 if (event.shiftKey)
1415 {
1416 cycleToolState(event.deltaY < 0 ? 1 : -1);
1417 if (hoverLocal)
1418 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
1419 return;
1420 }
1421 zoomEditor(event.deltaY < 0 ? 1 : -1);
1422}, { passive: false });
1423
1424document.addEventListener("contextmenu", (event) =>
1425{
1426 if (!scene?.canvas || anyModalOpen() || !draft)
1427 { return; }
1428 const rect = scene.canvas.getBoundingClientRect();
1429 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
1430 { return; }
1431 event.preventDefault();
1432 const tile = view.screenToTile(event.clientX - rect.left, event.clientY - rect.top);
1433 const localX = tile.tileX - chunkX * CHUNK_SIZE;
1434 const localY = tile.tileY - chunkY * CHUNK_SIZE;
1435 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
1436 { return; }
1437 const spawner = spawnerAt(localX, localY);
1438 if (spawner)
1439 {
1440 tileConfigModal.openSpawner({
1441 localX,
1442 localY,
1443 tileX: tile.tileX,
1444 tileY: tile.tileY,
1445 config: { ...spawner.config }
1446 });
1447 return;
1448 }
1449 const index = localY * CHUNK_SIZE + localX;
1450 const block = draft.blocks[index];
1451 if (block?.typeId === BlockType.doorway)
1452 {
1453 tileConfigModal.openDoorway({
1454 localX,
1455 localY,
1456 tileX: tile.tileX,
1457 tileY: tile.tileY,
1458 state: block.state ?? "door",
1459 config: block.config ? { ...block.config } : {}
1460 });
1461 }
1462});
1463
1464main().catch((error) =>
1465{
1466 $("error").textContent = error.message;
1467 console.error(error);
1468});