BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

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