BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

main.js 39.9 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 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
738 useNearestNeighbour(scene, game.images);
739 frameNeighborhood();
740}
741
742function requestChunks (coords)
743{
744 if (!socket?.socket || socket.socket.readyState !== WebSocket.OPEN)
745 { return; }
746 for (const coord of coords)
747 {
748 try
749 {
750 socket.send({
751 type: MessageType.editorLoadChunk,
752 chunkX: coord.chunkX,
753 chunkY: coord.chunkY,
754 dimensionId: selectedDimensionId
755 });
756 }
757 catch (_)
758 { break; }
759 }
760}
761
762function doLoadNeighborhood (x, y)
763{
764 chunkX = x;
765 chunkY = y;
766 $("coords").textContent = `${chunkX}, ${chunkY}`;
767 requestChunks(neighborhoodCoords(x, y));
768}
769
770function loadNeighborhood (x, y)
771{
772 if ((x !== chunkX || y !== chunkY) && isDraftDirty())
773 {
774 showUnsavedModal({ chunkX: x, chunkY: y, dimensionId: selectedDimensionId });
775 return;
776 }
777 doLoadNeighborhood(x, y);
778}
779
780function requestNeighbors ()
781{
782 requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
783}
784
785function anyModalOpen ()
786{
787 return settingsModal?.isOpen()
788 || paletteModal?.isOpen()
789 || tileConfigModal?.isOpen()
790 || questsModal?.isOpen()
791 || dialoguesModal?.isOpen()
792 || !$("unsaved-chunk-modal")?.hidden;
793}
794
795function updateHoverStatus (local)
796{
797 const el = $("hover-status-text");
798 if (!el)
799 { return; }
800 if (!local)
801 {
802 el.textContent = "Hover a tile for coordinates";
803 return;
804 }
805 const hoverChunkX = local.chunkX ?? Math.floor(local.tileX / CHUNK_SIZE);
806 const hoverChunkY = local.chunkY ?? Math.floor(local.tileY / CHUNK_SIZE);
807 el.textContent = `Tile (${local.tileX}, ${local.tileY}) · Chunk (${hoverChunkX}, ${hoverChunkY})`;
808}
809
810function updateTooltip (local, options = {})
811{
812 if (!options.keepStatus)
813 { updateHoverStatus(local); }
814 const tip = $("tile-tooltip");
815 if (!tip || !local || !draft)
816 {
817 if (tip)
818 { tip.hidden = true; }
819 view?.clearSpawnRangeHighlight();
820 return;
821 }
822 const block = normalizeBlock(draft.blocks[local.y * CHUNK_SIZE + local.x]);
823 const spawner = spawnerAt(local.x, local.y);
824 const lines = [];
825 if (block)
826 {
827 const def = BLOCK_DEFINITIONS[block.typeId];
828 lines.push(def?.displayName ?? `Block ${block.typeId}`);
829 if (block.config && Object.keys(block.config).length)
830 {
831 for (const [key, value] of Object.entries(block.config))
832 { lines.push(`${key}: ${value}`); }
833 }
834 }
835 if (spawner)
836 {
837 const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId);
838 const mob = mobDefinition(config.mobTypeId);
839 lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`);
840 lines.push(`maxAlive: ${config.maxAlive}`);
841 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
842 lines.push(`wanderRange: ${config.maxWanderRangeTiles}`);
843 lines.push(`id: ${config.spawnerId}`);
844 view.setSpawnRangeHighlight(
845 local.tileX,
846 local.tileY,
847 config.spawnRangeTiles,
848 config.maxWanderRangeTiles
849 );
850 }
851 else
852 { view.clearSpawnRangeHighlight(); }
853 if (!lines.length)
854 {
855 tip.hidden = true;
856 return;
857 }
858 tip.hidden = false;
859 tip.textContent = lines.join("\n");
860 const canvas = scene.canvas;
861 const rect = canvas.getBoundingClientRect();
862 const size = view.tileSize();
863 const screenX = local.tileX * size + scene.cameraPosition.x + rect.left + size;
864 const screenY = local.tileY * size + scene.cameraPosition.y + rect.top;
865 tip.style.left = `${screenX}px`;
866 tip.style.top = `${screenY}px`;
867}
868
869async function main ()
870{
871 const authStatus = await fetchAuthStatus();
872 const signIn = document.getElementById("auth-sign-in");
873 const signOut = document.getElementById("auth-sign-out");
874 if (signIn)
875 {
876 signIn.hidden = !!authStatus?.authenticated;
877 signIn.href = loginUrl("/editor");
878 }
879 if (signOut)
880 {
881 signOut.hidden = !authStatus?.authenticated;
882 signOut.href = logoutUrl("/editor");
883 }
884 if (!authStatus.authenticated)
885 {
886 $("who").textContent = "Sign in required";
887 $("error").textContent = "Sign in with your Tim Falken account to use the world editor.";
888 return;
889 }
890
891 const accountLabel = authStatus.username ?? authStatus.email ?? authStatus.authSubject ?? "Signed in";
892 $("who").textContent = `${accountLabel} · loading sprites…`;
893
894 catalog = await loadSpriteCatalog();
895 imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));
896 await preloadCatalogImages(game, catalog);
897 applySpriteSheets(game.images, catalog);
898 scene = new Scene(250, 56, 64, 64);
899 game.loadScene(scene);
900 useNearestNeighbour(scene, game.images);
901 view = new WorldView(game, scene, catalog);
902 view.followPlayer = false;
903 view.setGraphicsPrefs(loadGraphicsSettings());
904 syncSeasonControls(view.worldSeason ?? seasonIdAt());
905 layoutScene();
906 selectTool(tool);
907 $("tool").textContent = selectedToolLabel();
908
909 paletteModal = initPaletteModal({
910 catalog,
911 imageUrlFor (name)
912 {
913 const sprite = game.images[name];
914 const html = sprite?.g_image;
915 if (html && typeof html.toDataURL === "function")
916 {
917 try
918 { return html.toDataURL("image/png"); }
919 catch (_)
920 { /* fall through */ }
921 }
922 return imageUrlByName.get(name) ?? null;
923 },
924 onSelect (next)
925 {
926 selectTool(next);
927 $("tool").textContent = selectedToolLabel();
928 }
929 });
930
931 tileConfigModal = initTileConfigModal({
932 socket: {
933 send (payload)
934 {
935 socket?.send(payload);
936 }
937 },
938 MessageType,
939 getDialogues: () => dialoguesModal?.getDialogues?.() ?? [],
940 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
941 id: dim.dimensionId,
942 label: dim.displayName || dim.dimensionId,
943 disabled: !!dim.deletedAt,
944 hint: dim.deletedAt ? "soft-deleted" : undefined
945 })),
946 onSave (ctx, config)
947 {
948 if (!draft)
949 { return; }
950 if (ctx.kind === "doorway")
951 {
952 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
953 draft.blocks[index] = {
954 typeId: BlockType.doorway,
955 state: config.state || "door",
956 config: {
957 targetDimensionId: normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID),
958 tileX: Number(config.tileX) || 0,
959 tileY: Number(config.tileY) || 0
960 }
961 };
962 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
963 ground: draft.grounds[index],
964 block: draft.blocks[index],
965 light: draft.light[index]
966 });
967 afterDraftMutation();
968 return;
969 }
970 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
971 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
972 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
973 afterDraftMutation();
974 },
975 onRemove (ctx)
976 {
977 if (!draft)
978 { return; }
979 if (ctx.kind === "doorway")
980 {
981 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
982 draft.blocks[index] = null;
983 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
984 ground: draft.grounds[index],
985 block: draft.blocks[index],
986 light: draft.light[index]
987 });
988 afterDraftMutation();
989 return;
990 }
991 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
992 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
993 afterDraftMutation();
994 }
995 });
996
997 const ticker = new GameObject(0, 0, null, 10);
998 ticker.update = (dt) =>
999 {
1000 hoverLocal = null;
1001 const canvas = scene.canvas;
1002 const rect = canvas.getBoundingClientRect();
1003 const mouseX = GameInput.mousePosition.x - rect.left;
1004 const mouseY = GameInput.mousePosition.y - rect.top;
1005 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
1006 if (overCanvas && draft && !anyModalOpen())
1007 {
1008 const tile = view.screenToTile(mouseX, mouseY);
1009 const localX = tile.tileX - chunkX * CHUNK_SIZE;
1010 const localY = tile.tileY - chunkY * CHUNK_SIZE;
1011 const hoverChunkX = Math.floor(tile.tileX / CHUNK_SIZE);
1012 const hoverChunkY = Math.floor(tile.tileY / CHUNK_SIZE);
1013 updateHoverStatus({
1014 tileX: tile.tileX,
1015 tileY: tile.tileY,
1016 x: ((tile.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1017 y: ((tile.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1018 chunkX: hoverChunkX,
1019 chunkY: hoverChunkY
1020 });
1021 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
1022 {
1023 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
1024 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
1025 updateTooltip(hoverLocal);
1026 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
1027 { paintAt(localX, localY); }
1028 }
1029 else
1030 {
1031 hoverLocal = null;
1032 view.clearTilePreview();
1033 updateTooltip(null, { keepStatus: true });
1034 }
1035 }
1036 else
1037 {
1038 view.clearTilePreview();
1039 updateTooltip(null);
1040 }
1041 view.update(dt);
1042 frameNeighborhood();
1043 };
1044 scene.addObject(ticker);
1045 window.addEventListener("resize", layoutScene);
1046
1047 $("who").textContent = `${accountLabel} · connecting…`;
1048
1049 socket = new GameSocket(defaultSocketUrl(), (message) =>
1050 {
1051 if (message.type === MessageType.session)
1052 {
1053 sessionAuthSubject = message.authSubject ?? null;
1054 const label = message.username ?? message.authSubject ?? "Unknown";
1055 $("who").textContent = `${label}${message.isAdmin ? " · admin" : " · not admin"}`;
1056 if (!message.isAdmin)
1057 {
1058 $("error").textContent = "Admin access required.";
1059 return;
1060 }
1061 $("error").textContent = "";
1062 socket.send({ type: MessageType.editorLoadSettings });
1063 socket.send({ type: MessageType.editorLoadGameAdmins });
1064 socket.send({ type: MessageType.editorConsoleSubscribe });
1065 requestDimensions();
1066 loadNeighborhood(0, 0);
1067 }
1068 else if (message.type === MessageType.editorSettings
1069 || message.type === MessageType.editorGameAdmins)
1070 { settingsModal.handleMessage(message); }
1071 else if (message.type === MessageType.editorConsoleSnapshot)
1072 { applyConsoleSnapshot(message.lines); }
1073 else if (message.type === MessageType.editorConsoleLine)
1074 { appendConsoleLine(message.line); }
1075 else if (message.type === MessageType.editorDimensions)
1076 {
1077 applyDimensionsList(message);
1078 }
1079 else if (message.type === MessageType.editorQuests)
1080 { questsModal?.handleMessage(message); }
1081 else if (message.type === MessageType.editorDialogues)
1082 {
1083 dialoguesModal?.handleMessage(message);
1084 tileConfigModal?.handleMessage(message);
1085 }
1086 else if (message.type === MessageType.editorChunk)
1087 {
1088 const msgDim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
1089 if (msgDim !== selectedDimensionId)
1090 { return; }
1091 if (message.settings)
1092 { view.setSettings(message.settings); }
1093 if (!inEditorView(message.chunkX, message.chunkY))
1094 { return; }
1095 if (message.chunkX === chunkX && message.chunkY === chunkY)
1096 { showSelectedChunk(message); }
1097 else
1098 {
1099 view.applySnapshot(snapshotFromPayload(message));
1100 syncSpawnersOverlay(message.chunkX, message.chunkY, message.data.spawners);
1101 }
1102 pruneView();
1103 }
1104 else if (message.type === MessageType.editorRevisionApplied)
1105 {
1106 applyInFlight = false;
1107 setRevisionState({
1108 activeRevisionId: message.activeRevisionId,
1109 pendingRevisionId: message.pendingRevisionId
1110 });
1111 const status = $("apply-status");
1112 status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`;
1113 status.className = "hint ok";
1114 requestDimensions();
1115 requestChunks(neighborhoodCoords(chunkX, chunkY));
1116 }
1117 else if (message.type === MessageType.error)
1118 {
1119 $("error").textContent = message.message;
1120 pendingCreatedDimensionId = null;
1121 navigateAfterSave = false;
1122 dimensionCombo?.setValue(selectedDimensionId);
1123 if (applyInFlight)
1124 {
1125 applyInFlight = false;
1126 $("apply-status").textContent = "";
1127 $("apply-status").className = "hint";
1128 updateRevisionUI();
1129 }
1130 }
1131 }, {
1132 onClose (event)
1133 {
1134 if (event.code === 1000)
1135 { return; }
1136 const reasons = {
1137 4401: "Sign in expired or missing. Use Sign out, then sign in again.",
1138 1011: "Server could not verify your account with auth.timfalken.com.",
1139 1006: "Connection dropped before the editor session started."
1140 };
1141 const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`;
1142 $("who").textContent = "Connection failed";
1143 $("error").textContent = detail;
1144 },
1145 onError ()
1146 {
1147 $("who").textContent = "Connection failed";
1148 $("error").textContent = "Could not open a live connection to the server.";
1149 }
1150 });
1151 settingsModal = initSettingsModal({
1152 socket,
1153 MessageType,
1154 getAuthSubject: () => sessionAuthSubject,
1155 onApplied (settings)
1156 {
1157 view.setSettings(settings);
1158 },
1159 onPreviewNight (hour)
1160 {
1161 view.nightPreview = hour;
1162 $("night").value = String(hour);
1163 $("night-label").textContent = Number(hour).toFixed(1);
1164 }
1165 });
1166 dimensionCombo = createDimensionCombobox({
1167 root: $("dimension-combo"),
1168 allowCreate: true,
1169 placeholder: "Search or create dimension…",
1170 onSelect (id)
1171 {
1172 selectDimension(id);
1173 },
1174 onCreate (rawId)
1175 {
1176 const id = normalizeDimensionId(rawId);
1177 $("error").textContent = "";
1178 pendingCreatedDimensionId = id;
1179 socket.send({
1180 type: MessageType.editorCreateDimension,
1181 dimensionId: id,
1182 displayName: rawId.trim()
1183 });
1184 }
1185 });
1186 dimensionCombo.setOptions([{
1187 id: OVERWORLD_ID,
1188 label: "Overworld"
1189 }]);
1190 dimensionCombo.setValue(OVERWORLD_ID);
1191 dimensionSettings = initDimensionSettings({
1192 socket,
1193 MessageType,
1194 GROUND_DEFINITIONS,
1195 OVERWORLD_ID,
1196 getSelectedDimensionId: () => selectedDimensionId,
1197 getDimensionRecord: (id) => dimensionsById.get(id) ?? null,
1198 isOverworld
1199 });
1200 questsModal = initQuestsModal({ socket, MessageType });
1201 dialoguesModal = initDialoguesModal({ socket, MessageType });
1202 initSidePanelTabs();
1203 game.startGame();
1204 await socket.connect();
1205}
1206
1207$("tool").textContent = selectedToolLabel();
1208$("tool-erase").addEventListener("click", () =>
1209{
1210 selectTool({ kind: "erase" });
1211 $("tool").textContent = selectedToolLabel();
1212});
1213
1214$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
1215$("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1));
1216$("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY));
1217$("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
1218$("open").addEventListener("change", () =>
1219{
1220 if (isSelectedDimensionSoftDeleted())
1221 {
1222 $("open").checked = !!draft?.open;
1223 return;
1224 }
1225 if (draft)
1226 {
1227 draft.open = $("open").checked;
1228 view.setChunkOpen(chunkX, chunkY, draft.open);
1229 afterDraftMutation();
1230 }
1231});
1232$("save").addEventListener("click", () =>
1233{
1234 saveSelectedChunk();
1235});
1236$("unsaved-chunk-cancel")?.addEventListener("click", () =>
1237{
1238 pendingNavigate = null;
1239 navigateAfterSave = false;
1240 hideUnsavedModal();
1241});
1242$("unsaved-chunk-backdrop")?.addEventListener("click", () =>
1243{
1244 pendingNavigate = null;
1245 navigateAfterSave = false;
1246 hideUnsavedModal();
1247});
1248$("unsaved-chunk-discard")?.addEventListener("click", () =>
1249{
1250 const next = pendingNavigate;
1251 hideUnsavedModal();
1252 pendingNavigate = null;
1253 navigateAfterSave = false;
1254 if (!next)
1255 { return; }
1256 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1257 if (nextDim !== selectedDimensionId)
1258 {
1259 selectedDimensionId = nextDim;
1260 syncDimensionUi();
1261 clearNeighborhoodView();
1262 }
1263 doLoadNeighborhood(next.chunkX, next.chunkY);
1264});
1265$("unsaved-chunk-save")?.addEventListener("click", () =>
1266{
1267 hideUnsavedModal();
1268 if (!pendingNavigate)
1269 { return; }
1270 navigateAfterSave = true;
1271 if (!saveSelectedChunk())
1272 {
1273 navigateAfterSave = false;
1274 const next = pendingNavigate;
1275 pendingNavigate = null;
1276 if (next)
1277 {
1278 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1279 if (nextDim !== selectedDimensionId)
1280 {
1281 selectedDimensionId = nextDim;
1282 syncDimensionUi();
1283 clearNeighborhoodView();
1284 }
1285 doLoadNeighborhood(next.chunkX, next.chunkY);
1286 }
1287 }
1288});
1289$("apply").addEventListener("click", () =>
1290{
1291 if (!pendingRevisionId || applyInFlight)
1292 { return; }
1293 $("error").textContent = "";
1294 const status = $("apply-status");
1295 status.textContent = "Applying…";
1296 status.className = "hint";
1297 applyInFlight = true;
1298 updateRevisionUI();
1299 socket.send({ type: MessageType.editorApplyRevision });
1300});
1301$("night").addEventListener("input", () =>
1302{
1303 view.nightPreview = Number($("night").value);
1304 $("night-label").textContent = view.nightPreview.toFixed(1);
1305});
1306$("season").addEventListener("change", () =>
1307{
1308 applySeasonPreview($("season").value);
1309});
1310
1311function syncSeasonControls (season)
1312{
1313 const next = season === SeasonId.spring
1314 || season === SeasonId.fall
1315 || season === SeasonId.winter
1316 || season === SeasonId.summer
1317 ? season
1318 : seasonIdAt();
1319 $("season").value = next;
1320 view?.setWorldSeason(next);
1321}
1322
1323function applySeasonPreview (season)
1324{
1325 syncSeasonControls(season);
1326}
1327
1328function cycleToolState (direction)
1329{
1330 if (tool.kind === "erase" || tool.kind === "spawner")
1331 { return; }
1332 const layer = tool.kind === "ground" ? "ground" : "block";
1333 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
1334 if (definitionUsesNeighborConnect(def))
1335 { return; }
1336 if (tool.kind === "block" && def?.id === BlockType.flower)
1337 { return; }
1338 const allStates = statesForType(catalog, layer, def.key);
1339 const seasonal = seasonalCycleStates(allStates);
1340 const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
1341 if (states.length < 2)
1342 { return; }
1343 tool.state = cycleState(states, tool.state, direction);
1344 $("tool").textContent = selectedToolLabel();
1345 const season = seasonIdFromVisualState(tool.state);
1346 if (season)
1347 { applySeasonPreview(season); }
1348 if (!draft || !hoverLocal)
1349 { return; }
1350 const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;
1351 if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId)
1352 { paintAt(hoverLocal.x, hoverLocal.y); }
1353 else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId)
1354 { paintAt(hoverLocal.x, hoverLocal.y); }
1355}
1356
1357document.addEventListener("wheel", (event) =>
1358{
1359 if (!scene?.canvas || anyModalOpen())
1360 { return; }
1361 const rect = scene.canvas.getBoundingClientRect();
1362 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
1363 { return; }
1364 event.preventDefault();
1365 if (event.shiftKey)
1366 {
1367 cycleToolState(event.deltaY < 0 ? 1 : -1);
1368 if (hoverLocal)
1369 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
1370 return;
1371 }
1372 zoomEditor(event.deltaY < 0 ? 1 : -1);
1373}, { passive: false });
1374
1375document.addEventListener("contextmenu", (event) =>
1376{
1377 if (!scene?.canvas || anyModalOpen() || !draft)
1378 { return; }
1379 const rect = scene.canvas.getBoundingClientRect();
1380 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
1381 { return; }
1382 event.preventDefault();
1383 const tile = view.screenToTile(event.clientX - rect.left, event.clientY - rect.top);
1384 const localX = tile.tileX - chunkX * CHUNK_SIZE;
1385 const localY = tile.tileY - chunkY * CHUNK_SIZE;
1386 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
1387 { return; }
1388 const spawner = spawnerAt(localX, localY);
1389 if (spawner)
1390 {
1391 tileConfigModal.openSpawner({
1392 localX,
1393 localY,
1394 tileX: tile.tileX,
1395 tileY: tile.tileY,
1396 config: { ...spawner.config }
1397 });
1398 return;
1399 }
1400 const index = localY * CHUNK_SIZE + localX;
1401 const block = draft.blocks[index];
1402 if (block?.typeId === BlockType.doorway)
1403 {
1404 tileConfigModal.openDoorway({
1405 localX,
1406 localY,
1407 tileX: tile.tileX,
1408 tileY: tile.tileY,
1409 state: block.state ?? "door",
1410 config: block.config ? { ...block.config } : {}
1411 });
1412 }
1413});
1414
1415main().catch((error) =>
1416{
1417 $("error").textContent = error.message;
1418 console.error(error);
1419});