BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

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