BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

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