BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

main.js 8.9 KiB Download Raw
1import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType } from "/shared/definitions/tiles.js";
3import { GameSocket, defaultSocketUrl } from "../net/socket.js";
4import { PLAY_IMAGES, useNearestNeighbour } from "../render/sprites.js";
5import { WorldView } from "../render/worldView.js";
6import { initSettingsModal } from "./settingsModal.js";
7
8const game = new Game();
9let socket;
10let scene;
11let view;
12let draft = null;
13let chunkX = 0;
14let chunkY = 0;
15let tool = { kind: "ground", typeId: GroundType.grass };
16let settingsModal;
17
18function $ (id)
19{
20 return document.getElementById(id);
21}
22
23function selectedToolLabel ()
24{
25 if (tool.kind === "erase")
26 { return "Erase block"; }
27 if (tool.kind === "ground")
28 { return GROUND_DEFINITIONS[tool.typeId].displayName; }
29 return BLOCK_DEFINITIONS[tool.typeId].displayName;
30}
31
32function inEditorView (x, y)
33{
34 return Math.abs(x - chunkX) <= VISIBLE_CHUNK_RADIUS && Math.abs(y - chunkY) <= VISIBLE_CHUNK_RADIUS;
35}
36
37function neighborhoodCoords (centerX, centerY)
38{
39 const coords = [];
40 for (let dy = -VISIBLE_CHUNK_RADIUS; dy <= VISIBLE_CHUNK_RADIUS; dy++)
41 {
42 for (let dx = -VISIBLE_CHUNK_RADIUS; dx <= VISIBLE_CHUNK_RADIUS; dx++)
43 { coords.push({ chunkX: centerX + dx, chunkY: centerY + dy }); }
44 }
45 return coords;
46}
47
48function snapshotFromPayload (payload)
49{
50 return {
51 chunkX: payload.chunkX,
52 chunkY: payload.chunkY,
53 open: payload.data.open,
54 closedEdges: payload.closedEdges,
55 grounds: payload.data.grounds,
56 blocks: payload.data.blocks,
57 light: payload.data.light,
58 entities: []
59 };
60}
61
62function paintAt (localX, localY)
63{
64 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
65 { return; }
66 const index = localY * CHUNK_SIZE + localX;
67 if (tool.kind === "ground")
68 { draft.grounds[index] = tool.typeId; }
69 else if (tool.kind === "erase")
70 { draft.blocks[index] = null; }
71 else
72 { draft.blocks[index] = { typeId: tool.typeId, config: null }; }
73 view.applySnapshot({
74 chunkX,
75 chunkY,
76 open: draft.open,
77 closedEdges: view.chunks.get(`${chunkX},${chunkY}`)?.closedEdges,
78 grounds: draft.grounds,
79 blocks: draft.blocks,
80 light: draft.light,
81 entities: []
82 });
83}
84
85function showSelectedChunk (payload)
86{
87 draft = {
88 open: payload.data.open,
89 grounds: payload.data.grounds.slice(),
90 blocks: payload.data.blocks.map((block) => (block ? { ...block } : null)),
91 light: payload.data.light.slice()
92 };
93 $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`;
94 $("open").checked = draft.open;
95 $("revision").textContent = `active ${payload.activeRevisionId}` +
96 (payload.pendingRevisionId ? ` · pending ${payload.pendingRevisionId}` : " · no pending revision");
97 $("authored").textContent = payload.authored ? "authored" : "default grass (closed until saved open)";
98 const log = $("changelog");
99 log.innerHTML = "";
100 for (const entry of payload.changelog ?? [])
101 {
102 const item = document.createElement("article");
103 item.innerHTML = `<header>${entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
104 const list = document.createElement("ul");
105 for (const bullet of entry.diffEntries)
106 {
107 const li = document.createElement("li");
108 li.textContent = bullet;
109 list.append(li);
110 }
111 item.append(list);
112 log.append(item);
113 }
114 view.applySnapshot(snapshotFromPayload(payload));
115}
116
117function pruneView ()
118{
119 for (const key of [...view.chunks.keys()])
120 {
121 const [x, y] = key.split(",").map(Number);
122 if (!inEditorView(x, y))
123 { view.removeChunk(x, y); }
124 }
125}
126
127function frameNeighborhood ()
128{
129 const size = view.tileSize();
130 view.followPlayer = false;
131 const centerX = (chunkX + 0.5) * CHUNK_SIZE * size;
132 const centerY = (chunkY + 0.5) * CHUNK_SIZE * size;
133 view.scene.cameraPosition.x = view.scene.real_size.x / 2 - centerX;
134 view.scene.cameraPosition.y = view.scene.real_size.y / 2 - centerY;
135 updateSelectionBorder();
136}
137
138function updateSelectionBorder ()
139{
140 const border = $("selection-border");
141 const canvas = scene?.canvas;
142 if (!border || !canvas)
143 { return; }
144
145 const rect = canvas.getBoundingClientRect();
146 const size = view.tileSize();
147 const chunkPx = CHUNK_SIZE * size;
148 const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x;
149 const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y;
150 border.style.left = `${rect.left + screenLeft}px`;
151 border.style.top = `${rect.top + screenTop}px`;
152 border.style.width = `${chunkPx}px`;
153 border.style.height = `${chunkPx}px`;
154}
155
156function layoutScene ()
157{
158 const header = document.querySelector("body > header");
159 const aside = document.querySelector("body > aside");
160 const changelog = $("changelog-wrap");
161 const top = header.offsetHeight;
162 aside.style.top = `${top}px`;
163 changelog.style.top = `${top}px`;
164 const left = aside.offsetWidth;
165 const right = changelog.offsetWidth;
166 const width = Math.max(64, window.innerWidth - left - right);
167 const height = Math.max(64, window.innerHeight - top);
168 scene.position.x = left;
169 scene.position.y = top;
170 scene.size.x = width;
171 scene.size.y = height;
172 scene.g_fixSize();
173 useNearestNeighbour(scene, game.images);
174 const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX);
175 view.setZoom(fit, { min: 0.5, max: 4 });
176 frameNeighborhood();
177}
178
179function requestChunks (coords)
180{
181 for (const coord of coords)
182 {
183 socket.send({ type: MessageType.editorLoadChunk, chunkX: coord.chunkX, chunkY: coord.chunkY });
184 }
185}
186
187function loadNeighborhood (x, y)
188{
189 chunkX = x;
190 chunkY = y;
191 $("coords").textContent = `${chunkX}, ${chunkY}`;
192 requestChunks(neighborhoodCoords(x, y));
193}
194
195function requestNeighbors ()
196{
197 requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
198}
199
200async function main ()
201{
202 await game.preloadImages(PLAY_IMAGES);
203 scene = new Scene(250, 56, 64, 64);
204 game.loadScene(scene);
205 useNearestNeighbour(scene, game.images);
206 view = new WorldView(game, scene);
207 view.followPlayer = false;
208 layoutScene();
209 const ticker = new GameObject(0, 0, null, 10);
210 ticker.update = (dt) =>
211 {
212 if (GameInput.mouseHeld(GameInput.MouseButtons.Left) && draft && !settingsModal?.isOpen())
213 {
214 const canvas = scene.canvas;
215 const rect = canvas.getBoundingClientRect();
216 const mouseX = GameInput.mousePosition.x - rect.left;
217 const mouseY = GameInput.mousePosition.y - rect.top;
218 if (mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height)
219 {
220 const tile = view.screenToTile(mouseX, mouseY);
221 paintAt(tile.tileX - chunkX * CHUNK_SIZE, tile.tileY - chunkY * CHUNK_SIZE);
222 }
223 }
224 view.update(dt);
225 frameNeighborhood();
226 };
227 scene.addObject(ticker);
228 window.addEventListener("resize", layoutScene);
229
230 socket = new GameSocket(defaultSocketUrl(), (message) =>
231 {
232 if (message.type === MessageType.session)
233 {
234 $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`;
235 socket.send({ type: MessageType.editorLoadSettings });
236 loadNeighborhood(0, 0);
237 }
238 else if (message.type === MessageType.editorSettings)
239 { settingsModal.handleMessage(message); }
240 else if (message.type === MessageType.editorChunk)
241 {
242 if (message.settings)
243 { view.settings = message.settings; }
244 if (!inEditorView(message.chunkX, message.chunkY))
245 { return; }
246 if (message.chunkX === chunkX && message.chunkY === chunkY)
247 { showSelectedChunk(message); }
248 else
249 { view.applySnapshot(snapshotFromPayload(message)); }
250 pruneView();
251 }
252 else if (message.type === MessageType.error)
253 { $("error").textContent = message.message; }
254 });
255 settingsModal = initSettingsModal({
256 socket,
257 MessageType,
258 onApplied (settings)
259 {
260 view.settings = settings;
261 }
262 });
263 game.startGame();
264 await socket.connect();
265}
266
267$("tool").textContent = selectedToolLabel();
268document.querySelectorAll("[data-tool]").forEach((button) =>
269{
270 button.addEventListener("click", () =>
271 {
272 tool = JSON.parse(button.dataset.tool);
273 $("tool").textContent = selectedToolLabel();
274 });
275});
276
277$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
278$("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1));
279$("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY));
280$("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
281$("open").addEventListener("change", () =>
282{
283 if (draft)
284 {
285 draft.open = $("open").checked;
286 view.setChunkOpen(chunkX, chunkY, draft.open);
287 }
288});
289$("save").addEventListener("click", () =>
290{
291 $("error").textContent = "";
292 socket.send({
293 type: MessageType.editorSaveChunk,
294 chunkX,
295 chunkY,
296 draft: { open: $("open").checked, grounds: draft.grounds, blocks: draft.blocks }
297 });
298 requestNeighbors();
299});
300$("apply").addEventListener("click", () => socket.send({ type: MessageType.editorApplyRevision }));
301$("night").addEventListener("input", () =>
302{
303 view.nightPreview = Number($("night").value);
304 $("night-label").textContent = view.nightPreview.toFixed(1);
305});
306
307main().catch((error) =>
308{
309 $("error").textContent = error.message;
310 console.error(error);
311});