BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

main.js 40.1 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 applySpriteSheets(game.images, catalog);
911 scene = new Scene(250, 56, 64, 64);
912 game.loadScene(scene);
913 useNearestNeighbour(scene, game.images);
914 view = new WorldView(game, scene, catalog);
915 view.followPlayer = false;
916 view.setGraphicsPrefs(loadGraphicsSettings());
917 syncSeasonControls(view.worldSeason ?? seasonIdAt());
918 layoutScene();
919 selectTool(tool);
920 $("tool").textContent = selectedToolLabel();
921
922 paletteModal = initPaletteModal({
923 catalog,
924 imageUrlFor (name)
925 {
926 const sprite = game.images[name];
927 const html = sprite?.g_image;
928 if (html && typeof html.toDataURL === "function")
929 {
930 try
931 { return html.toDataURL("image/png"); }
932 catch (_)
933 { /* fall through */ }
934 }
935 return imageUrlByName.get(name) ?? null;
936 },
937 onSelect (next)
938 {
939 selectTool(next);
940 $("tool").textContent = selectedToolLabel();
941 }
942 });
943
944 tileConfigModal = initTileConfigModal({
945 socket: {
946 send (payload)
947 {
948 socket?.send(payload);
949 }
950 },
951 MessageType,
952 getDialogues: () => dialoguesModal?.getDialogues?.() ?? [],
953 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
954 id: dim.dimensionId,
955 label: dim.displayName || dim.dimensionId,
956 disabled: !!dim.deletedAt,
957 hint: dim.deletedAt ? "soft-deleted" : undefined
958 })),
959 onSave (ctx, config)
960 {
961 if (!draft)
962 { return; }
963 if (ctx.kind === "doorway")
964 {
965 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
966 draft.blocks[index] = {
967 typeId: BlockType.doorway,
968 state: config.state || "door",
969 config: {
970 targetDimensionId: normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID),
971 tileX: Number(config.tileX) || 0,
972 tileY: Number(config.tileY) || 0
973 }
974 };
975 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
976 ground: draft.grounds[index],
977 block: draft.blocks[index],
978 light: draft.light[index]
979 });
980 afterDraftMutation();
981 return;
982 }
983 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
984 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
985 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
986 afterDraftMutation();
987 },
988 onRemove (ctx)
989 {
990 if (!draft)
991 { return; }
992 if (ctx.kind === "doorway")
993 {
994 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
995 draft.blocks[index] = null;
996 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
997 ground: draft.grounds[index],
998 block: draft.blocks[index],
999 light: draft.light[index]
1000 });
1001 afterDraftMutation();
1002 return;
1003 }
1004 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1005 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1006 afterDraftMutation();
1007 }
1008 });
1009
1010 const ticker = new GameObject(0, 0, null, 10);
1011 ticker.update = (dt) =>
1012 {
1013 hoverLocal = null;
1014 const canvas = scene.canvas;
1015 const rect = canvas.getBoundingClientRect();
1016 const mouseX = GameInput.mousePosition.x - rect.left;
1017 const mouseY = GameInput.mousePosition.y - rect.top;
1018 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
1019 if (overCanvas && draft && !anyModalOpen())
1020 {
1021 const tile = view.screenToTile(mouseX, mouseY);
1022 const localX = tile.tileX - chunkX * CHUNK_SIZE;
1023 const localY = tile.tileY - chunkY * CHUNK_SIZE;
1024 const hoverChunkX = Math.floor(tile.tileX / CHUNK_SIZE);
1025 const hoverChunkY = Math.floor(tile.tileY / CHUNK_SIZE);
1026 updateHoverStatus({
1027 tileX: tile.tileX,
1028 tileY: tile.tileY,
1029 x: ((tile.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1030 y: ((tile.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1031 chunkX: hoverChunkX,
1032 chunkY: hoverChunkY
1033 });
1034 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
1035 {
1036 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
1037 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
1038 updateTooltip(hoverLocal);
1039 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
1040 { paintAt(localX, localY); }
1041 }
1042 else
1043 {
1044 hoverLocal = null;
1045 view.clearTilePreview();
1046 updateTooltip(null, { keepStatus: true });
1047 }
1048 }
1049 else
1050 {
1051 view.clearTilePreview();
1052 updateTooltip(null);
1053 }
1054 view.update(dt);
1055 frameNeighborhood();
1056 };
1057 scene.addObject(ticker);
1058 window.addEventListener("resize", layoutScene);
1059
1060 $("who").textContent = `${accountLabel} · connecting…`;
1061
1062 socket = new GameSocket(defaultSocketUrl(), (message) =>
1063 {
1064 if (message.type === MessageType.session)
1065 {
1066 sessionAuthSubject = message.authSubject ?? null;
1067 const label = message.username ?? message.authSubject ?? "Unknown";
1068 $("who").textContent = `${label}${message.isAdmin ? " · admin" : " · not admin"}`;
1069 if (!message.isAdmin)
1070 {
1071 $("error").textContent = "Admin access required.";
1072 return;
1073 }
1074 $("error").textContent = "";
1075 socket.send({ type: MessageType.editorLoadSettings });
1076 socket.send({ type: MessageType.editorLoadGameAdmins });
1077 socket.send({ type: MessageType.editorConsoleSubscribe });
1078 requestDimensions();
1079 loadNeighborhood(0, 0);
1080 }
1081 else if (message.type === MessageType.editorSettings
1082 || message.type === MessageType.editorGameAdmins)
1083 { settingsModal.handleMessage(message); }
1084 else if (message.type === MessageType.editorConsoleSnapshot)
1085 { applyConsoleSnapshot(message.lines); }
1086 else if (message.type === MessageType.editorConsoleLine)
1087 { appendConsoleLine(message.line); }
1088 else if (message.type === MessageType.editorDimensions)
1089 {
1090 applyDimensionsList(message);
1091 }
1092 else if (message.type === MessageType.editorQuests)
1093 { questsModal?.handleMessage(message); }
1094 else if (message.type === MessageType.editorDialogues)
1095 {
1096 dialoguesModal?.handleMessage(message);
1097 tileConfigModal?.handleMessage(message);
1098 }
1099 else if (message.type === MessageType.editorChunk)
1100 {
1101 const msgDim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
1102 if (msgDim !== selectedDimensionId)
1103 { return; }
1104 if (message.settings)
1105 { view.setSettings(message.settings); }
1106 if (!inEditorView(message.chunkX, message.chunkY))
1107 { return; }
1108 if (message.chunkX === chunkX && message.chunkY === chunkY)
1109 { showSelectedChunk(message); }
1110 else
1111 {
1112 view.applySnapshot(snapshotFromPayload(message));
1113 syncSpawnersOverlay(message.chunkX, message.chunkY, message.data.spawners);
1114 }
1115 pruneView();
1116 }
1117 else if (message.type === MessageType.editorRevisionApplied)
1118 {
1119 applyInFlight = false;
1120 setRevisionState({
1121 activeRevisionId: message.activeRevisionId,
1122 pendingRevisionId: message.pendingRevisionId
1123 });
1124 const status = $("apply-status");
1125 status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`;
1126 status.className = "hint ok";
1127 requestDimensions();
1128 requestChunks(neighborhoodCoords(chunkX, chunkY));
1129 }
1130 else if (message.type === MessageType.error)
1131 {
1132 $("error").textContent = message.message;
1133 pendingCreatedDimensionId = null;
1134 navigateAfterSave = false;
1135 dimensionCombo?.setValue(selectedDimensionId);
1136 if (applyInFlight)
1137 {
1138 applyInFlight = false;
1139 $("apply-status").textContent = "";
1140 $("apply-status").className = "hint";
1141 updateRevisionUI();
1142 }
1143 }
1144 }, {
1145 onClose (event)
1146 {
1147 if (event.code === 1000)
1148 { return; }
1149 const reasons = {
1150 4401: "Sign in expired or missing. Use Sign out, then sign in again.",
1151 1011: "Server could not verify your account with auth.timfalken.com.",
1152 1006: "Connection dropped before the editor session started."
1153 };
1154 const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`;
1155 $("who").textContent = "Connection failed";
1156 $("error").textContent = detail;
1157 },
1158 onError ()
1159 {
1160 $("who").textContent = "Connection failed";
1161 $("error").textContent = "Could not open a live connection to the server.";
1162 }
1163 });
1164 settingsModal = initSettingsModal({
1165 socket,
1166 MessageType,
1167 getAuthSubject: () => sessionAuthSubject,
1168 onApplied (settings)
1169 {
1170 view.setSettings(settings);
1171 },
1172 onPreviewNight (hour)
1173 {
1174 view.nightPreview = hour;
1175 $("night").value = String(hour);
1176 $("night-label").textContent = Number(hour).toFixed(1);
1177 }
1178 });
1179 dimensionCombo = createDimensionCombobox({
1180 root: $("dimension-combo"),
1181 allowCreate: true,
1182 placeholder: "Search or create dimension…",
1183 onSelect (id)
1184 {
1185 selectDimension(id);
1186 },
1187 onCreate (rawId)
1188 {
1189 const id = normalizeDimensionId(rawId);
1190 $("error").textContent = "";
1191 pendingCreatedDimensionId = id;
1192 socket.send({
1193 type: MessageType.editorCreateDimension,
1194 dimensionId: id,
1195 displayName: rawId.trim()
1196 });
1197 }
1198 });
1199 dimensionCombo.setOptions([{
1200 id: OVERWORLD_ID,
1201 label: "Overworld"
1202 }]);
1203 dimensionCombo.setValue(OVERWORLD_ID);
1204 dimensionSettings = initDimensionSettings({
1205 socket,
1206 MessageType,
1207 GROUND_DEFINITIONS,
1208 OVERWORLD_ID,
1209 getSelectedDimensionId: () => selectedDimensionId,
1210 getDimensionRecord: (id) => dimensionsById.get(id) ?? null,
1211 isOverworld
1212 });
1213 questsModal = initQuestsModal({ socket, MessageType });
1214 dialoguesModal = initDialoguesModal({ socket, MessageType });
1215 initSidePanelTabs();
1216 game.startGame();
1217 await socket.connect();
1218}
1219
1220$("tool").textContent = selectedToolLabel();
1221$("tool-erase").addEventListener("click", () =>
1222{
1223 selectTool({ kind: "erase" });
1224 $("tool").textContent = selectedToolLabel();
1225});
1226
1227$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
1228$("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1));
1229$("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY));
1230$("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
1231$("open").addEventListener("change", () =>
1232{
1233 if (isSelectedDimensionSoftDeleted())
1234 {
1235 $("open").checked = !!draft?.open;
1236 return;
1237 }
1238 if (draft)
1239 {
1240 draft.open = $("open").checked;
1241 view.setChunkOpen(chunkX, chunkY, draft.open);
1242 afterDraftMutation();
1243 }
1244});
1245$("save").addEventListener("click", () =>
1246{
1247 saveSelectedChunk();
1248});
1249$("unsaved-chunk-cancel")?.addEventListener("click", () =>
1250{
1251 pendingNavigate = null;
1252 navigateAfterSave = false;
1253 hideUnsavedModal();
1254});
1255$("unsaved-chunk-backdrop")?.addEventListener("click", () =>
1256{
1257 pendingNavigate = null;
1258 navigateAfterSave = false;
1259 hideUnsavedModal();
1260});
1261$("unsaved-chunk-discard")?.addEventListener("click", () =>
1262{
1263 const next = pendingNavigate;
1264 hideUnsavedModal();
1265 pendingNavigate = null;
1266 navigateAfterSave = false;
1267 if (!next)
1268 { return; }
1269 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1270 if (nextDim !== selectedDimensionId)
1271 {
1272 selectedDimensionId = nextDim;
1273 syncDimensionUi();
1274 clearNeighborhoodView();
1275 }
1276 doLoadNeighborhood(next.chunkX, next.chunkY);
1277});
1278$("unsaved-chunk-save")?.addEventListener("click", () =>
1279{
1280 hideUnsavedModal();
1281 if (!pendingNavigate)
1282 { return; }
1283 navigateAfterSave = true;
1284 if (!saveSelectedChunk())
1285 {
1286 navigateAfterSave = false;
1287 const next = pendingNavigate;
1288 pendingNavigate = null;
1289 if (next)
1290 {
1291 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1292 if (nextDim !== selectedDimensionId)
1293 {
1294 selectedDimensionId = nextDim;
1295 syncDimensionUi();
1296 clearNeighborhoodView();
1297 }
1298 doLoadNeighborhood(next.chunkX, next.chunkY);
1299 }
1300 }
1301});
1302$("apply").addEventListener("click", () =>
1303{
1304 if (!pendingRevisionId || applyInFlight)
1305 { return; }
1306 $("error").textContent = "";
1307 const status = $("apply-status");
1308 status.textContent = "Applying…";
1309 status.className = "hint";
1310 applyInFlight = true;
1311 updateRevisionUI();
1312 socket.send({ type: MessageType.editorApplyRevision });
1313});
1314$("night").addEventListener("input", () =>
1315{
1316 view.nightPreview = Number($("night").value);
1317 $("night-label").textContent = view.nightPreview.toFixed(1);
1318});
1319$("season").addEventListener("change", () =>
1320{
1321 applySeasonPreview($("season").value);
1322});
1323
1324function syncSeasonControls (season)
1325{
1326 const next = season === SeasonId.spring
1327 || season === SeasonId.fall
1328 || season === SeasonId.winter
1329 || season === SeasonId.summer
1330 ? season
1331 : seasonIdAt();
1332 $("season").value = next;
1333 view?.setWorldSeason(next);
1334}
1335
1336function applySeasonPreview (season)
1337{
1338 syncSeasonControls(season);
1339}
1340
1341function cycleToolState (direction)
1342{
1343 if (tool.kind === "erase" || tool.kind === "spawner")
1344 { return; }
1345 const layer = tool.kind === "ground" ? "ground" : "block";
1346 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
1347 if (definitionUsesNeighborConnect(def))
1348 { return; }
1349 if (tool.kind === "block" && def?.id === BlockType.flower)
1350 { return; }
1351 const allStates = statesForType(catalog, layer, def.key);
1352 const seasonal = seasonalCycleStates(allStates);
1353 const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
1354 if (states.length < 2)
1355 { return; }
1356 tool.state = cycleState(states, tool.state, direction);
1357 $("tool").textContent = selectedToolLabel();
1358 const season = seasonIdFromVisualState(tool.state);
1359 if (season)
1360 { applySeasonPreview(season); }
1361 if (!draft || !hoverLocal)
1362 { return; }
1363 const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;
1364 if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId)
1365 { paintAt(hoverLocal.x, hoverLocal.y); }
1366 else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId)
1367 { paintAt(hoverLocal.x, hoverLocal.y); }
1368}
1369
1370document.addEventListener("wheel", (event) =>
1371{
1372 if (!scene?.canvas || anyModalOpen())
1373 { return; }
1374 const rect = scene.canvas.getBoundingClientRect();
1375 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
1376 { return; }
1377 event.preventDefault();
1378 if (event.shiftKey)
1379 {
1380 cycleToolState(event.deltaY < 0 ? 1 : -1);
1381 if (hoverLocal)
1382 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
1383 return;
1384 }
1385 zoomEditor(event.deltaY < 0 ? 1 : -1);
1386}, { passive: false });
1387
1388document.addEventListener("contextmenu", (event) =>
1389{
1390 if (!scene?.canvas || anyModalOpen() || !draft)
1391 { return; }
1392 const rect = scene.canvas.getBoundingClientRect();
1393 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
1394 { return; }
1395 event.preventDefault();
1396 const tile = view.screenToTile(event.clientX - rect.left, event.clientY - rect.top);
1397 const localX = tile.tileX - chunkX * CHUNK_SIZE;
1398 const localY = tile.tileY - chunkY * CHUNK_SIZE;
1399 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
1400 { return; }
1401 const spawner = spawnerAt(localX, localY);
1402 if (spawner)
1403 {
1404 tileConfigModal.openSpawner({
1405 localX,
1406 localY,
1407 tileX: tile.tileX,
1408 tileY: tile.tileY,
1409 config: { ...spawner.config }
1410 });
1411 return;
1412 }
1413 const index = localY * CHUNK_SIZE + localX;
1414 const block = draft.blocks[index];
1415 if (block?.typeId === BlockType.doorway)
1416 {
1417 tileConfigModal.openDoorway({
1418 localX,
1419 localY,
1420 tileX: tile.tileX,
1421 tileY: tile.tileY,
1422 state: block.state ?? "door",
1423 config: block.config ? { ...block.config } : {}
1424 });
1425 }
1426});
1427
1428main().catch((error) =>
1429{
1430 $("error").textContent = error.message;
1431 console.error(error);
1432});