BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

main.js 59.5 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 neighborConnectRefreshTiles,
31 worldTileToChunkLocal
32} from "/shared/world/neighborConnect.js";
33import { GameSocket, defaultSocketUrl } from "../net/socket.js";
34import { fetchAuthStatus, loginUrl, logoutUrl } from "../net/auth.js";
35import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
36import { WorldView } from "../render/worldView.js";
37import { initSettingsModal, initDimensionSettings } from "./settingsModal.js";
38import { initPaletteModal } from "./paletteModal.js";
39import { initTileConfigModal } from "./tileConfigModal.js";
40import { initQuestsModal } from "./questsModal.js";
41import { initDialoguesModal } from "./dialoguesModal.js";
42import { initGiftsModal } from "./giftsModal.js";
43import { createDimensionCombobox } from "./dimensionCombobox.js";
44import
45{
46 OVERWORLD_ID,
47 normalizeDimensionId,
48 isOverworld
49} from "/shared/world/dimensions.js";
50import { normalizeDoorConfig } from "/shared/world/doorRequirements.js";
51
52const game = new Game();
53let socket;
54let scene;
55let view;
56let draft = null;
57/** @type {string|null} JSON snapshot of last loaded/saved draft (grounds/blocks/spawners/open). */
58let draftBaseline = null;
59/** @type {ReturnType<typeof cloneDraftContents>|null} In-memory chunk clipboard for copy/paste. */
60let chunkClipboard = null;
61/**
62 * Neighbor chunks whose connect masks were updated while editing the selected chunk.
63 * Key `"chunkX,chunkY"` → `{ open, grounds, blocks, spawners }`.
64 * @type {Map<string, { open: boolean, grounds: object[], blocks: object[], spawners: object[] }>}
65 */
66let dirtyNeighborChunks = new Map();
67/** Spawners for loaded non-selected chunks (needed when saving edge-mask fixes). */
68let neighborSpawnersByChunk = new Map();
69/** @type {{ chunkX: number, chunkY: number, dimensionId?: string }|null} */
70let pendingNavigate = null;
71/** When true, next matching editorChunk after save should navigate to pendingNavigate. */
72let navigateAfterSave = false;
73let chunkX = 0;
74let chunkY = 0;
75let selectedDimensionId = OVERWORLD_ID;
76/** @type {string|null} */
77let pendingCreatedDimensionId = null;
78/** @type {Map<string, object>} */
79let dimensionsById = new Map();
80let dimensionCombo = null;
81let dimensionSettings = null;
82let tool = { kind: "ground", typeId: GroundType.grass, state: null };
83let settingsModal;
84let paletteModal;
85let tileConfigModal;
86let questsModal;
87let dialoguesModal;
88let giftsModal;
89let catalog = { grounds: {}, blocks: {}, images: [] };
90let imageUrlByName = new Map();
91let hoverLocal = null;
92let editorZoom = null;
93let activeRevisionId = null;
94let pendingRevisionId = null;
95let applyInFlight = false;
96/** @type {string|null} */
97let sessionAuthSubject = null;
98const EDITOR_ZOOM_MIN = 0.25;
99const EDITOR_ZOOM_MAX = 8;
100const EDITOR_ZOOM_STEP = 1.12;
101const CONSOLE_MAX_LINES = 2000;
102
103function $ (id)
104{
105 return document.getElementById(id);
106}
107
108function formatConsoleTime (t)
109{
110 try
111 { return new Date(t).toLocaleTimeString(); }
112 catch
113 { return ""; }
114}
115
116function appendConsoleLine (entry, { scroll = true } = {})
117{
118 const pre = $("editor-console");
119 if (!pre || !entry)
120 { return; }
121 const line = document.createElement("div");
122 const level = entry.level || "info";
123 line.className = `console-${level}`;
124 line.textContent = `[${formatConsoleTime(entry.t)}] ${entry.text ?? ""}`;
125 pre.append(line);
126 while (pre.childElementCount > CONSOLE_MAX_LINES)
127 { pre.firstChild?.remove(); }
128 if (scroll)
129 { pre.scrollTop = pre.scrollHeight; }
130}
131
132function applyConsoleSnapshot (lines)
133{
134 const pre = $("editor-console");
135 if (!pre)
136 { return; }
137 pre.replaceChildren();
138 for (const entry of lines ?? [])
139 { appendConsoleLine(entry, { scroll: false }); }
140 pre.scrollTop = pre.scrollHeight;
141}
142
143function initSidePanelTabs ()
144{
145 const tabs = document.querySelectorAll(".side-panel-tab");
146 const bodies = document.querySelectorAll("[data-side-panel-body]");
147 function activate (name)
148 {
149 for (const tab of tabs)
150 {
151 const on = tab.dataset.sidePanel === name;
152 tab.classList.toggle("active", on);
153 tab.setAttribute("aria-selected", on ? "true" : "false");
154 }
155 for (const body of bodies)
156 { body.hidden = body.dataset.sidePanelBody !== name; }
157 if (name === "console")
158 {
159 const pre = $("editor-console");
160 if (pre)
161 { pre.scrollTop = pre.scrollHeight; }
162 }
163 }
164 for (const tab of tabs)
165 {
166 tab.addEventListener("click", () => activate(tab.dataset.sidePanel));
167 }
168 $("console-clear")?.addEventListener("click", () =>
169 {
170 const pre = $("editor-console");
171 if (pre)
172 { pre.replaceChildren(); }
173 });
174 activate("changelog");
175}
176
177function selectedToolLabel ()
178{
179 if (tool.kind === "erase")
180 { return "Erase block"; }
181 if (tool.kind === "spawner")
182 {
183 const def = mobDefinition(tool.mobTypeId);
184 return `Spawner · ${def?.displayName ?? tool.mobTypeId}`;
185 }
186 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
187 const layer = tool.kind === "ground" ? "ground" : "block";
188 const states = statesForType(catalog, layer, def.key);
189 const state = resolveState(states, tool.state);
190 if (tool.kind === "block" && def.id === BlockType.flower)
191 { return "Flower"; }
192 if (tool.kind === "block" && def.id === BlockType.boulder)
193 {
194 const entry = listPlaceableBlockPaletteEntries(catalog)
195 .find((row) => row.typeId === def.id && row.state === state);
196 if (entry)
197 { return entry.displayName; }
198 }
199 if (states.length > 1)
200 { return `${def.displayName} (${state})`; }
201 return def.displayName;
202}
203
204function selectTool (next)
205{
206 if (next.kind === "erase")
207 {
208 tool = { kind: "erase" };
209 return;
210 }
211 if (next.kind === "spawner")
212 {
213 tool = { kind: "spawner", mobTypeId: next.mobTypeId };
214 return;
215 }
216 const layer = next.kind === "ground" ? "ground" : "block";
217 const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
218 tool = {
219 kind: next.kind,
220 typeId: next.typeId,
221 state: next.state ?? defaultStateForType(catalog, layer, def.key)
222 };
223}
224
225function placeableToolState ()
226{
227 if (tool.kind === "erase" || tool.kind === "spawner")
228 { return null; }
229 const layer = tool.kind === "ground" ? "ground" : "block";
230 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
231 return resolveState(statesForType(catalog, layer, def.key), tool.state);
232}
233
234function previewFromTool ()
235{
236 if (tool.kind === "erase")
237 { return { block: null }; }
238 if (tool.kind === "spawner")
239 { return {}; }
240 const state = placeableToolState();
241 if (tool.kind === "ground")
242 { return { ground: { typeId: tool.typeId, state } }; }
243 return { block: { typeId: tool.typeId, state, config: null } };
244}
245
246function inEditorView (x, y)
247{
248 return Math.abs(x - chunkX) <= VISIBLE_CHUNK_RADIUS && Math.abs(y - chunkY) <= VISIBLE_CHUNK_RADIUS;
249}
250
251function neighborhoodCoords (centerX, centerY)
252{
253 const coords = [];
254 for (let dy = -VISIBLE_CHUNK_RADIUS; dy <= VISIBLE_CHUNK_RADIUS; dy++)
255 {
256 for (let dx = -VISIBLE_CHUNK_RADIUS; dx <= VISIBLE_CHUNK_RADIUS; dx++)
257 { coords.push({ chunkX: centerX + dx, chunkY: centerY + dy }); }
258 }
259 return coords;
260}
261
262function snapshotFromPayload (payload)
263{
264 return {
265 chunkX: payload.chunkX,
266 chunkY: payload.chunkY,
267 open: payload.data.open,
268 closedEdges: payload.closedEdges,
269 grounds: payload.data.grounds,
270 blocks: payload.data.blocks,
271 light: payload.data.light,
272 entities: []
273 };
274}
275
276function syncSpawnersOverlay (cx, cy, spawners)
277{
278 view.setEditorSpawners(cx, cy, spawners ?? [], (mobTypeId) => mobSpriteName(mobTypeId));
279}
280
281function spawnerAt (localX, localY)
282{
283 return (draft?.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
284}
285
286function draftPersistable ()
287{
288 if (!draft)
289 { return null; }
290 return {
291 open: !!draft.open,
292 grounds: draft.grounds,
293 blocks: draft.blocks,
294 spawners: draft.spawners ?? []
295 };
296}
297
298function cloneDraftContents (source)
299{
300 if (!source)
301 { return null; }
302 const tileCount = CHUNK_SIZE * CHUNK_SIZE;
303 return {
304 open: !!source.open,
305 grounds: (source.grounds ?? []).map((ground) => normalizeGround(ground)),
306 blocks: (source.blocks ?? []).map((block) => (block
307 ? {
308 ...block,
309 config: block.config != null ? structuredClone(block.config) : null
310 }
311 : null)),
312 light: Array.isArray(source.light) && source.light.length === tileCount
313 ? source.light.slice()
314 : new Array(tileCount).fill(0),
315 spawners: (source.spawners ?? []).map((entry) => ({
316 localX: entry.localX | 0,
317 localY: entry.localY | 0,
318 config: structuredClone(entry.config ?? {})
319 }))
320 };
321}
322
323function blankChunkContents ()
324{
325 const groundTypeId = dimensionsById.get(selectedDimensionId)?.defaultGroundTypeId
326 ?? GroundType.grass;
327 const tileCount = CHUNK_SIZE * CHUNK_SIZE;
328 return {
329 open: false,
330 grounds: new Array(tileCount).fill(null).map(() => normalizeGround(groundTypeId, groundTypeId)),
331 blocks: new Array(tileCount).fill(null),
332 light: new Array(tileCount).fill(0),
333 spawners: []
334 };
335}
336
337function applyDraftContents (next)
338{
339 if (!draft || !next || isSelectedDimensionSoftDeleted())
340 { return; }
341 clearNeighborEditState();
342 draft.open = !!next.open;
343 draft.grounds = next.grounds.map((ground) => normalizeGround(ground));
344 draft.blocks = next.blocks.map((block) => (block
345 ? { ...block, config: block.config ?? null }
346 : null));
347 draft.light = Array.isArray(next.light) ? next.light.slice() : new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0);
348 draft.spawners = (next.spawners ?? []).map((entry) => ({
349 localX: entry.localX | 0,
350 localY: entry.localY | 0,
351 config: { ...(entry.config ?? {}) }
352 }));
353 $("open").checked = draft.open;
354 const existing = view?.chunks.get(chunkKey(chunkX, chunkY));
355 view.applySnapshot({
356 chunkX,
357 chunkY,
358 open: draft.open,
359 closedEdges: existing?.closedEdges,
360 grounds: draft.grounds,
361 blocks: draft.blocks,
362 light: draft.light,
363 entities: []
364 });
365 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
366 afterDraftMutation();
367}
368
369function syncChunkClipboardButtons ()
370{
371 const softDeleted = isSelectedDimensionSoftDeleted();
372 const copyBtn = $("copy-chunk");
373 const pasteBtn = $("paste-chunk");
374 const clearBtn = $("clear-chunk");
375 if (copyBtn)
376 {
377 copyBtn.disabled = !draft || softDeleted;
378 copyBtn.title = softDeleted
379 ? "Cannot copy while this dimension is soft-deleted"
380 : "Copy this chunk into the editor clipboard";
381 }
382 if (pasteBtn)
383 {
384 const canPaste = !!draft && !!chunkClipboard && !softDeleted;
385 pasteBtn.disabled = !canPaste;
386 pasteBtn.title = softDeleted
387 ? "Cannot paste while this dimension is soft-deleted"
388 : chunkClipboard
389 ? "Paste the copied chunk over the current draft (does not save)"
390 : "Copy a chunk first";
391 }
392 if (clearBtn)
393 {
394 clearBtn.disabled = !draft || softDeleted;
395 clearBtn.title = softDeleted
396 ? "Cannot clear while this dimension is soft-deleted"
397 : "Erase this chunk to a blank slate (does not save)";
398 }
399}
400
401function copySelectedChunk ()
402{
403 if (!draft || isSelectedDimensionSoftDeleted())
404 { return; }
405 chunkClipboard = cloneDraftContents(draft);
406 syncChunkClipboardButtons();
407}
408
409function pasteSelectedChunk ()
410{
411 if (!draft || !chunkClipboard || isSelectedDimensionSoftDeleted())
412 { return; }
413 const ok = window.confirm(
414 "This will replace your current chunk entirely with your copied chunk. Are you sure?"
415 );
416 if (!ok)
417 { return; }
418 applyDraftContents(cloneDraftContents(chunkClipboard));
419}
420
421function clearSelectedChunk ()
422{
423 if (!draft || isSelectedDimensionSoftDeleted())
424 { return; }
425 const ok = window.confirm(
426 "this will erase the chunk and reset it to a default blank slate. Are you certain?"
427 );
428 if (!ok)
429 { return; }
430 applyDraftContents(blankChunkContents());
431}
432
433function captureDraftBaseline ()
434{
435 const payload = draftPersistable();
436 draftBaseline = payload ? JSON.stringify(payload) : null;
437 syncSaveButton();
438}
439
440function chunkKey (cx, cy)
441{
442 return `${cx},${cy}`;
443}
444
445function isDraftDirty ()
446{
447 if (dirtyNeighborChunks.size > 0)
448 { return true; }
449 if (!draft || draftBaseline == null)
450 { return false; }
451 return JSON.stringify(draftPersistable()) !== draftBaseline;
452}
453
454function syncSaveButton ()
455{
456 const btn = $("save");
457 if (!btn)
458 { return; }
459 const softDeleted = isSelectedDimensionSoftDeleted();
460 const dirty = isDraftDirty();
461 btn.disabled = !dirty || softDeleted;
462 btn.classList.toggle("save-dirty", dirty && !softDeleted);
463 btn.title = softDeleted
464 ? "Cannot save while this dimension is soft-deleted"
465 : dirty
466 ? "Save unsaved chunk changes"
467 : "No unsaved changes";
468 syncChunkClipboardButtons();
469}
470
471function afterDraftMutation ()
472{
473 syncSaveButton();
474}
475
476function clearNeighborEditState ()
477{
478 dirtyNeighborChunks.clear();
479}
480
481function groundAtWorld (tileX, tileY)
482{
483 const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
484 const index = localY * CHUNK_SIZE + localX;
485 if (cx === chunkX && cy === chunkY && draft)
486 { return draft.grounds[index] ?? null; }
487 const dirty = dirtyNeighborChunks.get(chunkKey(cx, cy));
488 if (dirty)
489 { return dirty.grounds[index] ?? null; }
490 const snapshot = view?.chunks.get(chunkKey(cx, cy));
491 return snapshot?.grounds?.[index] ?? null;
492}
493
494function spawnerAtWorld (tileX, tileY)
495{
496 const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
497 if (cx === chunkX && cy === chunkY && draft)
498 { return spawnerAt(localX, localY); }
499 const dirty = dirtyNeighborChunks.get(chunkKey(cx, cy));
500 if (dirty)
501 { return dirty.spawners?.find((entry) => entry.localX === localX && entry.localY === localY) ?? null; }
502 return (neighborSpawnersByChunk.get(chunkKey(cx, cy)) ?? [])
503 .find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
504}
505
506/** Human-readable summary of authored ground/block/spawner on a world tile. */
507function describeWorldTile (tileX, tileY, dimensionId = selectedDimensionId)
508{
509 const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);
510 if (dim !== selectedDimensionId)
511 {
512 return `Currently editing “${selectedDimensionId}”; switch to “${dim}” to inspect this tile.`;
513 }
514 const { chunkX: cx, chunkY: cy } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
515 const key = chunkKey(cx, cy);
516 const loaded = (cx === chunkX && cy === chunkY && draft)
517 || dirtyNeighborChunks.has(key)
518 || view?.chunks?.has(key);
519 if (!loaded)
520 { return `Chunk (${cx}, ${cy}) not loaded — center on this tile to load it.`; }
521
522 const lines = [];
523 const ground = normalizeGround(groundAtWorld(tileX, tileY));
524 const groundDef = GROUND_DEFINITIONS[ground?.typeId];
525 lines.push(`Ground: ${groundDef?.displayName ?? `type ${ground?.typeId ?? "?"}`}`);
526 const block = normalizeBlock(blockAtWorld(tileX, tileY));
527 if (block)
528 {
529 const blockDef = BLOCK_DEFINITIONS[block.typeId];
530 lines.push(`Block: ${blockDef?.displayName ?? `type ${block.typeId}`}${block.state ? ` (${block.state})` : ""}`);
531 if (block.config && Object.keys(block.config).length)
532 {
533 for (const [keyName, value] of Object.entries(block.config))
534 { lines.push(` ${keyName}: ${value}`); }
535 }
536 }
537 else
538 { lines.push("Block: (none)"); }
539 const spawner = spawnerAtWorld(tileX, tileY);
540 if (spawner)
541 {
542 const config = normalizeSpawnerConfig(spawner.config, spawner.config?.spawnerId);
543 const mob = mobDefinition(config.mobTypeId);
544 lines.push(`Spawner: ${mob?.displayName ?? config.mobTypeId} (${config.spawnerId})`);
545 }
546 else
547 { lines.push("Spawner: (none)"); }
548 return lines.join("\n");
549}
550
551/** Pan the editor to a world tile without closing other UI; loads its chunk neighborhood. */
552function centerEditorOnTile (tileX, tileY, dimensionId = selectedDimensionId)
553{
554 const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);
555 const { chunkX: cx, chunkY: cy } = worldTileToChunkLocal(tileX | 0, tileY | 0, CHUNK_SIZE);
556 if (dim !== selectedDimensionId)
557 {
558 if (isDraftDirty())
559 {
560 showUnsavedModal({ chunkX: cx, chunkY: cy, dimensionId: dim });
561 return false;
562 }
563 selectedDimensionId = dim;
564 syncDimensionUi();
565 clearNeighborhoodView();
566 doLoadNeighborhood(cx, cy);
567 }
568 else if (cx !== chunkX || cy !== chunkY)
569 {
570 if (isDraftDirty())
571 {
572 showUnsavedModal({ chunkX: cx, chunkY: cy, dimensionId: selectedDimensionId });
573 return false;
574 }
575 doLoadNeighborhood(cx, cy);
576 }
577 if (!view?.scene)
578 { return true; }
579 const size = view.tileSize();
580 view.followPlayer = false;
581 view.scene.cameraPosition.x = view.scene.real_size.x / 2 - ((tileX | 0) + 0.5) * size;
582 view.scene.cameraPosition.y = view.scene.real_size.y / 2 - ((tileY | 0) + 0.5) * size;
583 view.refreshViewport();
584 updateSelectionBorder();
585 return true;
586}
587
588function blockAtWorld (tileX, tileY)
589{
590 const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
591 if (cx === chunkX && cy === chunkY && draft)
592 { return draft.blocks[localY * CHUNK_SIZE + localX] ?? null; }
593 const dirty = dirtyNeighborChunks.get(chunkKey(cx, cy));
594 if (dirty)
595 { return dirty.blocks[localY * CHUNK_SIZE + localX] ?? null; }
596 const snapshot = view?.chunks.get(chunkKey(cx, cy));
597 return snapshot?.blocks?.[localY * CHUNK_SIZE + localX] ?? null;
598}
599
600function ensureDirtyNeighborChunk (cx, cy)
601{
602 const key = chunkKey(cx, cy);
603 let data = dirtyNeighborChunks.get(key);
604 if (data)
605 { return data; }
606 const snapshot = view?.chunks.get(key);
607 if (!snapshot)
608 { return null; }
609 data = {
610 open: !!snapshot.open,
611 grounds: (snapshot.grounds ?? []).map((ground) => normalizeGround(ground)),
612 blocks: (snapshot.blocks ?? []).map((block) => (block ? { ...block, config: block.config ?? null } : null)),
613 spawners: structuredClone(neighborSpawnersByChunk.get(key) ?? [])
614 };
615 dirtyNeighborChunks.set(key, data);
616 return data;
617}
618
619function writeBlockAtWorld (tileX, tileY, block)
620{
621 const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
622 const index = localY * CHUNK_SIZE + localX;
623 if (cx === chunkX && cy === chunkY && draft)
624 {
625 draft.blocks[index] = block;
626 view.updateAuthoredTile(cx, cy, localX, localY, {
627 ground: draft.grounds[index],
628 block: draft.blocks[index],
629 light: draft.light[index]
630 });
631 return true;
632 }
633 const data = ensureDirtyNeighborChunk(cx, cy);
634 if (!data)
635 { return false; }
636 data.blocks[index] = block;
637 const snapshot = view?.chunks.get(chunkKey(cx, cy));
638 const light = snapshot?.light?.[index];
639 view.updateAuthoredTile(cx, cy, localX, localY, {
640 ground: data.grounds[index],
641 block: data.blocks[index],
642 light
643 });
644 return true;
645}
646
647function showUnsavedModal (target)
648{
649 pendingNavigate = target;
650 $("unsaved-chunk-backdrop").hidden = false;
651 $("unsaved-chunk-modal").hidden = false;
652}
653
654function hideUnsavedModal ()
655{
656 $("unsaved-chunk-backdrop").hidden = true;
657 $("unsaved-chunk-modal").hidden = true;
658}
659
660function saveSelectedChunk ()
661{
662 if (!draft || !isDraftDirty())
663 { return false; }
664 if (isSelectedDimensionSoftDeleted())
665 {
666 $("error").textContent = "Cannot save while this dimension is soft-deleted.";
667 return false;
668 }
669 $("error").textContent = "";
670 $("apply-status").textContent = "";
671 $("apply-status").className = "hint";
672 const neighborSaves = [...dirtyNeighborChunks.entries()];
673 clearNeighborEditState();
674 const savedChunks = [{ chunkX, chunkY }];
675 socket.send({
676 type: MessageType.editorSaveChunk,
677 chunkX,
678 chunkY,
679 dimensionId: selectedDimensionId,
680 draft: {
681 open: $("open").checked,
682 grounds: draft.grounds,
683 blocks: draft.blocks,
684 spawners: draft.spawners ?? []
685 }
686 });
687 for (const [key, data] of neighborSaves)
688 {
689 const [cx, cy] = key.split(",").map(Number);
690 savedChunks.push({ chunkX: cx, chunkY: cy });
691 socket.send({
692 type: MessageType.editorSaveChunk,
693 chunkX: cx,
694 chunkY: cy,
695 dimensionId: selectedDimensionId,
696 draft: {
697 open: data.open,
698 grounds: data.grounds,
699 blocks: data.blocks,
700 spawners: data.spawners ?? []
701 }
702 });
703 }
704 view?.bakeNatureTintForChunks?.(savedChunks);
705 requestNeighbors();
706 return true;
707}
708
709function isSelectedDimensionSoftDeleted ()
710{
711 const record = dimensionsById.get(selectedDimensionId);
712 return record?.deletedAt != null;
713}
714
715function formatPurgeHint (record)
716{
717 if (!record?.purgeAfter)
718 { return "Soft-deleted — painting disabled."; }
719 const when = new Date(record.purgeAfter);
720 return `Soft-deleted — purges ${when.toLocaleString()} (painting disabled).`;
721}
722
723function syncDimensionUi ()
724{
725 const record = dimensionsById.get(selectedDimensionId);
726 const softDeleted = record?.deletedAt != null;
727 const hint = $("dimension-purge-hint");
728 if (hint)
729 {
730 hint.hidden = !softDeleted;
731 hint.textContent = softDeleted ? formatPurgeHint(record) : "";
732 }
733 const openToggle = $("open");
734 if (openToggle)
735 { openToggle.disabled = softDeleted; }
736 dimensionCombo?.setValue(selectedDimensionId);
737 dimensionSettings?.refresh();
738 syncSaveButton();
739}
740
741function applyDimensionsList (payload)
742{
743 const list = Array.isArray(payload?.dimensions) ? payload.dimensions : [];
744 dimensionsById = new Map(list.map((dim) => [dim.dimensionId, dim]));
745 if (!dimensionsById.has(OVERWORLD_ID))
746 {
747 dimensionsById.set(OVERWORLD_ID, {
748 dimensionId: OVERWORLD_ID,
749 displayName: "Overworld",
750 lightingMode: "dayNight",
751 seasonMode: "auto",
752 defaultGroundTypeId: 1,
753 deletedAt: null,
754 purgeAfter: null
755 });
756 }
757 const options = [...dimensionsById.values()].map((dim) => ({
758 id: dim.dimensionId,
759 label: dim.displayName || dim.dimensionId,
760 disabled: dim.deletedAt != null,
761 hint: dim.deletedAt != null ? formatPurgeHint(dim) : null
762 }));
763 dimensionCombo?.setOptions(options);
764 const createdId = pendingCreatedDimensionId;
765 pendingCreatedDimensionId = null;
766 if (createdId && dimensionsById.has(createdId))
767 {
768 setRevisionState({
769 activeRevisionId: payload.activeRevisionId,
770 pendingRevisionId: payload.pendingRevisionId
771 });
772 selectDimension(createdId, { force: true });
773 return;
774 }
775 if (!dimensionsById.has(selectedDimensionId))
776 { selectedDimensionId = OVERWORLD_ID; }
777 setRevisionState({
778 activeRevisionId: payload.activeRevisionId,
779 pendingRevisionId: payload.pendingRevisionId
780 });
781 syncDimensionUi();
782 if (!isDraftDirty())
783 { requestChunks(neighborhoodCoords(chunkX, chunkY)); }
784}
785
786function requestDimensions ()
787{
788 socket.send({ type: MessageType.editorListDimensions });
789}
790
791function selectDimension (dimensionId, { force = false } = {})
792{
793 const nextId = normalizeDimensionId(dimensionId);
794 if (!force && nextId === selectedDimensionId)
795 { return; }
796 if (!force && isDraftDirty())
797 {
798 showUnsavedModal({ chunkX, chunkY, dimensionId: nextId });
799 dimensionCombo?.setValue(selectedDimensionId);
800 return;
801 }
802 selectedDimensionId = nextId;
803 syncDimensionUi();
804 clearNeighborhoodView();
805 doLoadNeighborhood(chunkX, chunkY);
806}
807
808function clearNeighborhoodView ()
809{
810 draft = null;
811 draftBaseline = null;
812 clearNeighborEditState();
813 neighborSpawnersByChunk.clear();
814 if (!view)
815 { return; }
816 for (const key of [...view.chunks.keys()])
817 {
818 const [x, y] = key.split(",").map(Number);
819 view.removeChunk(x, y);
820 }
821 view.clearEditorSpawners?.();
822 syncSaveButton();
823}
824
825function paintAt (localX, localY)
826{
827 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
828 { return; }
829 if (isSelectedDimensionSoftDeleted())
830 { return; }
831 const index = localY * CHUNK_SIZE + localX;
832 const state = placeableToolState();
833 if (tool.kind === "ground")
834 { draft.grounds[index] = { typeId: tool.typeId, state }; }
835 else if (tool.kind === "erase")
836 {
837 const removed = draft.blocks[index];
838 draft.blocks[index] = null;
839 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
840 ground: draft.grounds[index],
841 block: draft.blocks[index],
842 light: draft.light[index]
843 });
844 if (removed && definitionUsesNeighborConnect(BLOCK_DEFINITIONS[removed.typeId]))
845 { refreshNeighborConnect(localX, localY, removed.typeId); }
846 afterDraftMutation();
847 return;
848 }
849 else if (tool.kind === "spawner")
850 {
851 const existing = spawnerAt(localX, localY);
852 const spawnerId = existing?.config?.spawnerId ?? `${chunkX}:${chunkY}:${index}`;
853 const entry = {
854 localX,
855 localY,
856 config: normalizeSpawnerConfig({
857 ...defaultSpawnerConfig(spawnerId, tool.mobTypeId),
858 ...(existing?.config ?? {}),
859 spawnerId,
860 mobTypeId: tool.mobTypeId
861 }, spawnerId)
862 };
863 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY);
864 draft.spawners.push(entry);
865 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
866 afterDraftMutation();
867 return;
868 }
869 else
870 {
871 const def = BLOCK_DEFINITIONS[tool.typeId];
872 if (def?.id === BlockType.fishingSpot)
873 {
874 const groundType = draft.grounds[index]?.typeId;
875 if (groundType !== GroundType.water && groundType !== GroundType.deepWater)
876 { return; }
877 }
878 let nextState = definitionUsesNeighborConnect(def)
879 ? composeNeighborConnectState(def, state, 0)
880 : state;
881 if (def?.id === BlockType.flower)
882 { nextState = flowerBlockState(randomFlowerColorId()); }
883 if (def?.id === BlockType.fishingSpot && !nextState)
884 { nextState = "fishing-spot"; }
885 const config = def?.id === BlockType.doorway
886 ? {
887 targetDimensionId: selectedDimensionId,
888 tileX: chunkX * CHUNK_SIZE + localX,
889 tileY: chunkY * CHUNK_SIZE + localY
890 }
891 : (def?.id === BlockType.fishingSpot
892 ? { fishes: [] }
893 : null);
894 if (def?.id === BlockType.doorway && !nextState)
895 { nextState = "door"; }
896 draft.blocks[index] = { typeId: tool.typeId, state: nextState, config };
897 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
898 ground: draft.grounds[index],
899 block: draft.blocks[index],
900 light: draft.light[index]
901 });
902 if (definitionUsesNeighborConnect(def))
903 { refreshNeighborConnect(localX, localY, tool.typeId); }
904 afterDraftMutation();
905 return;
906 }
907 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
908 ground: draft.grounds[index],
909 block: draft.blocks[index],
910 light: draft.light[index]
911 });
912 afterDraftMutation();
913}
914
915/** Recompute neighbor-connect masks around a local tile, including across chunk edges. */
916function refreshNeighborConnect (localX, localY, typeId)
917{
918 const def = BLOCK_DEFINITIONS[typeId];
919 if (!draft || !definitionUsesNeighborConnect(def))
920 { return; }
921 const originTileX = chunkX * CHUNK_SIZE + localX;
922 const originTileY = chunkY * CHUNK_SIZE + localY;
923 for (const [tileX, tileY] of neighborConnectRefreshTiles(originTileX, originTileY))
924 {
925 const block = blockAtWorld(tileX, tileY);
926 if (!block || block.typeId !== typeId)
927 { continue; }
928 const mask = computeNeighborConnectMask((dx, dy) =>
929 {
930 const neighbor = blockAtWorld(tileX + dx, tileY + dy);
931 return neighborConnectBlocksMatch(block, neighbor, def);
932 });
933 const nextState = composeNeighborConnectState(def, block.state, mask);
934 if (block.state === nextState)
935 { continue; }
936 writeBlockAtWorld(tileX, tileY, { ...block, state: nextState });
937 }
938}
939
940function updateRevisionUI ()
941{
942 const applyBtn = $("apply");
943 $("revision").textContent = `active ${activeRevisionId ?? "?"}` +
944 (pendingRevisionId ? ` · pending ${pendingRevisionId}` : " · no pending revision");
945 if (applyBtn)
946 {
947 applyBtn.disabled = !pendingRevisionId || applyInFlight;
948 applyBtn.title = pendingRevisionId
949 ? "Reload the live world with the pending map revision"
950 : "Save a chunk first to create a pending revision";
951 }
952}
953
954function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pending })
955{
956 if (active != null)
957 { activeRevisionId = active; }
958 pendingRevisionId = pending ?? null;
959 updateRevisionUI();
960}
961
962function showSelectedChunk (payload)
963{
964 clearNeighborEditState();
965 draft = {
966 open: payload.data.open,
967 grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
968 blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)),
969 light: payload.data.light.slice(),
970 spawners: (payload.data.spawners ?? []).map((entry) => ({
971 localX: entry.localX,
972 localY: entry.localY,
973 config: { ...entry.config }
974 }))
975 };
976 $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`;
977 $("open").checked = draft.open;
978 setRevisionState({
979 activeRevisionId: payload.activeRevisionId,
980 pendingRevisionId: payload.pendingRevisionId
981 });
982 $("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)";
983 const log = $("changelog");
984 log.innerHTML = "";
985 for (const entry of payload.changelog ?? [])
986 {
987 const item = document.createElement("article");
988 item.innerHTML = `<header>${entry.editorDisplayName || entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
989 const list = document.createElement("ul");
990 for (const bullet of entry.diffEntries)
991 {
992 const li = document.createElement("li");
993 li.textContent = bullet;
994 list.append(li);
995 }
996 item.append(list);
997 log.append(item);
998 }
999 view.applySnapshot(snapshotFromPayload(payload));
1000 syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);
1001 captureDraftBaseline();
1002 syncSaveButton();
1003 if (navigateAfterSave && pendingNavigate)
1004 {
1005 const next = pendingNavigate;
1006 navigateAfterSave = false;
1007 pendingNavigate = null;
1008 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1009 if (nextDim !== selectedDimensionId)
1010 {
1011 selectedDimensionId = nextDim;
1012 syncDimensionUi();
1013 clearNeighborhoodView();
1014 }
1015 doLoadNeighborhood(next.chunkX, next.chunkY);
1016 }
1017}
1018
1019function pruneView ()
1020{
1021 for (const key of [...view.chunks.keys()])
1022 {
1023 const [x, y] = key.split(",").map(Number);
1024 if (!inEditorView(x, y))
1025 {
1026 view.removeChunk(x, y);
1027 neighborSpawnersByChunk.delete(key);
1028 dirtyNeighborChunks.delete(key);
1029 }
1030 }
1031}
1032
1033function frameNeighborhood ()
1034{
1035 const size = view.tileSize();
1036 view.followPlayer = false;
1037 const centerX = (chunkX + 0.5) * CHUNK_SIZE * size;
1038 const centerY = (chunkY + 0.5) * CHUNK_SIZE * size;
1039 view.scene.cameraPosition.x = view.scene.real_size.x / 2 - centerX;
1040 view.scene.cameraPosition.y = view.scene.real_size.y / 2 - centerY;
1041 view.refreshViewport();
1042 updateSelectionBorder();
1043}
1044
1045function updateSelectionBorder ()
1046{
1047 const border = $("selection-border");
1048 const canvas = scene?.canvas;
1049 if (!border || !canvas)
1050 { return; }
1051
1052 const rect = canvas.getBoundingClientRect();
1053 const size = view.tileSize();
1054 const chunkPx = CHUNK_SIZE * size;
1055 const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x;
1056 const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y;
1057 border.style.left = `${rect.left + screenLeft}px`;
1058 border.style.top = `${rect.top + screenTop}px`;
1059 border.style.width = `${chunkPx}px`;
1060 border.style.height = `${chunkPx}px`;
1061}
1062
1063function layoutScene ()
1064{
1065 const header = document.querySelector("body > header");
1066 const aside = document.querySelector("body > aside");
1067 const sidePanels = $("side-panels") || $("changelog-wrap");
1068 const top = header.offsetHeight;
1069 aside.style.top = `${top}px`;
1070 sidePanels.style.top = `${top}px`;
1071 const left = aside.offsetWidth;
1072 const right = sidePanels.offsetWidth;
1073 const width = Math.max(64, window.innerWidth - left - right);
1074 const height = Math.max(64, window.innerHeight - top);
1075 scene.position.x = left;
1076 scene.position.y = top;
1077 scene.size.x = width;
1078 scene.size.y = height;
1079 scene.g_fixSize();
1080 useNearestNeighbour(scene, game.images);
1081 const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX);
1082 if (editorZoom == null)
1083 { editorZoom = fit; }
1084 else
1085 { editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, editorZoom)); }
1086 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
1087 frameNeighborhood();
1088}
1089
1090function zoomEditor (direction)
1091{
1092 if (!view)
1093 { return; }
1094 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
1095 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
1096 scheduleEditorZoom();
1097}
1098
1099let editorZoomRaf = 0;
1100function scheduleEditorZoom ()
1101{
1102 if (editorZoomRaf)
1103 { return; }
1104 editorZoomRaf = requestAnimationFrame(() =>
1105 {
1106 editorZoomRaf = 0;
1107 if (!view)
1108 { return; }
1109 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
1110 frameNeighborhood();
1111 });
1112}
1113
1114function requestChunks (coords)
1115{
1116 if (!socket?.socket || socket.socket.readyState !== WebSocket.OPEN)
1117 { return; }
1118 for (const coord of coords)
1119 {
1120 try
1121 {
1122 socket.send({
1123 type: MessageType.editorLoadChunk,
1124 chunkX: coord.chunkX,
1125 chunkY: coord.chunkY,
1126 dimensionId: selectedDimensionId
1127 });
1128 }
1129 catch (_)
1130 { break; }
1131 }
1132}
1133
1134function doLoadNeighborhood (x, y)
1135{
1136 chunkX = x;
1137 chunkY = y;
1138 $("coords").textContent = `${chunkX}, ${chunkY}`;
1139 requestChunks(neighborhoodCoords(x, y));
1140}
1141
1142function loadNeighborhood (x, y)
1143{
1144 if ((x !== chunkX || y !== chunkY) && isDraftDirty())
1145 {
1146 showUnsavedModal({ chunkX: x, chunkY: y, dimensionId: selectedDimensionId });
1147 return;
1148 }
1149 doLoadNeighborhood(x, y);
1150}
1151
1152function requestNeighbors ()
1153{
1154 requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
1155}
1156
1157function anyModalOpen ()
1158{
1159 return settingsModal?.isOpen()
1160 || paletteModal?.isOpen()
1161 || tileConfigModal?.isOpen()
1162 || questsModal?.isOpen()
1163 || dialoguesModal?.isOpen()
1164 || giftsModal?.isOpen()
1165 || !$("unsaved-chunk-modal")?.hidden
1166 || !$("global-changelog-modal")?.hidden;
1167}
1168
1169function updateHoverStatus (local)
1170{
1171 const el = $("hover-status-text");
1172 if (!el)
1173 { return; }
1174 if (!local)
1175 {
1176 el.textContent = "Hover a tile for coordinates";
1177 return;
1178 }
1179 const hoverChunkX = local.chunkX ?? Math.floor(local.tileX / CHUNK_SIZE);
1180 const hoverChunkY = local.chunkY ?? Math.floor(local.tileY / CHUNK_SIZE);
1181 el.textContent = `Tile (${local.tileX}, ${local.tileY}) · Chunk (${hoverChunkX}, ${hoverChunkY})`;
1182}
1183
1184function updateTooltip (local, options = {})
1185{
1186 if (!options.keepStatus)
1187 { updateHoverStatus(local); }
1188 const tip = $("tile-tooltip");
1189 if (!tip || !local || !draft)
1190 {
1191 if (tip)
1192 { tip.hidden = true; }
1193 view?.clearSpawnRangeHighlight();
1194 return;
1195 }
1196 const block = normalizeBlock(draft.blocks[local.y * CHUNK_SIZE + local.x]);
1197 const spawner = spawnerAt(local.x, local.y);
1198 const lines = [];
1199 if (block)
1200 {
1201 const def = BLOCK_DEFINITIONS[block.typeId];
1202 lines.push(def?.displayName ?? `Block ${block.typeId}`);
1203 if (block.config && Object.keys(block.config).length)
1204 {
1205 for (const [key, value] of Object.entries(block.config))
1206 { lines.push(`${key}: ${value}`); }
1207 }
1208 }
1209 if (spawner)
1210 {
1211 const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId);
1212 const mob = mobDefinition(config.mobTypeId);
1213 lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`);
1214 lines.push(`maxAlive: ${config.maxAlive}`);
1215 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
1216 lines.push(`wanderRange: ${config.maxWanderRangeTiles}`);
1217 lines.push(`id: ${config.spawnerId}`);
1218 view.setSpawnRangeHighlight(
1219 local.tileX,
1220 local.tileY,
1221 config.spawnRangeTiles,
1222 config.maxWanderRangeTiles
1223 );
1224 }
1225 else
1226 { view.clearSpawnRangeHighlight(); }
1227 if (!lines.length)
1228 {
1229 tip.hidden = true;
1230 return;
1231 }
1232 tip.hidden = false;
1233 tip.textContent = lines.join("\n");
1234 const canvas = scene.canvas;
1235 const rect = canvas.getBoundingClientRect();
1236 const size = view.tileSize();
1237 const screenX = local.tileX * size + scene.cameraPosition.x + rect.left + size;
1238 const screenY = local.tileY * size + scene.cameraPosition.y + rect.top;
1239 tip.style.left = `${screenX}px`;
1240 tip.style.top = `${screenY}px`;
1241}
1242
1243async function main ()
1244{
1245 const authStatus = await fetchAuthStatus();
1246 const signIn = document.getElementById("auth-sign-in");
1247 const signOut = document.getElementById("auth-sign-out");
1248 if (signIn)
1249 {
1250 signIn.hidden = !!authStatus?.authenticated;
1251 signIn.href = loginUrl("/editor");
1252 }
1253 if (signOut)
1254 {
1255 signOut.hidden = !authStatus?.authenticated;
1256 signOut.href = logoutUrl("/editor");
1257 }
1258 if (!authStatus.authenticated)
1259 {
1260 $("who").textContent = "Sign in required";
1261 $("error").textContent = "Sign in with your Tim Falken account to use the world editor.";
1262 return;
1263 }
1264
1265 const accountLabel = authStatus.username ?? authStatus.email ?? authStatus.authSubject ?? "Signed in";
1266 $("who").textContent = `${accountLabel} · loading sprites…`;
1267
1268 catalog = await loadSpriteCatalog();
1269 imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));
1270 await preloadCatalogImages(game, catalog, {
1271 onProgress ({ loaded, total })
1272 {
1273 $("who").textContent = `${accountLabel} · loading sprites ${loaded}/${total}`;
1274 }
1275 });
1276 applySpriteSheets(game.images, catalog);
1277 scene = new Scene(250, 56, 64, 64);
1278 game.loadScene(scene);
1279 view = new WorldView(game, scene, catalog);
1280 view.followPlayer = false;
1281 view.natureTintEnabled = false;
1282 view.setGraphicsPrefs(loadGraphicsSettings());
1283 syncSeasonControls(view.worldSeason ?? seasonIdAt());
1284 layoutScene();
1285 selectTool(tool);
1286 $("tool").textContent = selectedToolLabel();
1287
1288 paletteModal = initPaletteModal({
1289 catalog,
1290 imageUrlFor (name)
1291 {
1292 const sprite = game.images[name];
1293 const html = sprite?.g_image;
1294 if (html && typeof html.toDataURL === "function")
1295 {
1296 try
1297 { return html.toDataURL("image/png"); }
1298 catch (_)
1299 { /* fall through */ }
1300 }
1301 return imageUrlByName.get(name) ?? null;
1302 },
1303 onSelect (next)
1304 {
1305 selectTool(next);
1306 $("tool").textContent = selectedToolLabel();
1307 }
1308 });
1309
1310 tileConfigModal = initTileConfigModal({
1311 socket: {
1312 send (payload)
1313 {
1314 socket?.send(payload);
1315 }
1316 },
1317 MessageType,
1318 getDialogues: () => dialoguesModal?.getDialogues?.() ?? [],
1319 getQuests: () => questsModal?.getQuests?.() ?? [],
1320 describeWorldTile,
1321 centerEditorOnTile,
1322 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
1323 id: dim.dimensionId,
1324 label: dim.displayName || dim.dimensionId,
1325 disabled: !!dim.deletedAt,
1326 hint: dim.deletedAt ? "soft-deleted" : undefined
1327 })),
1328 onSave (ctx, config)
1329 {
1330 if (!draft)
1331 { return; }
1332 if (ctx.kind === "doorway")
1333 {
1334 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1335 draft.blocks[index] = {
1336 typeId: BlockType.doorway,
1337 state: config.state || "door",
1338 config: {
1339 targetDimensionId: normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID),
1340 tileX: Number(config.tileX) || 0,
1341 tileY: Number(config.tileY) || 0
1342 }
1343 };
1344 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1345 ground: draft.grounds[index],
1346 block: draft.blocks[index],
1347 light: draft.light[index]
1348 });
1349 afterDraftMutation();
1350 return;
1351 }
1352 if (ctx.kind === "door")
1353 {
1354 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1355 const existing = draft.blocks[index];
1356 if (!existing || existing.typeId !== BlockType.door)
1357 { return; }
1358 const prev = existing.config && typeof existing.config === "object" ? { ...existing.config } : {};
1359 const nextConfig = normalizeDoorConfig({
1360 ...prev,
1361 when: config.when,
1362 blockedMessage: config.blockedMessage
1363 });
1364 draft.blocks[index] = {
1365 typeId: BlockType.door,
1366 state: existing.state,
1367 config: nextConfig
1368 };
1369 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1370 ground: draft.grounds[index],
1371 block: draft.blocks[index],
1372 light: draft.light[index]
1373 });
1374 afterDraftMutation();
1375 return;
1376 }
1377 if (ctx.kind === "fishing-spot")
1378 {
1379 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1380 const existing = draft.blocks[index];
1381 draft.blocks[index] = {
1382 typeId: BlockType.fishingSpot,
1383 state: existing?.state === "exhausted" ? "exhausted" : "fishing-spot",
1384 config: { fishes: [...(config.fishes ?? [])] }
1385 };
1386 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1387 ground: draft.grounds[index],
1388 block: draft.blocks[index],
1389 light: draft.light[index]
1390 });
1391 afterDraftMutation();
1392 return;
1393 }
1394 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1395 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
1396 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1397 afterDraftMutation();
1398 },
1399 onRemove (ctx)
1400 {
1401 if (!draft)
1402 { return; }
1403 if (ctx.kind === "door")
1404 {
1405 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1406 const existing = draft.blocks[index];
1407 if (!existing || existing.typeId !== BlockType.door)
1408 { return; }
1409 const prev = existing.config && typeof existing.config === "object" ? { ...existing.config } : {};
1410 delete prev.when;
1411 delete prev.requirements;
1412 delete prev.blockedMessage;
1413 delete prev.denyMessage;
1414 draft.blocks[index] = {
1415 typeId: BlockType.door,
1416 state: existing.state,
1417 config: normalizeDoorConfig(prev)
1418 };
1419 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1420 ground: draft.grounds[index],
1421 block: draft.blocks[index],
1422 light: draft.light[index]
1423 });
1424 afterDraftMutation();
1425 return;
1426 }
1427 if (ctx.kind === "doorway")
1428 {
1429 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1430 draft.blocks[index] = null;
1431 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1432 ground: draft.grounds[index],
1433 block: draft.blocks[index],
1434 light: draft.light[index]
1435 });
1436 afterDraftMutation();
1437 return;
1438 }
1439 if (ctx.kind === "fishing-spot")
1440 {
1441 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1442 draft.blocks[index] = null;
1443 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1444 ground: draft.grounds[index],
1445 block: draft.blocks[index],
1446 light: draft.light[index]
1447 });
1448 afterDraftMutation();
1449 return;
1450 }
1451 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1452 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1453 afterDraftMutation();
1454 }
1455 });
1456
1457 const ticker = new GameObject(0, 0, null, 10);
1458 ticker.update = (dt) =>
1459 {
1460 hoverLocal = null;
1461 const canvas = scene.canvas;
1462 const rect = canvas.getBoundingClientRect();
1463 const mouseX = GameInput.mousePosition.x - rect.left;
1464 const mouseY = GameInput.mousePosition.y - rect.top;
1465 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
1466 if (overCanvas && draft && !anyModalOpen())
1467 {
1468 const tile = view.screenToTile(mouseX, mouseY);
1469 const localX = tile.tileX - chunkX * CHUNK_SIZE;
1470 const localY = tile.tileY - chunkY * CHUNK_SIZE;
1471 const hoverChunkX = Math.floor(tile.tileX / CHUNK_SIZE);
1472 const hoverChunkY = Math.floor(tile.tileY / CHUNK_SIZE);
1473 updateHoverStatus({
1474 tileX: tile.tileX,
1475 tileY: tile.tileY,
1476 x: ((tile.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1477 y: ((tile.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1478 chunkX: hoverChunkX,
1479 chunkY: hoverChunkY
1480 });
1481 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
1482 {
1483 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
1484 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
1485 updateTooltip(hoverLocal);
1486 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
1487 { paintAt(localX, localY); }
1488 }
1489 else
1490 {
1491 hoverLocal = null;
1492 view.clearTilePreview();
1493 updateTooltip(null, { keepStatus: true });
1494 }
1495 }
1496 else
1497 {
1498 view.clearTilePreview();
1499 updateTooltip(null);
1500 }
1501 view.update(dt);
1502 frameNeighborhood();
1503 };
1504 scene.addObject(ticker);
1505 window.addEventListener("resize", layoutScene);
1506
1507 $("who").textContent = `${accountLabel} · connecting…`;
1508
1509 socket = new GameSocket(defaultSocketUrl(), (message) =>
1510 {
1511 if (message.type === MessageType.session)
1512 {
1513 sessionAuthSubject = message.authSubject ?? null;
1514 const label = message.username ?? message.authSubject ?? "Unknown";
1515 $("who").textContent = `${label}${message.isAdmin ? " · admin" : " · not admin"}`;
1516 if (!message.isAdmin)
1517 {
1518 $("error").textContent = "Admin access required.";
1519 return;
1520 }
1521 $("error").textContent = "";
1522 const restartBtn = document.getElementById("editor-restart-now");
1523 if (restartBtn)
1524 {
1525 restartBtn.hidden = false;
1526 restartBtn.disabled = false;
1527 }
1528 socket.send({ type: MessageType.editorLoadSettings });
1529 socket.send({ type: MessageType.editorLoadGameAdmins });
1530 socket.send({ type: MessageType.editorConsoleSubscribe });
1531 requestDimensions();
1532 loadNeighborhood(0, 0);
1533 }
1534 else if (message.type === MessageType.editorSettings
1535 || message.type === MessageType.editorGameAdmins)
1536 { settingsModal.handleMessage(message); }
1537 else if (message.type === MessageType.editorConsoleSnapshot)
1538 { applyConsoleSnapshot(message.lines); }
1539 else if (message.type === MessageType.editorConsoleLine)
1540 { appendConsoleLine(message.line); }
1541 else if (message.type === MessageType.editorDimensions)
1542 {
1543 applyDimensionsList(message);
1544 }
1545 else if (message.type === MessageType.editorQuests)
1546 {
1547 questsModal?.handleMessage(message);
1548 settingsModal?.handleMessage(message);
1549 dialoguesModal?.handleMessage(message);
1550 tileConfigModal?.handleMessage(message);
1551 }
1552 else if (message.type === MessageType.editorDialogues)
1553 {
1554 dialoguesModal?.handleMessage(message);
1555 tileConfigModal?.handleMessage(message);
1556 questsModal?.handleMessage(message);
1557 }
1558 else if (message.type === MessageType.editorGiftCharacters
1559 || message.type === MessageType.editorGiftSent)
1560 { giftsModal?.handleMessage(message); }
1561 else if (message.type === MessageType.editorGlobalChangelog)
1562 { renderGlobalChangelog(message.changelog ?? []); }
1563 else if (message.type === MessageType.editorChunk)
1564 {
1565 const msgDim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
1566 if (msgDim !== selectedDimensionId)
1567 { return; }
1568 if (message.settings)
1569 { view.setSettings(message.settings); }
1570 if (!inEditorView(message.chunkX, message.chunkY))
1571 { return; }
1572 if (message.chunkX === chunkX && message.chunkY === chunkY)
1573 { showSelectedChunk(message); }
1574 else
1575 {
1576 const key = chunkKey(message.chunkX, message.chunkY);
1577 neighborSpawnersByChunk.set(key, message.data.spawners ?? []);
1578 if (!dirtyNeighborChunks.has(key))
1579 {
1580 view.applySnapshot(snapshotFromPayload(message));
1581 syncSpawnersOverlay(message.chunkX, message.chunkY, message.data.spawners);
1582 }
1583 }
1584 pruneView();
1585 }
1586 else if (message.type === MessageType.editorRevisionApplied)
1587 {
1588 applyInFlight = false;
1589 setRevisionState({
1590 activeRevisionId: message.activeRevisionId,
1591 pendingRevisionId: message.pendingRevisionId
1592 });
1593 const status = $("apply-status");
1594 status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`;
1595 status.className = "hint ok";
1596 requestDimensions();
1597 requestChunks(neighborhoodCoords(chunkX, chunkY));
1598 }
1599 else if (message.type === MessageType.forceLogout)
1600 {
1601 $("who").textContent = "Server restarting…";
1602 $("error").textContent = message.reason || "Server shutting down.";
1603 }
1604 else if (message.type === MessageType.error)
1605 {
1606 $("error").textContent = message.message;
1607 if (giftsModal?.isOpen())
1608 { giftsModal.handleError?.(message.message); }
1609 pendingCreatedDimensionId = null;
1610 navigateAfterSave = false;
1611 dimensionCombo?.setValue(selectedDimensionId);
1612 if (applyInFlight)
1613 {
1614 applyInFlight = false;
1615 $("apply-status").textContent = "";
1616 $("apply-status").className = "hint";
1617 updateRevisionUI();
1618 }
1619 }
1620 }, {
1621 onClose (event)
1622 {
1623 if (event.code === 1000)
1624 { return; }
1625 const reasons = {
1626 4401: "Sign in expired or missing. Use Sign out, then sign in again.",
1627 1011: "Server could not verify your account with auth.timfalken.com.",
1628 1006: "Connection dropped before the editor session started.",
1629 1001: "Server is restarting. Reload this page in a moment."
1630 };
1631 const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`;
1632 $("who").textContent = "Connection failed";
1633 $("error").textContent = detail;
1634 },
1635 onError ()
1636 {
1637 $("who").textContent = "Connection failed";
1638 $("error").textContent = "Could not open a live connection to the server.";
1639 }
1640 });
1641 settingsModal = initSettingsModal({
1642 socket,
1643 MessageType,
1644 getAuthSubject: () => sessionAuthSubject,
1645 onApplied (settings)
1646 {
1647 view.setSettings(settings);
1648 },
1649 onPreviewNight (hour)
1650 {
1651 view.nightPreview = hour;
1652 $("night").value = String(hour);
1653 $("night-label").textContent = Number(hour).toFixed(1);
1654 }
1655 });
1656 dimensionCombo = createDimensionCombobox({
1657 root: $("dimension-combo"),
1658 allowCreate: true,
1659 placeholder: "Search or create dimension…",
1660 onSelect (id)
1661 {
1662 selectDimension(id);
1663 },
1664 onCreate (rawId)
1665 {
1666 const id = normalizeDimensionId(rawId);
1667 $("error").textContent = "";
1668 pendingCreatedDimensionId = id;
1669 socket.send({
1670 type: MessageType.editorCreateDimension,
1671 dimensionId: id,
1672 displayName: rawId.trim()
1673 });
1674 }
1675 });
1676 dimensionCombo.setOptions([{
1677 id: OVERWORLD_ID,
1678 label: "Overworld"
1679 }]);
1680 dimensionCombo.setValue(OVERWORLD_ID);
1681 dimensionSettings = initDimensionSettings({
1682 socket,
1683 MessageType,
1684 GROUND_DEFINITIONS,
1685 OVERWORLD_ID,
1686 getSelectedDimensionId: () => selectedDimensionId,
1687 getDimensionRecord: (id) => dimensionsById.get(id) ?? null,
1688 isOverworld
1689 });
1690 questsModal = initQuestsModal({
1691 socket,
1692 MessageType,
1693 describeWorldTile,
1694 centerEditorOnTile,
1695 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
1696 id: dim.dimensionId,
1697 label: dim.displayName || dim.dimensionId,
1698 disabled: dim.deletedAt != null,
1699 hint: dim.deletedAt != null ? "soft-deleted" : null
1700 }))
1701 });
1702 dialoguesModal = initDialoguesModal({
1703 socket,
1704 MessageType,
1705 describeWorldTile,
1706 centerEditorOnTile,
1707 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
1708 id: dim.dimensionId,
1709 label: dim.displayName || dim.dimensionId,
1710 disabled: dim.deletedAt != null,
1711 hint: dim.deletedAt != null ? "soft-deleted" : null
1712 }))
1713 });
1714 giftsModal = initGiftsModal({ socket, MessageType });
1715 initSidePanelTabs();
1716 game.startGame();
1717 useNearestNeighbour(scene, game.images);
1718 await socket.connect();
1719}
1720
1721$("tool").textContent = selectedToolLabel();
1722$("tool-erase").addEventListener("click", () =>
1723{
1724 selectTool({ kind: "erase" });
1725 $("tool").textContent = selectedToolLabel();
1726});
1727
1728$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
1729$("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1));
1730$("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY));
1731$("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
1732$("copy-chunk")?.addEventListener("click", () => copySelectedChunk());
1733$("paste-chunk")?.addEventListener("click", () => pasteSelectedChunk());
1734$("clear-chunk")?.addEventListener("click", () => clearSelectedChunk());
1735
1736function isTypingTarget (target)
1737{
1738 if (!(target instanceof Element))
1739 { return false; }
1740 const tag = target.tagName;
1741 if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT")
1742 { return true; }
1743 return !!target.closest("[contenteditable='true']");
1744}
1745
1746window.addEventListener("keydown", (event) =>
1747{
1748 if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey)
1749 { return; }
1750 if (anyModalOpen() || isTypingTarget(event.target))
1751 { return; }
1752 if (event.key === "ArrowUp")
1753 {
1754 event.preventDefault();
1755 loadNeighborhood(chunkX, chunkY - 1);
1756 }
1757 else if (event.key === "ArrowDown")
1758 {
1759 event.preventDefault();
1760 loadNeighborhood(chunkX, chunkY + 1);
1761 }
1762 else if (event.key === "ArrowLeft")
1763 {
1764 event.preventDefault();
1765 loadNeighborhood(chunkX - 1, chunkY);
1766 }
1767 else if (event.key === "ArrowRight")
1768 {
1769 event.preventDefault();
1770 loadNeighborhood(chunkX + 1, chunkY);
1771 }
1772});
1773$("open").addEventListener("change", () =>
1774{
1775 if (isSelectedDimensionSoftDeleted())
1776 {
1777 $("open").checked = !!draft?.open;
1778 return;
1779 }
1780 if (draft)
1781 {
1782 draft.open = $("open").checked;
1783 view.setChunkOpen(chunkX, chunkY, draft.open);
1784 afterDraftMutation();
1785 }
1786});
1787$("save").addEventListener("click", () =>
1788{
1789 saveSelectedChunk();
1790});
1791$("unsaved-chunk-cancel")?.addEventListener("click", () =>
1792{
1793 pendingNavigate = null;
1794 navigateAfterSave = false;
1795 hideUnsavedModal();
1796});
1797$("unsaved-chunk-backdrop")?.addEventListener("click", () =>
1798{
1799 pendingNavigate = null;
1800 navigateAfterSave = false;
1801 hideUnsavedModal();
1802});
1803$("unsaved-chunk-discard")?.addEventListener("click", () =>
1804{
1805 const next = pendingNavigate;
1806 hideUnsavedModal();
1807 pendingNavigate = null;
1808 navigateAfterSave = false;
1809 if (!next)
1810 { return; }
1811 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1812 if (nextDim !== selectedDimensionId)
1813 {
1814 selectedDimensionId = nextDim;
1815 syncDimensionUi();
1816 clearNeighborhoodView();
1817 }
1818 doLoadNeighborhood(next.chunkX, next.chunkY);
1819});
1820$("unsaved-chunk-save")?.addEventListener("click", () =>
1821{
1822 hideUnsavedModal();
1823 if (!pendingNavigate)
1824 { return; }
1825 navigateAfterSave = true;
1826 if (!saveSelectedChunk())
1827 {
1828 navigateAfterSave = false;
1829 const next = pendingNavigate;
1830 pendingNavigate = null;
1831 if (next)
1832 {
1833 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1834 if (nextDim !== selectedDimensionId)
1835 {
1836 selectedDimensionId = nextDim;
1837 syncDimensionUi();
1838 clearNeighborhoodView();
1839 }
1840 doLoadNeighborhood(next.chunkX, next.chunkY);
1841 }
1842 }
1843});
1844$("apply").addEventListener("click", () =>
1845{
1846 if (!pendingRevisionId || applyInFlight)
1847 { return; }
1848 $("error").textContent = "";
1849 const status = $("apply-status");
1850 status.textContent = "Applying…";
1851 status.className = "hint";
1852 applyInFlight = true;
1853 updateRevisionUI();
1854 socket.send({ type: MessageType.editorApplyRevision });
1855});
1856document.getElementById("editor-restart-now")?.addEventListener("click", () =>
1857{
1858 if (!socket)
1859 { return; }
1860 const ok = window.confirm(
1861 "Restart the server now?\n\nAll players and editor sessions will disconnect. "
1862 + "systemd will start a fresh process and pull the latest code from git."
1863 );
1864 if (!ok)
1865 { return; }
1866 const restartBtn = document.getElementById("editor-restart-now");
1867 if (restartBtn)
1868 { restartBtn.disabled = true; }
1869 $("who").textContent = "Restarting server…";
1870 $("error").textContent = "";
1871 socket.send({ type: MessageType.editorRestartNow });
1872});
1873$("night").addEventListener("input", () =>
1874{
1875 view.nightPreview = Number($("night").value);
1876 $("night-label").textContent = view.nightPreview.toFixed(1);
1877});
1878$("season").addEventListener("change", () =>
1879{
1880 applySeasonPreview($("season").value);
1881});
1882
1883function showGlobalChangelog (visible)
1884{
1885 const backdrop = $("global-changelog-backdrop");
1886 const modal = $("global-changelog-modal");
1887 if (backdrop)
1888 { backdrop.hidden = !visible; }
1889 if (modal)
1890 { modal.hidden = !visible; }
1891}
1892
1893function renderGlobalChangelog (changelog)
1894{
1895 const log = $("global-changelog");
1896 if (!log)
1897 { return; }
1898 log.innerHTML = "";
1899 if (!changelog.length)
1900 {
1901 log.innerHTML = "<p class=\"hint\">No edits logged yet.</p>";
1902 return;
1903 }
1904 const kindLabel = {
1905 chunk: "Chunk",
1906 settings: "Settings",
1907 quest: "Quest",
1908 dialogue: "Dialogue"
1909 };
1910 for (const entry of changelog)
1911 {
1912 const item = document.createElement("article");
1913 const who = entry.editorDisplayName || entry.editor_admin_id;
1914 const kind = kindLabel[entry.kind] || entry.kind || "Edit";
1915 const scope = entry.scope ? ` · ${entry.scope}` : "";
1916 item.innerHTML = `<header>${kind}${scope} · ${who} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
1917 const list = document.createElement("ul");
1918 for (const bullet of entry.diffEntries ?? [])
1919 {
1920 const li = document.createElement("li");
1921 li.textContent = bullet;
1922 list.append(li);
1923 }
1924 item.append(list);
1925 log.append(item);
1926 }
1927 log.scrollTop = 0;
1928}
1929
1930document.getElementById("open-global-changelog")?.addEventListener("click", () =>
1931{
1932 const log = $("global-changelog");
1933 if (log)
1934 { log.innerHTML = "<p class=\"hint\">Loading…</p>"; }
1935 showGlobalChangelog(true);
1936 socket.send({ type: MessageType.editorLoadGlobalChangelog });
1937});
1938document.getElementById("global-changelog-close")?.addEventListener("click", () => showGlobalChangelog(false));
1939document.getElementById("global-changelog-backdrop")?.addEventListener("click", () => showGlobalChangelog(false));
1940
1941function syncSeasonControls (season)
1942{
1943 const next = season === SeasonId.spring
1944 || season === SeasonId.fall
1945 || season === SeasonId.winter
1946 || season === SeasonId.summer
1947 ? season
1948 : seasonIdAt();
1949 $("season").value = next;
1950 view?.setWorldSeason(next);
1951}
1952
1953function applySeasonPreview (season)
1954{
1955 syncSeasonControls(season);
1956}
1957
1958function cycleToolState (direction)
1959{
1960 if (tool.kind === "erase" || tool.kind === "spawner")
1961 { return; }
1962 const layer = tool.kind === "ground" ? "ground" : "block";
1963 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
1964 if (definitionUsesNeighborConnect(def))
1965 { return; }
1966 if (tool.kind === "block" && def?.id === BlockType.flower)
1967 { return; }
1968 const allStates = statesForType(catalog, layer, def.key);
1969 const seasonal = seasonalCycleStates(allStates);
1970 const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
1971 if (states.length < 2)
1972 { return; }
1973 tool.state = cycleState(states, tool.state, direction);
1974 $("tool").textContent = selectedToolLabel();
1975 const season = seasonIdFromVisualState(tool.state);
1976 if (season)
1977 { applySeasonPreview(season); }
1978 if (!draft || !hoverLocal)
1979 { return; }
1980 const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;
1981 if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId)
1982 { paintAt(hoverLocal.x, hoverLocal.y); }
1983 else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId)
1984 { paintAt(hoverLocal.x, hoverLocal.y); }
1985}
1986
1987document.addEventListener("wheel", (event) =>
1988{
1989 if (!scene?.canvas || anyModalOpen())
1990 { return; }
1991 const rect = scene.canvas.getBoundingClientRect();
1992 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
1993 { return; }
1994 event.preventDefault();
1995 if (event.shiftKey)
1996 {
1997 cycleToolState(event.deltaY < 0 ? 1 : -1);
1998 if (hoverLocal)
1999 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
2000 return;
2001 }
2002 zoomEditor(event.deltaY < 0 ? 1 : -1);
2003}, { passive: false });
2004
2005document.addEventListener("contextmenu", (event) =>
2006{
2007 if (!scene?.canvas || anyModalOpen() || !draft)
2008 { return; }
2009 const rect = scene.canvas.getBoundingClientRect();
2010 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
2011 { return; }
2012 event.preventDefault();
2013 const tile = view.screenToTile(event.clientX - rect.left, event.clientY - rect.top);
2014 const localX = tile.tileX - chunkX * CHUNK_SIZE;
2015 const localY = tile.tileY - chunkY * CHUNK_SIZE;
2016 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
2017 { return; }
2018 const spawner = spawnerAt(localX, localY);
2019 if (spawner)
2020 {
2021 tileConfigModal.openSpawner({
2022 localX,
2023 localY,
2024 tileX: tile.tileX,
2025 tileY: tile.tileY,
2026 config: { ...spawner.config }
2027 });
2028 return;
2029 }
2030 const index = localY * CHUNK_SIZE + localX;
2031 const block = draft.blocks[index];
2032 if (block?.typeId === BlockType.doorway)
2033 {
2034 tileConfigModal.openDoorway({
2035 localX,
2036 localY,
2037 tileX: tile.tileX,
2038 tileY: tile.tileY,
2039 state: block.state ?? "door",
2040 config: block.config ? { ...block.config } : {}
2041 });
2042 return;
2043 }
2044 if (block?.typeId === BlockType.door)
2045 {
2046 tileConfigModal.openDoor({
2047 localX,
2048 localY,
2049 tileX: tile.tileX,
2050 tileY: tile.tileY,
2051 state: block.state,
2052 config: block.config ? { ...block.config } : {}
2053 });
2054 return;
2055 }
2056 if (block?.typeId === BlockType.fishingSpot)
2057 {
2058 tileConfigModal.openFishingSpot({
2059 localX,
2060 localY,
2061 tileX: tile.tileX,
2062 tileY: tile.tileY,
2063 config: block.config ? { ...block.config } : { fishes: [] }
2064 });
2065 }
2066});
2067
2068main().catch((error) =>
2069{
2070 $("error").textContent = error.message;
2071 console.error(error);
2072});