BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

main.js 26.6 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 { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";
20import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
21import {
22 computeNeighborConnectMask,
23 composeNeighborConnectState,
24 definitionUsesNeighborConnect,
25 neighborConnectBlocksMatch
26} from "/shared/world/neighborConnect.js";
27import { GameSocket, defaultSocketUrl } from "../net/socket.js";
28import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
29import { WorldView } from "../render/worldView.js";
30import { initSettingsModal } from "./settingsModal.js";
31import { initPaletteModal } from "./paletteModal.js";
32import { initTileConfigModal } from "./tileConfigModal.js";
33
34const game = new Game();
35let socket;
36let scene;
37let view;
38let draft = null;
39/** @type {string|null} JSON snapshot of last loaded/saved draft (grounds/blocks/spawners/open). */
40let draftBaseline = null;
41/** @type {{ chunkX: number, chunkY: number }|null} */
42let pendingNavigate = null;
43/** When true, next matching editorChunk after save should navigate to pendingNavigate. */
44let navigateAfterSave = false;
45let chunkX = 0;
46let chunkY = 0;
47let tool = { kind: "ground", typeId: GroundType.grass, state: null };
48let settingsModal;
49let paletteModal;
50let tileConfigModal;
51let catalog = { grounds: {}, blocks: {}, images: [] };
52let imageUrlByName = new Map();
53let hoverLocal = null;
54let editorZoom = null;
55let activeRevisionId = null;
56let pendingRevisionId = null;
57let applyInFlight = false;
58const EDITOR_ZOOM_MIN = 0.25;
59const EDITOR_ZOOM_MAX = 8;
60const EDITOR_ZOOM_STEP = 1.12;
61
62function $ (id)
63{
64 return document.getElementById(id);
65}
66
67function selectedToolLabel ()
68{
69 if (tool.kind === "erase")
70 { return "Erase block"; }
71 if (tool.kind === "spawner")
72 {
73 const def = mobDefinition(tool.mobTypeId);
74 return `Spawner · ${def?.displayName ?? tool.mobTypeId}`;
75 }
76 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
77 const layer = tool.kind === "ground" ? "ground" : "block";
78 const states = statesForType(catalog, layer, def.key);
79 const state = resolveState(states, tool.state);
80 if (tool.kind === "block" && def.id === BlockType.flower)
81 { return "Flower"; }
82 if (tool.kind === "block" && def.id === BlockType.boulder)
83 {
84 const entry = listPlaceableBlockPaletteEntries(catalog)
85 .find((row) => row.typeId === def.id && row.state === state);
86 if (entry)
87 { return entry.displayName; }
88 }
89 if (states.length > 1)
90 { return `${def.displayName} (${state})`; }
91 return def.displayName;
92}
93
94function selectTool (next)
95{
96 if (next.kind === "erase")
97 {
98 tool = { kind: "erase" };
99 return;
100 }
101 if (next.kind === "spawner")
102 {
103 tool = { kind: "spawner", mobTypeId: next.mobTypeId };
104 return;
105 }
106 const layer = next.kind === "ground" ? "ground" : "block";
107 const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
108 tool = {
109 kind: next.kind,
110 typeId: next.typeId,
111 state: next.state ?? defaultStateForType(catalog, layer, def.key)
112 };
113}
114
115function placeableToolState ()
116{
117 if (tool.kind === "erase" || tool.kind === "spawner")
118 { return null; }
119 const layer = tool.kind === "ground" ? "ground" : "block";
120 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
121 return resolveState(statesForType(catalog, layer, def.key), tool.state);
122}
123
124function previewFromTool ()
125{
126 if (tool.kind === "erase")
127 { return { block: null }; }
128 if (tool.kind === "spawner")
129 { return {}; }
130 const state = placeableToolState();
131 if (tool.kind === "ground")
132 { return { ground: { typeId: tool.typeId, state } }; }
133 return { block: { typeId: tool.typeId, state, config: null } };
134}
135
136function inEditorView (x, y)
137{
138 return Math.abs(x - chunkX) <= VISIBLE_CHUNK_RADIUS && Math.abs(y - chunkY) <= VISIBLE_CHUNK_RADIUS;
139}
140
141function neighborhoodCoords (centerX, centerY)
142{
143 const coords = [];
144 for (let dy = -VISIBLE_CHUNK_RADIUS; dy <= VISIBLE_CHUNK_RADIUS; dy++)
145 {
146 for (let dx = -VISIBLE_CHUNK_RADIUS; dx <= VISIBLE_CHUNK_RADIUS; dx++)
147 { coords.push({ chunkX: centerX + dx, chunkY: centerY + dy }); }
148 }
149 return coords;
150}
151
152function snapshotFromPayload (payload)
153{
154 return {
155 chunkX: payload.chunkX,
156 chunkY: payload.chunkY,
157 open: payload.data.open,
158 closedEdges: payload.closedEdges,
159 grounds: payload.data.grounds,
160 blocks: payload.data.blocks,
161 light: payload.data.light,
162 entities: []
163 };
164}
165
166function syncSpawnersOverlay (cx, cy, spawners)
167{
168 view.setEditorSpawners(cx, cy, spawners ?? [], (mobTypeId) => mobSpriteName(mobTypeId));
169}
170
171function spawnerAt (localX, localY)
172{
173 return (draft?.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
174}
175
176function draftPersistable ()
177{
178 if (!draft)
179 { return null; }
180 return {
181 open: !!draft.open,
182 grounds: draft.grounds,
183 blocks: draft.blocks,
184 spawners: draft.spawners ?? []
185 };
186}
187
188function captureDraftBaseline ()
189{
190 const payload = draftPersistable();
191 draftBaseline = payload ? JSON.stringify(payload) : null;
192 syncSaveButton();
193}
194
195function isDraftDirty ()
196{
197 if (!draft || draftBaseline == null)
198 { return false; }
199 return JSON.stringify(draftPersistable()) !== draftBaseline;
200}
201
202function syncSaveButton ()
203{
204 const btn = $("save");
205 if (!btn)
206 { return; }
207 const dirty = isDraftDirty();
208 btn.disabled = !dirty;
209 btn.classList.toggle("save-dirty", dirty);
210 btn.title = dirty ? "Save unsaved chunk changes" : "No unsaved changes";
211}
212
213function afterDraftMutation ()
214{
215 syncSaveButton();
216}
217
218function showUnsavedModal (target)
219{
220 pendingNavigate = target;
221 $("unsaved-chunk-backdrop").hidden = false;
222 $("unsaved-chunk-modal").hidden = false;
223}
224
225function hideUnsavedModal ()
226{
227 $("unsaved-chunk-backdrop").hidden = true;
228 $("unsaved-chunk-modal").hidden = true;
229}
230
231function saveSelectedChunk ()
232{
233 if (!draft || !isDraftDirty())
234 { return false; }
235 $("error").textContent = "";
236 $("apply-status").textContent = "";
237 $("apply-status").className = "hint";
238 socket.send({
239 type: MessageType.editorSaveChunk,
240 chunkX,
241 chunkY,
242 draft: {
243 open: $("open").checked,
244 grounds: draft.grounds,
245 blocks: draft.blocks,
246 spawners: draft.spawners ?? []
247 }
248 });
249 requestNeighbors();
250 return true;
251}
252
253function paintAt (localX, localY)
254{
255 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
256 { return; }
257 const index = localY * CHUNK_SIZE + localX;
258 const state = placeableToolState();
259 if (tool.kind === "ground")
260 { draft.grounds[index] = { typeId: tool.typeId, state }; }
261 else if (tool.kind === "erase")
262 {
263 const removed = draft.blocks[index];
264 draft.blocks[index] = null;
265 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
266 ground: draft.grounds[index],
267 block: draft.blocks[index],
268 light: draft.light[index]
269 });
270 if (removed && definitionUsesNeighborConnect(BLOCK_DEFINITIONS[removed.typeId]))
271 { refreshNeighborConnect(localX, localY, removed.typeId); }
272 afterDraftMutation();
273 return;
274 }
275 else if (tool.kind === "spawner")
276 {
277 const existing = spawnerAt(localX, localY);
278 const spawnerId = existing?.config?.spawnerId ?? `${chunkX}:${chunkY}:${index}`;
279 const entry = {
280 localX,
281 localY,
282 config: normalizeSpawnerConfig({
283 ...defaultSpawnerConfig(spawnerId, tool.mobTypeId),
284 ...(existing?.config ?? {}),
285 spawnerId,
286 mobTypeId: tool.mobTypeId
287 }, spawnerId)
288 };
289 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY);
290 draft.spawners.push(entry);
291 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
292 afterDraftMutation();
293 return;
294 }
295 else
296 {
297 const def = BLOCK_DEFINITIONS[tool.typeId];
298 let nextState = definitionUsesNeighborConnect(def)
299 ? composeNeighborConnectState(def, state, 0)
300 : state;
301 if (def?.id === BlockType.flower)
302 { nextState = flowerBlockState(randomFlowerColorId()); }
303 draft.blocks[index] = { typeId: tool.typeId, state: nextState, config: null };
304 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
305 ground: draft.grounds[index],
306 block: draft.blocks[index],
307 light: draft.light[index]
308 });
309 if (definitionUsesNeighborConnect(def))
310 { refreshNeighborConnect(localX, localY, tool.typeId); }
311 afterDraftMutation();
312 return;
313 }
314 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
315 ground: draft.grounds[index],
316 block: draft.blocks[index],
317 light: draft.light[index]
318 });
319 afterDraftMutation();
320}
321
322/** Recompute neighbor-connect masks for a type around a local tile (same chunk). */
323function refreshNeighborConnect (localX, localY, typeId)
324{
325 const def = BLOCK_DEFINITIONS[typeId];
326 if (!draft || !definitionUsesNeighborConnect(def))
327 { return; }
328 const cells = [[localX, localY]];
329 for (const [dx, dy] of [[0, -1], [1, 0], [0, 1], [-1, 0]])
330 { cells.push([localX + dx, localY + dy]); }
331 for (const [lx, ly] of cells)
332 {
333 if (lx < 0 || ly < 0 || lx >= CHUNK_SIZE || ly >= CHUNK_SIZE)
334 { continue; }
335 const index = ly * CHUNK_SIZE + lx;
336 const block = draft.blocks[index];
337 if (!block || block.typeId !== typeId)
338 { continue; }
339 const mask = computeNeighborConnectMask((dx, dy) =>
340 {
341 const nx = lx + dx;
342 const ny = ly + dy;
343 if (nx < 0 || ny < 0 || nx >= CHUNK_SIZE || ny >= CHUNK_SIZE)
344 { return false; }
345 const neighbor = draft.blocks[ny * CHUNK_SIZE + nx];
346 return neighborConnectBlocksMatch(block, neighbor, def);
347 });
348 block.state = composeNeighborConnectState(def, block.state, mask);
349 view.updateAuthoredTile(chunkX, chunkY, lx, ly, {
350 ground: draft.grounds[index],
351 block: draft.blocks[index],
352 light: draft.light[index]
353 });
354 }
355}
356
357function updateRevisionUI ()
358{
359 const applyBtn = $("apply");
360 $("revision").textContent = `active ${activeRevisionId ?? "?"}` +
361 (pendingRevisionId ? ` · pending ${pendingRevisionId}` : " · no pending revision");
362 if (applyBtn)
363 {
364 applyBtn.disabled = !pendingRevisionId || applyInFlight;
365 applyBtn.title = pendingRevisionId
366 ? "Reload the live world with the pending map revision"
367 : "Save a chunk first to create a pending revision";
368 }
369}
370
371function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pending })
372{
373 if (active != null)
374 { activeRevisionId = active; }
375 pendingRevisionId = pending ?? null;
376 updateRevisionUI();
377}
378
379function showSelectedChunk (payload)
380{
381 draft = {
382 open: payload.data.open,
383 grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
384 blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)),
385 light: payload.data.light.slice(),
386 spawners: (payload.data.spawners ?? []).map((entry) => ({
387 localX: entry.localX,
388 localY: entry.localY,
389 config: { ...entry.config }
390 }))
391 };
392 $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`;
393 $("open").checked = draft.open;
394 setRevisionState({
395 activeRevisionId: payload.activeRevisionId,
396 pendingRevisionId: payload.pendingRevisionId
397 });
398 $("authored").textContent = payload.authored ? "authored" : "default grass (closed until saved open)";
399 const log = $("changelog");
400 log.innerHTML = "";
401 for (const entry of payload.changelog ?? [])
402 {
403 const item = document.createElement("article");
404 item.innerHTML = `<header>${entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
405 const list = document.createElement("ul");
406 for (const bullet of entry.diffEntries)
407 {
408 const li = document.createElement("li");
409 li.textContent = bullet;
410 list.append(li);
411 }
412 item.append(list);
413 log.append(item);
414 }
415 view.applySnapshot(snapshotFromPayload(payload));
416 syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);
417 captureDraftBaseline();
418 if (navigateAfterSave && pendingNavigate)
419 {
420 const next = pendingNavigate;
421 navigateAfterSave = false;
422 pendingNavigate = null;
423 doLoadNeighborhood(next.chunkX, next.chunkY);
424 }
425}
426
427function pruneView ()
428{
429 for (const key of [...view.chunks.keys()])
430 {
431 const [x, y] = key.split(",").map(Number);
432 if (!inEditorView(x, y))
433 { view.removeChunk(x, y); }
434 }
435}
436
437function frameNeighborhood ()
438{
439 const size = view.tileSize();
440 view.followPlayer = false;
441 const centerX = (chunkX + 0.5) * CHUNK_SIZE * size;
442 const centerY = (chunkY + 0.5) * CHUNK_SIZE * size;
443 view.scene.cameraPosition.x = view.scene.real_size.x / 2 - centerX;
444 view.scene.cameraPosition.y = view.scene.real_size.y / 2 - centerY;
445 updateSelectionBorder();
446}
447
448function updateSelectionBorder ()
449{
450 const border = $("selection-border");
451 const canvas = scene?.canvas;
452 if (!border || !canvas)
453 { return; }
454
455 const rect = canvas.getBoundingClientRect();
456 const size = view.tileSize();
457 const chunkPx = CHUNK_SIZE * size;
458 const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x;
459 const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y;
460 border.style.left = `${rect.left + screenLeft}px`;
461 border.style.top = `${rect.top + screenTop}px`;
462 border.style.width = `${chunkPx}px`;
463 border.style.height = `${chunkPx}px`;
464}
465
466function layoutScene ()
467{
468 const header = document.querySelector("body > header");
469 const aside = document.querySelector("body > aside");
470 const changelog = $("changelog-wrap");
471 const top = header.offsetHeight;
472 aside.style.top = `${top}px`;
473 changelog.style.top = `${top}px`;
474 const left = aside.offsetWidth;
475 const right = changelog.offsetWidth;
476 const width = Math.max(64, window.innerWidth - left - right);
477 const height = Math.max(64, window.innerHeight - top);
478 scene.position.x = left;
479 scene.position.y = top;
480 scene.size.x = width;
481 scene.size.y = height;
482 scene.g_fixSize();
483 useNearestNeighbour(scene, game.images);
484 const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX);
485 if (editorZoom == null)
486 { editorZoom = fit; }
487 else
488 { editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, editorZoom)); }
489 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
490 frameNeighborhood();
491}
492
493function zoomEditor (direction)
494{
495 if (!view)
496 { return; }
497 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
498 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
499 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
500 useNearestNeighbour(scene, game.images);
501 frameNeighborhood();
502}
503
504function requestChunks (coords)
505{
506 for (const coord of coords)
507 {
508 socket.send({ type: MessageType.editorLoadChunk, chunkX: coord.chunkX, chunkY: coord.chunkY });
509 }
510}
511
512function doLoadNeighborhood (x, y)
513{
514 chunkX = x;
515 chunkY = y;
516 $("coords").textContent = `${chunkX}, ${chunkY}`;
517 requestChunks(neighborhoodCoords(x, y));
518}
519
520function loadNeighborhood (x, y)
521{
522 if ((x !== chunkX || y !== chunkY) && isDraftDirty())
523 {
524 showUnsavedModal({ chunkX: x, chunkY: y });
525 return;
526 }
527 doLoadNeighborhood(x, y);
528}
529
530function requestNeighbors ()
531{
532 requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
533}
534
535function anyModalOpen ()
536{
537 return settingsModal?.isOpen()
538 || paletteModal?.isOpen()
539 || tileConfigModal?.isOpen()
540 || !$("unsaved-chunk-modal")?.hidden;
541}
542
543function updateTooltip (local)
544{
545 const tip = $("tile-tooltip");
546 if (!tip || !local || !draft)
547 {
548 if (tip)
549 { tip.hidden = true; }
550 view?.clearSpawnRangeHighlight();
551 return;
552 }
553 const block = normalizeBlock(draft.blocks[local.y * CHUNK_SIZE + local.x]);
554 const spawner = spawnerAt(local.x, local.y);
555 const lines = [];
556 if (block)
557 {
558 const def = BLOCK_DEFINITIONS[block.typeId];
559 lines.push(def?.displayName ?? `Block ${block.typeId}`);
560 if (block.config && Object.keys(block.config).length)
561 {
562 for (const [key, value] of Object.entries(block.config))
563 { lines.push(`${key}: ${value}`); }
564 }
565 }
566 if (spawner)
567 {
568 const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId);
569 const mob = mobDefinition(config.mobTypeId);
570 lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`);
571 lines.push(`maxAlive: ${config.maxAlive}`);
572 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
573 lines.push(`wanderRange: ${config.maxWanderRangeTiles}`);
574 lines.push(`id: ${config.spawnerId}`);
575 view.setSpawnRangeHighlight(
576 local.tileX,
577 local.tileY,
578 config.spawnRangeTiles,
579 config.maxWanderRangeTiles
580 );
581 }
582 else
583 { view.clearSpawnRangeHighlight(); }
584 if (!lines.length)
585 {
586 tip.hidden = true;
587 return;
588 }
589 tip.hidden = false;
590 tip.textContent = lines.join("\n");
591 const canvas = scene.canvas;
592 const rect = canvas.getBoundingClientRect();
593 const size = view.tileSize();
594 const screenX = local.tileX * size + scene.cameraPosition.x + rect.left + size;
595 const screenY = local.tileY * size + scene.cameraPosition.y + rect.top;
596 tip.style.left = `${screenX}px`;
597 tip.style.top = `${screenY}px`;
598}
599
600async function main ()
601{
602 catalog = await loadSpriteCatalog();
603 imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));
604 await preloadCatalogImages(game, catalog);
605 applySpriteSheets(game.images, catalog);
606 scene = new Scene(250, 56, 64, 64);
607 game.loadScene(scene);
608 useNearestNeighbour(scene, game.images);
609 view = new WorldView(game, scene, catalog);
610 view.followPlayer = false;
611 syncSeasonControls(view.worldSeason ?? seasonIdAt());
612 layoutScene();
613 selectTool(tool);
614 $("tool").textContent = selectedToolLabel();
615
616 paletteModal = initPaletteModal({
617 catalog,
618 imageUrlFor (name)
619 {
620 const sprite = game.images[name];
621 const html = sprite?.g_image;
622 if (html && typeof html.toDataURL === "function")
623 {
624 try
625 { return html.toDataURL("image/png"); }
626 catch (_)
627 { /* fall through */ }
628 }
629 return imageUrlByName.get(name) ?? null;
630 },
631 onSelect (next)
632 {
633 selectTool(next);
634 $("tool").textContent = selectedToolLabel();
635 }
636 });
637
638 tileConfigModal = initTileConfigModal({
639 onSave (ctx, config)
640 {
641 if (!draft)
642 { return; }
643 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
644 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
645 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
646 afterDraftMutation();
647 },
648 onRemove (ctx)
649 {
650 if (!draft)
651 { return; }
652 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
653 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
654 afterDraftMutation();
655 }
656 });
657
658 const ticker = new GameObject(0, 0, null, 10);
659 ticker.update = (dt) =>
660 {
661 hoverLocal = null;
662 const canvas = scene.canvas;
663 const rect = canvas.getBoundingClientRect();
664 const mouseX = GameInput.mousePosition.x - rect.left;
665 const mouseY = GameInput.mousePosition.y - rect.top;
666 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
667 if (overCanvas && draft && !anyModalOpen())
668 {
669 const tile = view.screenToTile(mouseX, mouseY);
670 const localX = tile.tileX - chunkX * CHUNK_SIZE;
671 const localY = tile.tileY - chunkY * CHUNK_SIZE;
672 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
673 {
674 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
675 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
676 updateTooltip(hoverLocal);
677 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
678 { paintAt(localX, localY); }
679 }
680 else
681 {
682 view.clearTilePreview();
683 updateTooltip(null);
684 }
685 }
686 else
687 {
688 view.clearTilePreview();
689 updateTooltip(null);
690 }
691 view.update(dt);
692 frameNeighborhood();
693 };
694 scene.addObject(ticker);
695 window.addEventListener("resize", layoutScene);
696
697 socket = new GameSocket(defaultSocketUrl(), (message) =>
698 {
699 if (message.type === MessageType.session)
700 {
701 $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`;
702 socket.send({ type: MessageType.editorLoadSettings });
703 loadNeighborhood(0, 0);
704 }
705 else if (message.type === MessageType.editorSettings)
706 { settingsModal.handleMessage(message); }
707 else if (message.type === MessageType.editorChunk)
708 {
709 if (message.settings)
710 { view.setSettings(message.settings); }
711 if (!inEditorView(message.chunkX, message.chunkY))
712 { return; }
713 if (message.chunkX === chunkX && message.chunkY === chunkY)
714 { showSelectedChunk(message); }
715 else
716 {
717 view.applySnapshot(snapshotFromPayload(message));
718 syncSpawnersOverlay(message.chunkX, message.chunkY, message.data.spawners);
719 }
720 pruneView();
721 }
722 else if (message.type === MessageType.editorRevisionApplied)
723 {
724 applyInFlight = false;
725 setRevisionState({
726 activeRevisionId: message.activeRevisionId,
727 pendingRevisionId: message.pendingRevisionId
728 });
729 const status = $("apply-status");
730 status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`;
731 status.className = "hint ok";
732 requestChunks(neighborhoodCoords(chunkX, chunkY));
733 }
734 else if (message.type === MessageType.error)
735 {
736 $("error").textContent = message.message;
737 navigateAfterSave = false;
738 if (applyInFlight)
739 {
740 applyInFlight = false;
741 $("apply-status").textContent = "";
742 $("apply-status").className = "hint";
743 updateRevisionUI();
744 }
745 }
746 });
747 settingsModal = initSettingsModal({
748 socket,
749 MessageType,
750 onApplied (settings)
751 {
752 view.setSettings(settings);
753 },
754 onPreviewNight (hour)
755 {
756 view.nightPreview = hour;
757 $("night").value = String(hour);
758 $("night-label").textContent = Number(hour).toFixed(1);
759 }
760 });
761 game.startGame();
762 await socket.connect();
763}
764
765$("tool").textContent = selectedToolLabel();
766$("tool-erase").addEventListener("click", () =>
767{
768 selectTool({ kind: "erase" });
769 $("tool").textContent = selectedToolLabel();
770});
771
772$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
773$("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1));
774$("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY));
775$("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
776$("open").addEventListener("change", () =>
777{
778 if (draft)
779 {
780 draft.open = $("open").checked;
781 view.setChunkOpen(chunkX, chunkY, draft.open);
782 afterDraftMutation();
783 }
784});
785$("save").addEventListener("click", () =>
786{
787 saveSelectedChunk();
788});
789$("unsaved-chunk-cancel")?.addEventListener("click", () =>
790{
791 pendingNavigate = null;
792 navigateAfterSave = false;
793 hideUnsavedModal();
794});
795$("unsaved-chunk-backdrop")?.addEventListener("click", () =>
796{
797 pendingNavigate = null;
798 navigateAfterSave = false;
799 hideUnsavedModal();
800});
801$("unsaved-chunk-discard")?.addEventListener("click", () =>
802{
803 const next = pendingNavigate;
804 hideUnsavedModal();
805 pendingNavigate = null;
806 navigateAfterSave = false;
807 if (next)
808 { doLoadNeighborhood(next.chunkX, next.chunkY); }
809});
810$("unsaved-chunk-save")?.addEventListener("click", () =>
811{
812 hideUnsavedModal();
813 if (!pendingNavigate)
814 { return; }
815 navigateAfterSave = true;
816 if (!saveSelectedChunk())
817 {
818 navigateAfterSave = false;
819 const next = pendingNavigate;
820 pendingNavigate = null;
821 if (next)
822 { doLoadNeighborhood(next.chunkX, next.chunkY); }
823 }
824});
825$("apply").addEventListener("click", () =>
826{
827 if (!pendingRevisionId || applyInFlight)
828 { return; }
829 $("error").textContent = "";
830 const status = $("apply-status");
831 status.textContent = "Applying…";
832 status.className = "hint";
833 applyInFlight = true;
834 updateRevisionUI();
835 socket.send({ type: MessageType.editorApplyRevision });
836});
837$("night").addEventListener("input", () =>
838{
839 view.nightPreview = Number($("night").value);
840 $("night-label").textContent = view.nightPreview.toFixed(1);
841});
842$("season").addEventListener("change", () =>
843{
844 applySeasonPreview($("season").value);
845});
846
847function syncSeasonControls (season)
848{
849 const next = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer
850 ? season
851 : seasonIdAt();
852 $("season").value = next;
853 view?.setWorldSeason(next);
854}
855
856function applySeasonPreview (season)
857{
858 syncSeasonControls(season);
859}
860
861function cycleToolState (direction)
862{
863 if (tool.kind === "erase" || tool.kind === "spawner")
864 { return; }
865 const layer = tool.kind === "ground" ? "ground" : "block";
866 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
867 if (definitionUsesNeighborConnect(def))
868 { return; }
869 if (tool.kind === "block" && def?.id === BlockType.flower)
870 { return; }
871 const allStates = statesForType(catalog, layer, def.key);
872 const seasonal = seasonalCycleStates(allStates);
873 const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
874 if (states.length < 2)
875 { return; }
876 tool.state = cycleState(states, tool.state, direction);
877 $("tool").textContent = selectedToolLabel();
878 const season = seasonIdFromVisualState(tool.state);
879 if (season)
880 { applySeasonPreview(season); }
881 if (!draft || !hoverLocal)
882 { return; }
883 const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;
884 if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId)
885 { paintAt(hoverLocal.x, hoverLocal.y); }
886 else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId)
887 { paintAt(hoverLocal.x, hoverLocal.y); }
888}
889
890document.addEventListener("wheel", (event) =>
891{
892 if (!scene?.canvas || anyModalOpen())
893 { return; }
894 const rect = scene.canvas.getBoundingClientRect();
895 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
896 { return; }
897 event.preventDefault();
898 if (event.shiftKey)
899 {
900 cycleToolState(event.deltaY < 0 ? 1 : -1);
901 if (hoverLocal)
902 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
903 return;
904 }
905 zoomEditor(event.deltaY < 0 ? 1 : -1);
906}, { passive: false });
907
908document.addEventListener("contextmenu", (event) =>
909{
910 if (!scene?.canvas || anyModalOpen() || !draft)
911 { return; }
912 const rect = scene.canvas.getBoundingClientRect();
913 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
914 { return; }
915 event.preventDefault();
916 const tile = view.screenToTile(event.clientX - rect.left, event.clientY - rect.top);
917 const localX = tile.tileX - chunkX * CHUNK_SIZE;
918 const localY = tile.tileY - chunkY * CHUNK_SIZE;
919 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
920 { return; }
921 const spawner = spawnerAt(localX, localY);
922 if (!spawner)
923 { return; }
924 tileConfigModal.openSpawner({
925 localX,
926 localY,
927 tileX: tile.tileX,
928 tileY: tile.tileY,
929 config: { ...spawner.config }
930 });
931});
932
933main().catch((error) =>
934{
935 $("error").textContent = error.message;
936 console.error(error);
937});