BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

main.js 42.6 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 if (def?.id === BlockType.fishingSpot)
521 {
522 const groundType = draft.grounds[index]?.typeId;
523 if (groundType !== GroundType.water && groundType !== GroundType.deepWater)
524 { return; }
525 }
526 let nextState = definitionUsesNeighborConnect(def)
527 ? composeNeighborConnectState(def, state, 0)
528 : state;
529 if (def?.id === BlockType.flower)
530 { nextState = flowerBlockState(randomFlowerColorId()); }
531 if (def?.id === BlockType.fishingSpot && !nextState)
532 { nextState = "fishing-spot"; }
533 const config = def?.id === BlockType.doorway
534 ? {
535 targetDimensionId: selectedDimensionId,
536 tileX: chunkX * CHUNK_SIZE + localX,
537 tileY: chunkY * CHUNK_SIZE + localY
538 }
539 : (def?.id === BlockType.fishingSpot
540 ? { fishes: [] }
541 : null);
542 if (def?.id === BlockType.doorway && !nextState)
543 { nextState = "door"; }
544 draft.blocks[index] = { typeId: tool.typeId, state: nextState, config };
545 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
546 ground: draft.grounds[index],
547 block: draft.blocks[index],
548 light: draft.light[index]
549 });
550 if (definitionUsesNeighborConnect(def))
551 { refreshNeighborConnect(localX, localY, tool.typeId); }
552 afterDraftMutation();
553 return;
554 }
555 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
556 ground: draft.grounds[index],
557 block: draft.blocks[index],
558 light: draft.light[index]
559 });
560 afterDraftMutation();
561}
562
563/** Recompute neighbor-connect masks for a type around a local tile (same chunk). */
564function refreshNeighborConnect (localX, localY, typeId)
565{
566 const def = BLOCK_DEFINITIONS[typeId];
567 if (!draft || !definitionUsesNeighborConnect(def))
568 { return; }
569 const cells = [[localX, localY]];
570 for (const [dx, dy] of [[0, -1], [1, 0], [0, 1], [-1, 0]])
571 { cells.push([localX + dx, localY + dy]); }
572 for (const [lx, ly] of cells)
573 {
574 if (lx < 0 || ly < 0 || lx >= CHUNK_SIZE || ly >= CHUNK_SIZE)
575 { continue; }
576 const index = ly * CHUNK_SIZE + lx;
577 const block = draft.blocks[index];
578 if (!block || block.typeId !== typeId)
579 { continue; }
580 const mask = computeNeighborConnectMask((dx, dy) =>
581 {
582 const nx = lx + dx;
583 const ny = ly + dy;
584 if (nx < 0 || ny < 0 || nx >= CHUNK_SIZE || ny >= CHUNK_SIZE)
585 { return false; }
586 const neighbor = draft.blocks[ny * CHUNK_SIZE + nx];
587 return neighborConnectBlocksMatch(block, neighbor, def);
588 });
589 block.state = composeNeighborConnectState(def, block.state, mask);
590 view.updateAuthoredTile(chunkX, chunkY, lx, ly, {
591 ground: draft.grounds[index],
592 block: draft.blocks[index],
593 light: draft.light[index]
594 });
595 }
596}
597
598function updateRevisionUI ()
599{
600 const applyBtn = $("apply");
601 $("revision").textContent = `active ${activeRevisionId ?? "?"}` +
602 (pendingRevisionId ? ` · pending ${pendingRevisionId}` : " · no pending revision");
603 if (applyBtn)
604 {
605 applyBtn.disabled = !pendingRevisionId || applyInFlight;
606 applyBtn.title = pendingRevisionId
607 ? "Reload the live world with the pending map revision"
608 : "Save a chunk first to create a pending revision";
609 }
610}
611
612function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pending })
613{
614 if (active != null)
615 { activeRevisionId = active; }
616 pendingRevisionId = pending ?? null;
617 updateRevisionUI();
618}
619
620function showSelectedChunk (payload)
621{
622 draft = {
623 open: payload.data.open,
624 grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
625 blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)),
626 light: payload.data.light.slice(),
627 spawners: (payload.data.spawners ?? []).map((entry) => ({
628 localX: entry.localX,
629 localY: entry.localY,
630 config: { ...entry.config }
631 }))
632 };
633 $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`;
634 $("open").checked = draft.open;
635 setRevisionState({
636 activeRevisionId: payload.activeRevisionId,
637 pendingRevisionId: payload.pendingRevisionId
638 });
639 $("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)";
640 const log = $("changelog");
641 log.innerHTML = "";
642 for (const entry of payload.changelog ?? [])
643 {
644 const item = document.createElement("article");
645 item.innerHTML = `<header>${entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
646 const list = document.createElement("ul");
647 for (const bullet of entry.diffEntries)
648 {
649 const li = document.createElement("li");
650 li.textContent = bullet;
651 list.append(li);
652 }
653 item.append(list);
654 log.append(item);
655 }
656 view.applySnapshot(snapshotFromPayload(payload));
657 syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);
658 captureDraftBaseline();
659 if (navigateAfterSave && pendingNavigate)
660 {
661 const next = pendingNavigate;
662 navigateAfterSave = false;
663 pendingNavigate = null;
664 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
665 if (nextDim !== selectedDimensionId)
666 {
667 selectedDimensionId = nextDim;
668 syncDimensionUi();
669 clearNeighborhoodView();
670 }
671 doLoadNeighborhood(next.chunkX, next.chunkY);
672 }
673}
674
675function pruneView ()
676{
677 for (const key of [...view.chunks.keys()])
678 {
679 const [x, y] = key.split(",").map(Number);
680 if (!inEditorView(x, y))
681 { view.removeChunk(x, y); }
682 }
683}
684
685function frameNeighborhood ()
686{
687 const size = view.tileSize();
688 view.followPlayer = false;
689 const centerX = (chunkX + 0.5) * CHUNK_SIZE * size;
690 const centerY = (chunkY + 0.5) * CHUNK_SIZE * size;
691 view.scene.cameraPosition.x = view.scene.real_size.x / 2 - centerX;
692 view.scene.cameraPosition.y = view.scene.real_size.y / 2 - centerY;
693 updateSelectionBorder();
694}
695
696function updateSelectionBorder ()
697{
698 const border = $("selection-border");
699 const canvas = scene?.canvas;
700 if (!border || !canvas)
701 { return; }
702
703 const rect = canvas.getBoundingClientRect();
704 const size = view.tileSize();
705 const chunkPx = CHUNK_SIZE * size;
706 const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x;
707 const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y;
708 border.style.left = `${rect.left + screenLeft}px`;
709 border.style.top = `${rect.top + screenTop}px`;
710 border.style.width = `${chunkPx}px`;
711 border.style.height = `${chunkPx}px`;
712}
713
714function layoutScene ()
715{
716 const header = document.querySelector("body > header");
717 const aside = document.querySelector("body > aside");
718 const sidePanels = $("side-panels") || $("changelog-wrap");
719 const top = header.offsetHeight;
720 aside.style.top = `${top}px`;
721 sidePanels.style.top = `${top}px`;
722 const left = aside.offsetWidth;
723 const right = sidePanels.offsetWidth;
724 const width = Math.max(64, window.innerWidth - left - right);
725 const height = Math.max(64, window.innerHeight - top);
726 scene.position.x = left;
727 scene.position.y = top;
728 scene.size.x = width;
729 scene.size.y = height;
730 scene.g_fixSize();
731 useNearestNeighbour(scene, game.images);
732 const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX);
733 if (editorZoom == null)
734 { editorZoom = fit; }
735 else
736 { editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, editorZoom)); }
737 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
738 frameNeighborhood();
739}
740
741function zoomEditor (direction)
742{
743 if (!view)
744 { return; }
745 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
746 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
747 scheduleEditorZoom();
748}
749
750let editorZoomRaf = 0;
751function scheduleEditorZoom ()
752{
753 if (editorZoomRaf)
754 { return; }
755 editorZoomRaf = requestAnimationFrame(() =>
756 {
757 editorZoomRaf = 0;
758 if (!view)
759 { return; }
760 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
761 frameNeighborhood();
762 });
763}
764
765function requestChunks (coords)
766{
767 if (!socket?.socket || socket.socket.readyState !== WebSocket.OPEN)
768 { return; }
769 for (const coord of coords)
770 {
771 try
772 {
773 socket.send({
774 type: MessageType.editorLoadChunk,
775 chunkX: coord.chunkX,
776 chunkY: coord.chunkY,
777 dimensionId: selectedDimensionId
778 });
779 }
780 catch (_)
781 { break; }
782 }
783}
784
785function doLoadNeighborhood (x, y)
786{
787 chunkX = x;
788 chunkY = y;
789 $("coords").textContent = `${chunkX}, ${chunkY}`;
790 requestChunks(neighborhoodCoords(x, y));
791}
792
793function loadNeighborhood (x, y)
794{
795 if ((x !== chunkX || y !== chunkY) && isDraftDirty())
796 {
797 showUnsavedModal({ chunkX: x, chunkY: y, dimensionId: selectedDimensionId });
798 return;
799 }
800 doLoadNeighborhood(x, y);
801}
802
803function requestNeighbors ()
804{
805 requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
806}
807
808function anyModalOpen ()
809{
810 return settingsModal?.isOpen()
811 || paletteModal?.isOpen()
812 || tileConfigModal?.isOpen()
813 || questsModal?.isOpen()
814 || dialoguesModal?.isOpen()
815 || !$("unsaved-chunk-modal")?.hidden;
816}
817
818function updateHoverStatus (local)
819{
820 const el = $("hover-status-text");
821 if (!el)
822 { return; }
823 if (!local)
824 {
825 el.textContent = "Hover a tile for coordinates";
826 return;
827 }
828 const hoverChunkX = local.chunkX ?? Math.floor(local.tileX / CHUNK_SIZE);
829 const hoverChunkY = local.chunkY ?? Math.floor(local.tileY / CHUNK_SIZE);
830 el.textContent = `Tile (${local.tileX}, ${local.tileY}) · Chunk (${hoverChunkX}, ${hoverChunkY})`;
831}
832
833function updateTooltip (local, options = {})
834{
835 if (!options.keepStatus)
836 { updateHoverStatus(local); }
837 const tip = $("tile-tooltip");
838 if (!tip || !local || !draft)
839 {
840 if (tip)
841 { tip.hidden = true; }
842 view?.clearSpawnRangeHighlight();
843 return;
844 }
845 const block = normalizeBlock(draft.blocks[local.y * CHUNK_SIZE + local.x]);
846 const spawner = spawnerAt(local.x, local.y);
847 const lines = [];
848 if (block)
849 {
850 const def = BLOCK_DEFINITIONS[block.typeId];
851 lines.push(def?.displayName ?? `Block ${block.typeId}`);
852 if (block.config && Object.keys(block.config).length)
853 {
854 for (const [key, value] of Object.entries(block.config))
855 { lines.push(`${key}: ${value}`); }
856 }
857 }
858 if (spawner)
859 {
860 const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId);
861 const mob = mobDefinition(config.mobTypeId);
862 lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`);
863 lines.push(`maxAlive: ${config.maxAlive}`);
864 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
865 lines.push(`wanderRange: ${config.maxWanderRangeTiles}`);
866 lines.push(`id: ${config.spawnerId}`);
867 view.setSpawnRangeHighlight(
868 local.tileX,
869 local.tileY,
870 config.spawnRangeTiles,
871 config.maxWanderRangeTiles
872 );
873 }
874 else
875 { view.clearSpawnRangeHighlight(); }
876 if (!lines.length)
877 {
878 tip.hidden = true;
879 return;
880 }
881 tip.hidden = false;
882 tip.textContent = lines.join("\n");
883 const canvas = scene.canvas;
884 const rect = canvas.getBoundingClientRect();
885 const size = view.tileSize();
886 const screenX = local.tileX * size + scene.cameraPosition.x + rect.left + size;
887 const screenY = local.tileY * size + scene.cameraPosition.y + rect.top;
888 tip.style.left = `${screenX}px`;
889 tip.style.top = `${screenY}px`;
890}
891
892async function main ()
893{
894 const authStatus = await fetchAuthStatus();
895 const signIn = document.getElementById("auth-sign-in");
896 const signOut = document.getElementById("auth-sign-out");
897 if (signIn)
898 {
899 signIn.hidden = !!authStatus?.authenticated;
900 signIn.href = loginUrl("/editor");
901 }
902 if (signOut)
903 {
904 signOut.hidden = !authStatus?.authenticated;
905 signOut.href = logoutUrl("/editor");
906 }
907 if (!authStatus.authenticated)
908 {
909 $("who").textContent = "Sign in required";
910 $("error").textContent = "Sign in with your Tim Falken account to use the world editor.";
911 return;
912 }
913
914 const accountLabel = authStatus.username ?? authStatus.email ?? authStatus.authSubject ?? "Signed in";
915 $("who").textContent = `${accountLabel} · loading sprites…`;
916
917 catalog = await loadSpriteCatalog();
918 imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));
919 await preloadCatalogImages(game, catalog, {
920 onProgress ({ loaded, total })
921 {
922 $("who").textContent = `${accountLabel} · loading sprites ${loaded}/${total}`;
923 }
924 });
925 applySpriteSheets(game.images, catalog);
926 scene = new Scene(250, 56, 64, 64);
927 game.loadScene(scene);
928 view = new WorldView(game, scene, catalog);
929 view.followPlayer = false;
930 view.setGraphicsPrefs(loadGraphicsSettings());
931 syncSeasonControls(view.worldSeason ?? seasonIdAt());
932 layoutScene();
933 selectTool(tool);
934 $("tool").textContent = selectedToolLabel();
935
936 paletteModal = initPaletteModal({
937 catalog,
938 imageUrlFor (name)
939 {
940 const sprite = game.images[name];
941 const html = sprite?.g_image;
942 if (html && typeof html.toDataURL === "function")
943 {
944 try
945 { return html.toDataURL("image/png"); }
946 catch (_)
947 { /* fall through */ }
948 }
949 return imageUrlByName.get(name) ?? null;
950 },
951 onSelect (next)
952 {
953 selectTool(next);
954 $("tool").textContent = selectedToolLabel();
955 }
956 });
957
958 tileConfigModal = initTileConfigModal({
959 socket: {
960 send (payload)
961 {
962 socket?.send(payload);
963 }
964 },
965 MessageType,
966 getDialogues: () => dialoguesModal?.getDialogues?.() ?? [],
967 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
968 id: dim.dimensionId,
969 label: dim.displayName || dim.dimensionId,
970 disabled: !!dim.deletedAt,
971 hint: dim.deletedAt ? "soft-deleted" : undefined
972 })),
973 onSave (ctx, config)
974 {
975 if (!draft)
976 { return; }
977 if (ctx.kind === "doorway")
978 {
979 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
980 draft.blocks[index] = {
981 typeId: BlockType.doorway,
982 state: config.state || "door",
983 config: {
984 targetDimensionId: normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID),
985 tileX: Number(config.tileX) || 0,
986 tileY: Number(config.tileY) || 0
987 }
988 };
989 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
990 ground: draft.grounds[index],
991 block: draft.blocks[index],
992 light: draft.light[index]
993 });
994 afterDraftMutation();
995 return;
996 }
997 if (ctx.kind === "fishing-spot")
998 {
999 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1000 const existing = draft.blocks[index];
1001 draft.blocks[index] = {
1002 typeId: BlockType.fishingSpot,
1003 state: existing?.state === "exhausted" ? "exhausted" : "fishing-spot",
1004 config: { fishes: [...(config.fishes ?? [])] }
1005 };
1006 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1007 ground: draft.grounds[index],
1008 block: draft.blocks[index],
1009 light: draft.light[index]
1010 });
1011 afterDraftMutation();
1012 return;
1013 }
1014 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1015 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
1016 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1017 afterDraftMutation();
1018 },
1019 onRemove (ctx)
1020 {
1021 if (!draft)
1022 { return; }
1023 if (ctx.kind === "doorway")
1024 {
1025 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1026 draft.blocks[index] = null;
1027 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1028 ground: draft.grounds[index],
1029 block: draft.blocks[index],
1030 light: draft.light[index]
1031 });
1032 afterDraftMutation();
1033 return;
1034 }
1035 if (ctx.kind === "fishing-spot")
1036 {
1037 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1038 draft.blocks[index] = null;
1039 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1040 ground: draft.grounds[index],
1041 block: draft.blocks[index],
1042 light: draft.light[index]
1043 });
1044 afterDraftMutation();
1045 return;
1046 }
1047 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1048 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1049 afterDraftMutation();
1050 }
1051 });
1052
1053 const ticker = new GameObject(0, 0, null, 10);
1054 ticker.update = (dt) =>
1055 {
1056 hoverLocal = null;
1057 const canvas = scene.canvas;
1058 const rect = canvas.getBoundingClientRect();
1059 const mouseX = GameInput.mousePosition.x - rect.left;
1060 const mouseY = GameInput.mousePosition.y - rect.top;
1061 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
1062 if (overCanvas && draft && !anyModalOpen())
1063 {
1064 const tile = view.screenToTile(mouseX, mouseY);
1065 const localX = tile.tileX - chunkX * CHUNK_SIZE;
1066 const localY = tile.tileY - chunkY * CHUNK_SIZE;
1067 const hoverChunkX = Math.floor(tile.tileX / CHUNK_SIZE);
1068 const hoverChunkY = Math.floor(tile.tileY / CHUNK_SIZE);
1069 updateHoverStatus({
1070 tileX: tile.tileX,
1071 tileY: tile.tileY,
1072 x: ((tile.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1073 y: ((tile.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1074 chunkX: hoverChunkX,
1075 chunkY: hoverChunkY
1076 });
1077 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
1078 {
1079 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
1080 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
1081 updateTooltip(hoverLocal);
1082 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
1083 { paintAt(localX, localY); }
1084 }
1085 else
1086 {
1087 hoverLocal = null;
1088 view.clearTilePreview();
1089 updateTooltip(null, { keepStatus: true });
1090 }
1091 }
1092 else
1093 {
1094 view.clearTilePreview();
1095 updateTooltip(null);
1096 }
1097 view.update(dt);
1098 frameNeighborhood();
1099 };
1100 scene.addObject(ticker);
1101 window.addEventListener("resize", layoutScene);
1102
1103 $("who").textContent = `${accountLabel} · connecting…`;
1104
1105 socket = new GameSocket(defaultSocketUrl(), (message) =>
1106 {
1107 if (message.type === MessageType.session)
1108 {
1109 sessionAuthSubject = message.authSubject ?? null;
1110 const label = message.username ?? message.authSubject ?? "Unknown";
1111 $("who").textContent = `${label}${message.isAdmin ? " · admin" : " · not admin"}`;
1112 if (!message.isAdmin)
1113 {
1114 $("error").textContent = "Admin access required.";
1115 return;
1116 }
1117 $("error").textContent = "";
1118 const restartBtn = document.getElementById("editor-restart-now");
1119 if (restartBtn)
1120 {
1121 restartBtn.hidden = false;
1122 restartBtn.disabled = false;
1123 }
1124 socket.send({ type: MessageType.editorLoadSettings });
1125 socket.send({ type: MessageType.editorLoadGameAdmins });
1126 socket.send({ type: MessageType.editorConsoleSubscribe });
1127 requestDimensions();
1128 loadNeighborhood(0, 0);
1129 }
1130 else if (message.type === MessageType.editorSettings
1131 || message.type === MessageType.editorGameAdmins)
1132 { settingsModal.handleMessage(message); }
1133 else if (message.type === MessageType.editorConsoleSnapshot)
1134 { applyConsoleSnapshot(message.lines); }
1135 else if (message.type === MessageType.editorConsoleLine)
1136 { appendConsoleLine(message.line); }
1137 else if (message.type === MessageType.editorDimensions)
1138 {
1139 applyDimensionsList(message);
1140 }
1141 else if (message.type === MessageType.editorQuests)
1142 { questsModal?.handleMessage(message); }
1143 else if (message.type === MessageType.editorDialogues)
1144 {
1145 dialoguesModal?.handleMessage(message);
1146 tileConfigModal?.handleMessage(message);
1147 }
1148 else if (message.type === MessageType.editorChunk)
1149 {
1150 const msgDim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
1151 if (msgDim !== selectedDimensionId)
1152 { return; }
1153 if (message.settings)
1154 { view.setSettings(message.settings); }
1155 if (!inEditorView(message.chunkX, message.chunkY))
1156 { return; }
1157 if (message.chunkX === chunkX && message.chunkY === chunkY)
1158 { showSelectedChunk(message); }
1159 else
1160 {
1161 view.applySnapshot(snapshotFromPayload(message));
1162 syncSpawnersOverlay(message.chunkX, message.chunkY, message.data.spawners);
1163 }
1164 pruneView();
1165 }
1166 else if (message.type === MessageType.editorRevisionApplied)
1167 {
1168 applyInFlight = false;
1169 setRevisionState({
1170 activeRevisionId: message.activeRevisionId,
1171 pendingRevisionId: message.pendingRevisionId
1172 });
1173 const status = $("apply-status");
1174 status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`;
1175 status.className = "hint ok";
1176 requestDimensions();
1177 requestChunks(neighborhoodCoords(chunkX, chunkY));
1178 }
1179 else if (message.type === MessageType.forceLogout)
1180 {
1181 $("who").textContent = "Server restarting…";
1182 $("error").textContent = message.reason || "Server shutting down.";
1183 }
1184 else if (message.type === MessageType.error)
1185 {
1186 $("error").textContent = message.message;
1187 pendingCreatedDimensionId = null;
1188 navigateAfterSave = false;
1189 dimensionCombo?.setValue(selectedDimensionId);
1190 if (applyInFlight)
1191 {
1192 applyInFlight = false;
1193 $("apply-status").textContent = "";
1194 $("apply-status").className = "hint";
1195 updateRevisionUI();
1196 }
1197 }
1198 }, {
1199 onClose (event)
1200 {
1201 if (event.code === 1000)
1202 { return; }
1203 const reasons = {
1204 4401: "Sign in expired or missing. Use Sign out, then sign in again.",
1205 1011: "Server could not verify your account with auth.timfalken.com.",
1206 1006: "Connection dropped before the editor session started.",
1207 1001: "Server is restarting. Reload this page in a moment."
1208 };
1209 const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`;
1210 $("who").textContent = "Connection failed";
1211 $("error").textContent = detail;
1212 },
1213 onError ()
1214 {
1215 $("who").textContent = "Connection failed";
1216 $("error").textContent = "Could not open a live connection to the server.";
1217 }
1218 });
1219 settingsModal = initSettingsModal({
1220 socket,
1221 MessageType,
1222 getAuthSubject: () => sessionAuthSubject,
1223 onApplied (settings)
1224 {
1225 view.setSettings(settings);
1226 },
1227 onPreviewNight (hour)
1228 {
1229 view.nightPreview = hour;
1230 $("night").value = String(hour);
1231 $("night-label").textContent = Number(hour).toFixed(1);
1232 }
1233 });
1234 dimensionCombo = createDimensionCombobox({
1235 root: $("dimension-combo"),
1236 allowCreate: true,
1237 placeholder: "Search or create dimension…",
1238 onSelect (id)
1239 {
1240 selectDimension(id);
1241 },
1242 onCreate (rawId)
1243 {
1244 const id = normalizeDimensionId(rawId);
1245 $("error").textContent = "";
1246 pendingCreatedDimensionId = id;
1247 socket.send({
1248 type: MessageType.editorCreateDimension,
1249 dimensionId: id,
1250 displayName: rawId.trim()
1251 });
1252 }
1253 });
1254 dimensionCombo.setOptions([{
1255 id: OVERWORLD_ID,
1256 label: "Overworld"
1257 }]);
1258 dimensionCombo.setValue(OVERWORLD_ID);
1259 dimensionSettings = initDimensionSettings({
1260 socket,
1261 MessageType,
1262 GROUND_DEFINITIONS,
1263 OVERWORLD_ID,
1264 getSelectedDimensionId: () => selectedDimensionId,
1265 getDimensionRecord: (id) => dimensionsById.get(id) ?? null,
1266 isOverworld
1267 });
1268 questsModal = initQuestsModal({ socket, MessageType });
1269 dialoguesModal = initDialoguesModal({ socket, MessageType });
1270 initSidePanelTabs();
1271 game.startGame();
1272 useNearestNeighbour(scene, game.images);
1273 await socket.connect();
1274}
1275
1276$("tool").textContent = selectedToolLabel();
1277$("tool-erase").addEventListener("click", () =>
1278{
1279 selectTool({ kind: "erase" });
1280 $("tool").textContent = selectedToolLabel();
1281});
1282
1283$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
1284$("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1));
1285$("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY));
1286$("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
1287$("open").addEventListener("change", () =>
1288{
1289 if (isSelectedDimensionSoftDeleted())
1290 {
1291 $("open").checked = !!draft?.open;
1292 return;
1293 }
1294 if (draft)
1295 {
1296 draft.open = $("open").checked;
1297 view.setChunkOpen(chunkX, chunkY, draft.open);
1298 afterDraftMutation();
1299 }
1300});
1301$("save").addEventListener("click", () =>
1302{
1303 saveSelectedChunk();
1304});
1305$("unsaved-chunk-cancel")?.addEventListener("click", () =>
1306{
1307 pendingNavigate = null;
1308 navigateAfterSave = false;
1309 hideUnsavedModal();
1310});
1311$("unsaved-chunk-backdrop")?.addEventListener("click", () =>
1312{
1313 pendingNavigate = null;
1314 navigateAfterSave = false;
1315 hideUnsavedModal();
1316});
1317$("unsaved-chunk-discard")?.addEventListener("click", () =>
1318{
1319 const next = pendingNavigate;
1320 hideUnsavedModal();
1321 pendingNavigate = null;
1322 navigateAfterSave = false;
1323 if (!next)
1324 { return; }
1325 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1326 if (nextDim !== selectedDimensionId)
1327 {
1328 selectedDimensionId = nextDim;
1329 syncDimensionUi();
1330 clearNeighborhoodView();
1331 }
1332 doLoadNeighborhood(next.chunkX, next.chunkY);
1333});
1334$("unsaved-chunk-save")?.addEventListener("click", () =>
1335{
1336 hideUnsavedModal();
1337 if (!pendingNavigate)
1338 { return; }
1339 navigateAfterSave = true;
1340 if (!saveSelectedChunk())
1341 {
1342 navigateAfterSave = false;
1343 const next = pendingNavigate;
1344 pendingNavigate = null;
1345 if (next)
1346 {
1347 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1348 if (nextDim !== selectedDimensionId)
1349 {
1350 selectedDimensionId = nextDim;
1351 syncDimensionUi();
1352 clearNeighborhoodView();
1353 }
1354 doLoadNeighborhood(next.chunkX, next.chunkY);
1355 }
1356 }
1357});
1358$("apply").addEventListener("click", () =>
1359{
1360 if (!pendingRevisionId || applyInFlight)
1361 { return; }
1362 $("error").textContent = "";
1363 const status = $("apply-status");
1364 status.textContent = "Applying…";
1365 status.className = "hint";
1366 applyInFlight = true;
1367 updateRevisionUI();
1368 socket.send({ type: MessageType.editorApplyRevision });
1369});
1370document.getElementById("editor-restart-now")?.addEventListener("click", () =>
1371{
1372 if (!socket)
1373 { return; }
1374 const ok = window.confirm(
1375 "Restart the server now?\n\nAll players and editor sessions will disconnect. "
1376 + "systemd will start a fresh process and pull the latest code from git."
1377 );
1378 if (!ok)
1379 { return; }
1380 const restartBtn = document.getElementById("editor-restart-now");
1381 if (restartBtn)
1382 { restartBtn.disabled = true; }
1383 $("who").textContent = "Restarting server…";
1384 $("error").textContent = "";
1385 socket.send({ type: MessageType.editorRestartNow });
1386});
1387$("night").addEventListener("input", () =>
1388{
1389 view.nightPreview = Number($("night").value);
1390 $("night-label").textContent = view.nightPreview.toFixed(1);
1391});
1392$("season").addEventListener("change", () =>
1393{
1394 applySeasonPreview($("season").value);
1395});
1396
1397function syncSeasonControls (season)
1398{
1399 const next = season === SeasonId.spring
1400 || season === SeasonId.fall
1401 || season === SeasonId.winter
1402 || season === SeasonId.summer
1403 ? season
1404 : seasonIdAt();
1405 $("season").value = next;
1406 view?.setWorldSeason(next);
1407}
1408
1409function applySeasonPreview (season)
1410{
1411 syncSeasonControls(season);
1412}
1413
1414function cycleToolState (direction)
1415{
1416 if (tool.kind === "erase" || tool.kind === "spawner")
1417 { return; }
1418 const layer = tool.kind === "ground" ? "ground" : "block";
1419 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
1420 if (definitionUsesNeighborConnect(def))
1421 { return; }
1422 if (tool.kind === "block" && def?.id === BlockType.flower)
1423 { return; }
1424 const allStates = statesForType(catalog, layer, def.key);
1425 const seasonal = seasonalCycleStates(allStates);
1426 const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
1427 if (states.length < 2)
1428 { return; }
1429 tool.state = cycleState(states, tool.state, direction);
1430 $("tool").textContent = selectedToolLabel();
1431 const season = seasonIdFromVisualState(tool.state);
1432 if (season)
1433 { applySeasonPreview(season); }
1434 if (!draft || !hoverLocal)
1435 { return; }
1436 const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;
1437 if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId)
1438 { paintAt(hoverLocal.x, hoverLocal.y); }
1439 else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId)
1440 { paintAt(hoverLocal.x, hoverLocal.y); }
1441}
1442
1443document.addEventListener("wheel", (event) =>
1444{
1445 if (!scene?.canvas || anyModalOpen())
1446 { return; }
1447 const rect = scene.canvas.getBoundingClientRect();
1448 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
1449 { return; }
1450 event.preventDefault();
1451 if (event.shiftKey)
1452 {
1453 cycleToolState(event.deltaY < 0 ? 1 : -1);
1454 if (hoverLocal)
1455 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
1456 return;
1457 }
1458 zoomEditor(event.deltaY < 0 ? 1 : -1);
1459}, { passive: false });
1460
1461document.addEventListener("contextmenu", (event) =>
1462{
1463 if (!scene?.canvas || anyModalOpen() || !draft)
1464 { return; }
1465 const rect = scene.canvas.getBoundingClientRect();
1466 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
1467 { return; }
1468 event.preventDefault();
1469 const tile = view.screenToTile(event.clientX - rect.left, event.clientY - rect.top);
1470 const localX = tile.tileX - chunkX * CHUNK_SIZE;
1471 const localY = tile.tileY - chunkY * CHUNK_SIZE;
1472 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
1473 { return; }
1474 const spawner = spawnerAt(localX, localY);
1475 if (spawner)
1476 {
1477 tileConfigModal.openSpawner({
1478 localX,
1479 localY,
1480 tileX: tile.tileX,
1481 tileY: tile.tileY,
1482 config: { ...spawner.config }
1483 });
1484 return;
1485 }
1486 const index = localY * CHUNK_SIZE + localX;
1487 const block = draft.blocks[index];
1488 if (block?.typeId === BlockType.doorway)
1489 {
1490 tileConfigModal.openDoorway({
1491 localX,
1492 localY,
1493 tileX: tile.tileX,
1494 tileY: tile.tileY,
1495 state: block.state ?? "door",
1496 config: block.config ? { ...block.config } : {}
1497 });
1498 return;
1499 }
1500 if (block?.typeId === BlockType.fishingSpot)
1501 {
1502 tileConfigModal.openFishingSpot({
1503 localX,
1504 localY,
1505 tileX: tile.tileX,
1506 tileY: tile.tileY,
1507 config: block.config ? { ...block.config } : { fishes: [] }
1508 });
1509 }
1510});
1511
1512main().catch((error) =>
1513{
1514 $("error").textContent = error.message;
1515 console.error(error);
1516});