BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

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