BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

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