BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

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