BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

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