BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

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