BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

main.js 15.1 KiB Download Raw
1import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, BlockType, GroundType, normalizeGround } from "/shared/definitions/tiles.js";
3import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
4import { GameSocket, defaultSocketUrl } from "../net/socket.js";
5import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
6import { WorldView } from "../render/worldView.js";
7import { initSettingsModal } from "./settingsModal.js";
8
9const game = new Game();
10let socket;
11let scene;
12let view;
13let draft = null;
14let chunkX = 0;
15let chunkY = 0;
16let tool = { kind: "ground", typeId: GroundType.grass, state: null };
17let settingsModal;
18let catalog = { grounds: {}, blocks: {} };
19let hoverLocal = null;
20let editorZoom = null;
21let activeRevisionId = null;
22let pendingRevisionId = null;
23let applyInFlight = false;
24const EDITOR_ZOOM_MIN = 0.25;
25const EDITOR_ZOOM_MAX = 8;
26const EDITOR_ZOOM_STEP = 1.12;
27
28function $ (id)
29{
30 return document.getElementById(id);
31}
32
33function selectedToolLabel ()
34{
35 if (tool.kind === "erase")
36 { return "Erase block"; }
37 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
38 const layer = tool.kind === "ground" ? "ground" : "block";
39 const states = statesForType(catalog, layer, def.key);
40 const state = resolveState(states, tool.state);
41 if (states.length > 1)
42 { return `${def.displayName} (${state})`; }
43 return def.displayName;
44}
45
46function selectTool (next)
47{
48 if (next.kind === "erase")
49 {
50 tool = { kind: "erase" };
51 return;
52 }
53 const layer = next.kind === "ground" ? "ground" : "block";
54 const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
55 tool = {
56 kind: next.kind,
57 typeId: next.typeId,
58 state: defaultStateForType(catalog, layer, def.key)
59 };
60}
61
62function placeableToolState ()
63{
64 if (tool.kind === "erase")
65 { return null; }
66 const layer = tool.kind === "ground" ? "ground" : "block";
67 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
68 return resolveState(statesForType(catalog, layer, def.key), tool.state);
69}
70
71function previewFromTool ()
72{
73 if (tool.kind === "erase")
74 { return { block: null }; }
75 const state = placeableToolState();
76 if (tool.kind === "ground")
77 { return { ground: { typeId: tool.typeId, state } }; }
78 return { block: { typeId: tool.typeId, state, config: null } };
79}
80
81function inEditorView (x, y)
82{
83 return Math.abs(x - chunkX) <= VISIBLE_CHUNK_RADIUS && Math.abs(y - chunkY) <= VISIBLE_CHUNK_RADIUS;
84}
85
86function neighborhoodCoords (centerX, centerY)
87{
88 const coords = [];
89 for (let dy = -VISIBLE_CHUNK_RADIUS; dy <= VISIBLE_CHUNK_RADIUS; dy++)
90 {
91 for (let dx = -VISIBLE_CHUNK_RADIUS; dx <= VISIBLE_CHUNK_RADIUS; dx++)
92 { coords.push({ chunkX: centerX + dx, chunkY: centerY + dy }); }
93 }
94 return coords;
95}
96
97function snapshotFromPayload (payload)
98{
99 return {
100 chunkX: payload.chunkX,
101 chunkY: payload.chunkY,
102 open: payload.data.open,
103 closedEdges: payload.closedEdges,
104 grounds: payload.data.grounds,
105 blocks: payload.data.blocks,
106 light: payload.data.light,
107 entities: []
108 };
109}
110
111function paintAt (localX, localY)
112{
113 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
114 { return; }
115 const index = localY * CHUNK_SIZE + localX;
116 const state = placeableToolState();
117 if (tool.kind === "ground")
118 { draft.grounds[index] = { typeId: tool.typeId, state }; }
119 else if (tool.kind === "erase")
120 { draft.blocks[index] = null; }
121 else
122 {
123 const existing = draft.blocks[index];
124 let config = null;
125 if (tool.typeId === BlockType.spawner)
126 {
127 const spawnerId = existing?.typeId === BlockType.spawner && existing.config?.spawnerId
128 ? existing.config.spawnerId
129 : `${chunkX}:${chunkY}:${index}`;
130 config = {
131 spawnerId,
132 mobTypeId: $("spawner-mob")?.value || "deer",
133 maxAlive: Number($("spawner-max")?.value || 3),
134 spawnRangeTiles: Number($("spawner-range")?.value || 4)
135 };
136 }
137 draft.blocks[index] = { typeId: tool.typeId, state, config };
138 }
139 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
140 ground: draft.grounds[index],
141 block: draft.blocks[index],
142 light: draft.light[index]
143 });
144}
145
146function updateRevisionUI ()
147{
148 const applyBtn = $("apply");
149 $("revision").textContent = `active ${activeRevisionId ?? "?"}` +
150 (pendingRevisionId ? ` · pending ${pendingRevisionId}` : " · no pending revision");
151 if (applyBtn)
152 {
153 applyBtn.disabled = !pendingRevisionId || applyInFlight;
154 applyBtn.title = pendingRevisionId
155 ? "Reload the live world with the pending map revision"
156 : "Save a chunk first to create a pending revision";
157 }
158}
159
160function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pending })
161{
162 if (active != null)
163 { activeRevisionId = active; }
164 pendingRevisionId = pending ?? null;
165 updateRevisionUI();
166}
167
168function showSelectedChunk (payload)
169{
170 draft = {
171 open: payload.data.open,
172 grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
173 blocks: payload.data.blocks.map((block) => (block ? { ...block } : null)),
174 light: payload.data.light.slice()
175 };
176 $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`;
177 $("open").checked = draft.open;
178 setRevisionState({
179 activeRevisionId: payload.activeRevisionId,
180 pendingRevisionId: payload.pendingRevisionId
181 });
182 $("authored").textContent = payload.authored ? "authored" : "default grass (closed until saved open)";
183 const log = $("changelog");
184 log.innerHTML = "";
185 for (const entry of payload.changelog ?? [])
186 {
187 const item = document.createElement("article");
188 item.innerHTML = `<header>${entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
189 const list = document.createElement("ul");
190 for (const bullet of entry.diffEntries)
191 {
192 const li = document.createElement("li");
193 li.textContent = bullet;
194 list.append(li);
195 }
196 item.append(list);
197 log.append(item);
198 }
199 view.applySnapshot(snapshotFromPayload(payload));
200}
201
202function pruneView ()
203{
204 for (const key of [...view.chunks.keys()])
205 {
206 const [x, y] = key.split(",").map(Number);
207 if (!inEditorView(x, y))
208 { view.removeChunk(x, y); }
209 }
210}
211
212function frameNeighborhood ()
213{
214 const size = view.tileSize();
215 view.followPlayer = false;
216 const centerX = (chunkX + 0.5) * CHUNK_SIZE * size;
217 const centerY = (chunkY + 0.5) * CHUNK_SIZE * size;
218 view.scene.cameraPosition.x = view.scene.real_size.x / 2 - centerX;
219 view.scene.cameraPosition.y = view.scene.real_size.y / 2 - centerY;
220 updateSelectionBorder();
221}
222
223function updateSelectionBorder ()
224{
225 const border = $("selection-border");
226 const canvas = scene?.canvas;
227 if (!border || !canvas)
228 { return; }
229
230 const rect = canvas.getBoundingClientRect();
231 const size = view.tileSize();
232 const chunkPx = CHUNK_SIZE * size;
233 const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x;
234 const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y;
235 border.style.left = `${rect.left + screenLeft}px`;
236 border.style.top = `${rect.top + screenTop}px`;
237 border.style.width = `${chunkPx}px`;
238 border.style.height = `${chunkPx}px`;
239}
240
241function layoutScene ()
242{
243 const header = document.querySelector("body > header");
244 const aside = document.querySelector("body > aside");
245 const changelog = $("changelog-wrap");
246 const top = header.offsetHeight;
247 aside.style.top = `${top}px`;
248 changelog.style.top = `${top}px`;
249 const left = aside.offsetWidth;
250 const right = changelog.offsetWidth;
251 const width = Math.max(64, window.innerWidth - left - right);
252 const height = Math.max(64, window.innerHeight - top);
253 scene.position.x = left;
254 scene.position.y = top;
255 scene.size.x = width;
256 scene.size.y = height;
257 scene.g_fixSize();
258 useNearestNeighbour(scene, game.images);
259 const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX);
260 if (editorZoom == null)
261 { editorZoom = fit; }
262 else
263 { editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, editorZoom)); }
264 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
265 frameNeighborhood();
266}
267
268function zoomEditor (direction)
269{
270 if (!view)
271 { return; }
272 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
273 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
274 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
275 useNearestNeighbour(scene, game.images);
276 frameNeighborhood();
277}
278
279function requestChunks (coords)
280{
281 for (const coord of coords)
282 {
283 socket.send({ type: MessageType.editorLoadChunk, chunkX: coord.chunkX, chunkY: coord.chunkY });
284 }
285}
286
287function loadNeighborhood (x, y)
288{
289 chunkX = x;
290 chunkY = y;
291 $("coords").textContent = `${chunkX}, ${chunkY}`;
292 requestChunks(neighborhoodCoords(x, y));
293}
294
295function requestNeighbors ()
296{
297 requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
298}
299
300async function main ()
301{
302 catalog = await loadSpriteCatalog();
303 await preloadCatalogImages(game, catalog);
304 applySpriteSheets(game.images, catalog);
305 scene = new Scene(250, 56, 64, 64);
306 game.loadScene(scene);
307 useNearestNeighbour(scene, game.images);
308 view = new WorldView(game, scene, catalog);
309 view.followPlayer = false;
310 layoutScene();
311 selectTool(tool);
312 $("tool").textContent = selectedToolLabel();
313 const ticker = new GameObject(0, 0, null, 10);
314 ticker.update = (dt) =>
315 {
316 hoverLocal = null;
317 const canvas = scene.canvas;
318 const rect = canvas.getBoundingClientRect();
319 const mouseX = GameInput.mousePosition.x - rect.left;
320 const mouseY = GameInput.mousePosition.y - rect.top;
321 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
322 if (overCanvas && draft && !settingsModal?.isOpen())
323 {
324 const tile = view.screenToTile(mouseX, mouseY);
325 const localX = tile.tileX - chunkX * CHUNK_SIZE;
326 const localY = tile.tileY - chunkY * CHUNK_SIZE;
327 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
328 {
329 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
330 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
331 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
332 { paintAt(localX, localY); }
333 }
334 else
335 { view.clearTilePreview(); }
336 }
337 else
338 { view.clearTilePreview(); }
339 view.update(dt);
340 frameNeighborhood();
341 };
342 scene.addObject(ticker);
343 window.addEventListener("resize", layoutScene);
344
345 socket = new GameSocket(defaultSocketUrl(), (message) =>
346 {
347 if (message.type === MessageType.session)
348 {
349 $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`;
350 socket.send({ type: MessageType.editorLoadSettings });
351 loadNeighborhood(0, 0);
352 }
353 else if (message.type === MessageType.editorSettings)
354 { settingsModal.handleMessage(message); }
355 else if (message.type === MessageType.editorChunk)
356 {
357 if (message.settings)
358 { view.setSettings(message.settings); }
359 if (!inEditorView(message.chunkX, message.chunkY))
360 { return; }
361 if (message.chunkX === chunkX && message.chunkY === chunkY)
362 { showSelectedChunk(message); }
363 else
364 { view.applySnapshot(snapshotFromPayload(message)); }
365 pruneView();
366 }
367 else if (message.type === MessageType.editorRevisionApplied)
368 {
369 applyInFlight = false;
370 setRevisionState({
371 activeRevisionId: message.activeRevisionId,
372 pendingRevisionId: message.pendingRevisionId
373 });
374 const status = $("apply-status");
375 status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`;
376 status.className = "hint ok";
377 requestChunks(neighborhoodCoords(chunkX, chunkY));
378 }
379 else if (message.type === MessageType.error)
380 {
381 $("error").textContent = message.message;
382 if (applyInFlight)
383 {
384 applyInFlight = false;
385 $("apply-status").textContent = "";
386 $("apply-status").className = "hint";
387 updateRevisionUI();
388 }
389 }
390 });
391 settingsModal = initSettingsModal({
392 socket,
393 MessageType,
394 onApplied (settings)
395 {
396 view.setSettings(settings);
397 },
398 onPreviewNight (hour)
399 {
400 view.nightPreview = hour;
401 $("night").value = String(hour);
402 $("night-label").textContent = Number(hour).toFixed(1);
403 }
404 });
405 game.startGame();
406 await socket.connect();
407}
408
409$("tool").textContent = selectedToolLabel();
410document.querySelectorAll("[data-tool]").forEach((button) =>
411{
412 button.addEventListener("click", () =>
413 {
414 selectTool(JSON.parse(button.dataset.tool));
415 $("tool").textContent = selectedToolLabel();
416 });
417});
418
419$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
420$("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1));
421$("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY));
422$("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
423$("open").addEventListener("change", () =>
424{
425 if (draft)
426 {
427 draft.open = $("open").checked;
428 view.setChunkOpen(chunkX, chunkY, draft.open);
429 }
430});
431$("save").addEventListener("click", () =>
432{
433 $("error").textContent = "";
434 $("apply-status").textContent = "";
435 $("apply-status").className = "hint";
436 socket.send({
437 type: MessageType.editorSaveChunk,
438 chunkX,
439 chunkY,
440 draft: { open: $("open").checked, grounds: draft.grounds, blocks: draft.blocks }
441 });
442 requestNeighbors();
443});
444$("apply").addEventListener("click", () =>
445{
446 if (!pendingRevisionId || applyInFlight)
447 { return; }
448 $("error").textContent = "";
449 const status = $("apply-status");
450 status.textContent = "Applying…";
451 status.className = "hint";
452 applyInFlight = true;
453 updateRevisionUI();
454 socket.send({ type: MessageType.editorApplyRevision });
455});
456$("night").addEventListener("input", () =>
457{
458 view.nightPreview = Number($("night").value);
459 $("night-label").textContent = view.nightPreview.toFixed(1);
460});
461
462function cycleToolState (direction)
463{
464 if (tool.kind === "erase")
465 { return; }
466 const layer = tool.kind === "ground" ? "ground" : "block";
467 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
468 const states = statesForType(catalog, layer, def.key);
469 if (states.length < 2)
470 { return; }
471 tool.state = cycleState(states, tool.state, direction);
472 $("tool").textContent = selectedToolLabel();
473 if (!draft || !hoverLocal)
474 { return; }
475 const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;
476 if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId)
477 { paintAt(hoverLocal.x, hoverLocal.y); }
478 else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId)
479 { paintAt(hoverLocal.x, hoverLocal.y); }
480}
481
482document.addEventListener("wheel", (event) =>
483{
484 if (!scene?.canvas || settingsModal?.isOpen())
485 { return; }
486 const rect = scene.canvas.getBoundingClientRect();
487 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
488 { return; }
489 event.preventDefault();
490 if (event.shiftKey)
491 {
492 cycleToolState(event.deltaY < 0 ? 1 : -1);
493 if (hoverLocal)
494 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
495 return;
496 }
497 zoomEditor(event.deltaY < 0 ? 1 : -1);
498}, { passive: false });
499
500main().catch((error) =>
501{
502 $("error").textContent = error.message;
503 console.error(error);
504});