BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

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