BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

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