space-browser / commits / 5e7e690
refactor: frontend files by concerns
This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.
@@ -0,0 +1,122 @@
1+// An agent driving this page sees no cursor and cannot know where the camera is,
2+// so it gets the transform the game itself uses, never a copy of it: world point
3+// to screen pixel, screen pixel to world point, and every clickable thing already
4+// converted. It also gets the pointer drawn in cells, because a screenshot cannot
5+// show the browser's own cursor. Nothing here runs in a build a player sees.
6+import { CELL, type View } from './view';
7+import { toWorld } from './sim';
8+import { at, cam, cellOf, rect, screen, screenOf } from './stage';
9+import { loose, ore, ships, state } from './world';
10+
11+type Target = {
12+ id: number;
13+ kind: string; // me, ship, piece, loose, ore, or a body kind
14+ owner: number; // the hull a piece belongs to, 0 for anything loose
15+ x: number;
16+ y: number;
17+ px: number;
18+ py: number;
19+ cellX: number;
20+ cellY: number;
21+ cellPx: number; // the centre of that cell: a click lands on a glyph, not between four
22+ cellPy: number;
23+ d: number; // world distance from your hull, nearest first
24+};
25+
26+// The canvas box and the world<->screen transform, read once per use: a layout read
27+// per target would make the pointer cost a forced reflow for every thing on screen.
28+const boxOf = (r: DOMRect) => ({
29+ left: r.left,
30+ top: r.top,
31+ width: r.width,
32+ height: r.height,
33+ cell: CELL,
34+ cols: r.width / CELL,
35+ rows: r.height / CELL,
36+});
37+const canvasBox = () => boxOf(rect());
38+
39+const targets = (): Target[] => {
40+ const me = ships.get(state?.you ?? 0);
41+ const r = rect();
42+ const box = boxOf(r);
43+ const out: Target[] = [];
44+ const add = (id: number, kind: string, owner: number, x: number, y: number) => {
45+ const s = screenOf(r, x, y);
46+ const c = cellOf(s.px, s.py, r);
47+ out.push({
48+ id,
49+ kind,
50+ owner,
51+ x,
52+ y,
53+ px: s.px,
54+ py: s.py,
55+ ...c,
56+ cellPx: box.left + (c.cellX + 0.5) * CELL,
57+ cellPy: box.top + (c.cellY + 0.5) * CELL,
58+ d: me ? Math.hypot(x - me.x, y - me.y) : 0,
59+ });
60+ };
61+ for (const s of ships.values()) {
62+ add(s.id, s.id === state?.you ? 'me' : 'ship', 0, s.x, s.y);
63+ for (const p of s.pieces) {
64+ const w = toWorld(s, p);
65+ add(p.id, 'piece', s.id, w.x, w.y);
66+ }
67+ }
68+ for (const l of loose.values()) add(l.id, 'loose', 0, l.x, l.y);
69+ for (const o of ore.values()) add(o.id, 'ore', 0, o.x, o.y);
70+ for (const b of state?.bodies ?? []) add(b.id, b.kind, 0, b.x, b.y);
71+ return out.sort((a, b) => a.d - b.d);
72+};
73+
74+let pointer: { px: number; py: number; cellX: number; cellY: number; world: { x: number; y: number } } | null = null;
75+const dev = import.meta.env.DEV;
76+const label = dev ? document.createElement('pre') : null;
77+let view: View | null = null;
78+
79+const game = {
80+ get cam() {
81+ return { x: cam.x, y: cam.y, zoom: cam.zoom, follow: cam.follow };
82+ },
83+ get state() {
84+ return state;
85+ },
86+ get pointer() {
87+ return pointer;
88+ },
89+ canvas: canvasBox,
90+ cellOf,
91+ toScreen: screen,
92+ toWorld: (px: number, py: number) => at({ clientX: px, clientY: py } as MouseEvent),
93+ targets,
94+};
95+declare global {
96+ interface Window {
97+ __game: typeof game;
98+ }
99+}
100+
101+// Called once the view exists: the dev build needs it to draw the pointer it owns.
102+export function install(v: View): void {
103+ if (!label) return;
104+ view = v;
105+ label.id = 'dev';
106+ document.body.append(label);
107+ window.__game = game;
108+}
109+
110+// Drawn every move: the reticle in cells, and one line of text spelling out the
111+// cell, the world point and the thing under it.
112+export function aim(e: MouseEvent): void {
113+ const c = cellOf(e.clientX, e.clientY);
114+ const w = at(e);
115+ pointer = { px: e.clientX, py: e.clientY, ...c, world: w };
116+ if (!label || !view) return;
117+ view.setPointer(c.cellX, c.cellY);
118+ const hit = targets().find((t) => t.cellX === c.cellX && t.cellY === c.cellY);
119+ label.textContent =
120+ `cell ${c.cellX},${c.cellY} world ${Math.round(w.x)},${Math.round(w.y)} px ${Math.round(e.clientX)},${Math.round(e.clientY)}` +
121+ (hit ? `\n${hit.kind} ${hit.id}` : '');
122+}
@@ -0,0 +1,72 @@
1+// Intents: every pointer and key here becomes a message for the server, and the
2+// server decides what happened. The only local decisions are the camera's.
3+import { aim } from './dev';
4+import { at, cam, pan, wpc, wpp, zoomAt } from './stage';
5+import { send } from './world';
6+
7+const keys = new Set<string>();
8+let pan0: { x: number; y: number } | null = null; // right/middle drag moves the camera
9+let pulling = false; // left button down: keep reporting where the piece is
10+let pullTo: { x: number; y: number } | null = null;
11+let pullIn = 0;
12+
13+export function bind(): void {
14+ addEventListener('pointerdown', (e) => {
15+ aim(e);
16+ if (e.button !== 0) {
17+ pan0 = { x: e.clientX, y: e.clientY };
18+ return;
19+ }
20+ const p = at(e);
21+ pulling = true;
22+ send({ t: 'pick', x: p.x, y: p.y });
23+ });
24+
25+ addEventListener('pointermove', (e) => {
26+ aim(e);
27+ if (pan0) {
28+ pan(-(e.clientX - pan0.x) * wpp(), (e.clientY - pan0.y) * wpp());
29+ pan0 = { x: e.clientX, y: e.clientY };
30+ return;
31+ }
32+ if (!pulling) return;
33+ pullTo = at(e);
34+ });
35+
36+ addEventListener('pointerup', (e) => {
37+ if (e.button !== 0) {
38+ pan0 = null;
39+ return;
40+ }
41+ if (!pulling) return;
42+ pulling = false;
43+ pullTo = null;
44+ const p = at(e);
45+ send({ t: 'drop', x: p.x, y: p.y });
46+ });
47+ addEventListener('contextmenu', (e) => e.preventDefault());
48+
49+ addEventListener('wheel', (e) => zoomAt(e));
50+
51+ addEventListener('keydown', (e) => {
52+ keys.add(e.code);
53+ if (e.code === 'Space') cam.follow = true;
54+ });
55+ addEventListener('keyup', (e) => keys.delete(e.code));
56+}
57+
58+// Per frame: pan on screen-space speed so it feels the same at every zoom, and
59+// report a drag no faster than the server needs it.
60+export function step(dt: number): void {
61+ const px = (keys.has('KeyD') || keys.has('ArrowRight') ? 1 : 0) - (keys.has('KeyA') || keys.has('ArrowLeft') ? 1 : 0);
62+ const py = (keys.has('KeyW') || keys.has('ArrowUp') ? 1 : 0) - (keys.has('KeyS') || keys.has('ArrowDown') ? 1 : 0);
63+ if (px || py) {
64+ const s = (30 * wpc() * dt) / Math.hypot(px, py); // 30 cells / second
65+ pan(px * s, py * s);
66+ }
67+ if (pullTo && (pullIn += dt) > 1 / 30) {
68+ pullIn = 0;
69+ send({ t: 'drag', x: pullTo.x, y: pullTo.y });
70+ pullTo = null;
71+ }
72+}
@@ -1,232 +1,15 @@
1-import { connect, type State } from './net';
2-import { toWorld, type Loose, type Ore, type Ship, type Shot } from './sim';
3-import { View, CELL, CELL_WORLD, ZOOM_MIN, ZOOM_MAX, type Camera } from './view';
1+// Space Browser, the game. The client draws what the server sends and asks for
2+// nothing else: this file is only the wiring, and the one loop that eases and draws.
3+import { install } from './dev';
4+import { bind, step } from './input';
5+import { cam, canvas } from './stage';
6+import { View } from './view';
7+import { apply, follow, loose, ore, own, shots, ships, state } from './world';
48
5-const canvas = document.getElementById('view') as HTMLCanvasElement;
69 const view = new View(canvas);
710 addEventListener('resize', () => view.resize());
8-
9-const cam: Camera & { follow: boolean } = { x: 0, y: 0, zoom: ZOOM_MIN, follow: true };
10-
11-// Everything drawn comes from the server. We only send intents: pick up what is
12-// under the cursor, report the drag, drop it and let the server decide.
13-let state: State | null = null;
14-const net = connect((s) => {
15- const was = state?.you;
16- state = s;
17- const me = s.players.find((p) => p.id === s.you);
18- // A ship we have never followed (the first, or the one we come back as) puts the
19- // camera on it at once, so a death never slides the view across the system.
20- if (me && s.you !== was) {
21- cam.x = me.x;
22- cam.y = me.y;
23- }
24-});
25-
26-// The server reports at tick rate; we ease our copies toward it so movement reads
27-// smooth without ever deciding anything ourselves.
28-const ships = new Map<number, Ship>();
29-const loose = new Map<number, Loose>();
30-const ore = new Map<number, Ore>();
31-const shots = new Map<number, Shot>();
32-
33-const keys = new Set<string>();
34-let pan0: { x: number; y: number } | null = null; // right/middle drag moves the camera
35-let pulling = false; // left button down: keep reporting where the piece is
36-let pullTo: { x: number; y: number } | null = null;
37-let pullIn = 0;
38-
39-const wpc = () => CELL_WORLD / cam.zoom; // world units per character cell
40-const wpp = () => wpc() / CELL; // world units per css px
41-const pan = (dx: number, dy: number) => {
42- cam.x += dx;
43- cam.y += dy;
44- cam.follow = false;
45-};
46-const at = (e: MouseEvent) => {
47- const r = canvas.getBoundingClientRect(); // the camera is centered on the canvas, not the window
48- return {
49- x: cam.x + (e.clientX - r.left - r.width / 2) * wpp(),
50- y: cam.y - (e.clientY - r.top - r.height / 2) * wpp(), // screen y points down, world y up
51- };
52-};
53-
54-// An agent driving this page sees no cursor and cannot know where the camera is,
55-// so it gets the transform the game itself uses, never a copy of it: world point
56-// to screen pixel, screen pixel to world point, and every clickable thing already
57-// converted. It also gets the pointer drawn in cells, because a screenshot cannot
58-// show the browser's own cursor.
59-type Target = {
60- id: number;
61- kind: string; // me, ship, piece, loose, ore, or a body kind
62- owner: number; // the hull a piece belongs to, 0 for anything loose
63- x: number;
64- y: number;
65- px: number;
66- py: number;
67- cellX: number;
68- cellY: number;
69- cellPx: number; // the centre of that cell: a click lands on a glyph, not between four
70- cellPy: number;
71- d: number; // world distance from your hull, nearest first
72-};
73-
74-// The canvas box and the world<->screen transform, read once per use: a layout read
75-// per target would make the pointer cost a forced reflow for every thing on screen.
76-const boxOf = (r: DOMRect) => ({
77- left: r.left,
78- top: r.top,
79- width: r.width,
80- height: r.height,
81- cell: CELL,
82- cols: r.width / CELL,
83- rows: r.height / CELL,
84-});
85-const canvasBox = () => boxOf(canvas.getBoundingClientRect());
86-const cellOf = (px: number, py: number, r = canvas.getBoundingClientRect()) => ({
87- cellX: Math.floor((px - r.left) / CELL),
88- cellY: Math.floor((py - r.top) / CELL),
89-});
90-const screenOf = (r: DOMRect, x: number, y: number) => ({
91- px: r.left + r.width / 2 + (x - cam.x) / wpp(),
92- py: r.top + r.height / 2 - (y - cam.y) / wpp(),
93-});
94-const screen = (x: number, y: number) => screenOf(canvas.getBoundingClientRect(), x, y);
95-
96-const targets = (): Target[] => {
97- const me = ships.get(state?.you ?? 0);
98- const r = canvas.getBoundingClientRect();
99- const box = boxOf(r);
100- const out: Target[] = [];
101- const add = (id: number, kind: string, owner: number, x: number, y: number) => {
102- const s = screenOf(r, x, y);
103- const c = cellOf(s.px, s.py, r);
104- out.push({
105- id,
106- kind,
107- owner,
108- x,
109- y,
110- px: s.px,
111- py: s.py,
112- ...c,
113- cellPx: box.left + (c.cellX + 0.5) * CELL,
114- cellPy: box.top + (c.cellY + 0.5) * CELL,
115- d: me ? Math.hypot(x - me.x, y - me.y) : 0,
116- });
117- };
118- for (const s of ships.values()) {
119- add(s.id, s.id === state?.you ? 'me' : 'ship', 0, s.x, s.y);
120- for (const p of s.pieces) {
121- const w = toWorld(s, p);
122- add(p.id, 'piece', s.id, w.x, w.y);
123- }
124- }
125- for (const l of loose.values()) add(l.id, 'loose', 0, l.x, l.y);
126- for (const o of ore.values()) add(o.id, 'ore', 0, o.x, o.y);
127- for (const b of state?.bodies ?? []) add(b.id, b.kind, 0, b.x, b.y);
128- return out.sort((a, b) => a.d - b.d);
129-};
130-
131-let pointer: { px: number; py: number; cellX: number; cellY: number; world: { x: number; y: number } } | null = null;
132-const dev = import.meta.env.DEV; // the bridge and the drawn cursor are for testing only
133-const label = dev ? document.createElement('pre') : null;
134-if (label) {
135- label.id = 'dev';
136- document.body.append(label);
137-}
138-
139-// Drawn every move: the reticle in cells, and one line of text spelling out the
140-// cell, the world point and the thing under it.
141-const aim = (e: MouseEvent) => {
142- const c = cellOf(e.clientX, e.clientY);
143- const w = at(e);
144- pointer = { px: e.clientX, py: e.clientY, ...c, world: w };
145- if (!label) return;
146- view.setPointer(c.cellX, c.cellY);
147- const hit = targets().find((t) => t.cellX === c.cellX && t.cellY === c.cellY);
148- label.textContent =
149- `cell ${c.cellX},${c.cellY} world ${Math.round(w.x)},${Math.round(w.y)} px ${Math.round(e.clientX)},${Math.round(e.clientY)}` +
150- (hit ? `\n${hit.kind} ${hit.id}` : '');
151-};
152-
153-const game = {
154- get cam() {
155- return { x: cam.x, y: cam.y, zoom: cam.zoom, follow: cam.follow };
156- },
157- get state() {
158- return state;
159- },
160- get pointer() {
161- return pointer;
162- },
163- canvas: canvasBox,
164- cellOf,
165- toScreen: screen,
166- toWorld: (px: number, py: number) => at({ clientX: px, clientY: py } as MouseEvent),
167- targets,
168-};
169-declare global {
170- interface Window {
171- __game: typeof game;
172- }
173-}
174-if (dev) window.__game = game;
175-
176-addEventListener('pointerdown', (e) => {
177- aim(e);
178- if (e.button !== 0) {
179- pan0 = { x: e.clientX, y: e.clientY };
180- return;
181- }
182- const p = at(e);
183- pulling = true;
184- net.send({ t: 'pick', x: p.x, y: p.y });
185-});
186-
187-addEventListener('pointermove', (e) => {
188- aim(e);
189- if (pan0) {
190- pan(-(e.clientX - pan0.x) * wpp(), (e.clientY - pan0.y) * wpp());
191- pan0 = { x: e.clientX, y: e.clientY };
192- return;
193- }
194- if (!pulling) return;
195- pullTo = at(e);
196-});
197-
198-addEventListener('pointerup', (e) => {
199- if (e.button !== 0) {
200- pan0 = null;
201- return;
202- }
203- if (!pulling) return;
204- pulling = false;
205- pullTo = null;
206- const p = at(e);
207- net.send({ t: 'drop', x: p.x, y: p.y });
208-});
209-addEventListener('contextmenu', (e) => e.preventDefault());
210-
211-// Zoom is multiplicative and anchored on the world point under the cursor.
212-addEventListener('wheel', (e) => {
213- const a = at(e);
214- const z = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, cam.zoom * Math.exp(-e.deltaY * 0.0015)));
215- if (z === cam.zoom) return;
216- cam.zoom = z;
217- const b = at(e);
218- cam.x += a.x - b.x;
219- cam.y += a.y - b.y;
220-});
221-
222-addEventListener('keydown', (e) => {
223- keys.add(e.code);
224- if (e.code === 'Space') cam.follow = true;
225-});
226-addEventListener('keyup', (e) => keys.delete(e.code));
227-
228-const ease = (a: number, b: number, k: number) => a + (b - a) * k;
229-const turn = (a: number, b: number, k: number) => a + Math.atan2(Math.sin(b - a), Math.cos(b - a)) * k;
11+if (import.meta.env.DEV) install(view); // the dev bridge needs the view to draw the pointer
12+bind();
23013
23114 let last = performance.now();
23215 function frame(): void {
@@ -234,86 +17,12 @@ function frame(): void {
23417 const dt = Math.min(0.05, Math.max(0, now - last) / 1000);
23518 last = now;
23619
237- // Pan on screen-space speed so it feels the same at every zoom.
238- const px = (keys.has('KeyD') || keys.has('ArrowRight') ? 1 : 0) - (keys.has('KeyA') || keys.has('ArrowLeft') ? 1 : 0);
239- const py = (keys.has('KeyW') || keys.has('ArrowUp') ? 1 : 0) - (keys.has('KeyS') || keys.has('ArrowDown') ? 1 : 0);
240- if (px || py) {
241- const s = (30 * wpc() * dt) / Math.hypot(px, py); // 30 cells / second
242- pan(px * s, py * s);
243- }
244-
245- if (pullTo && (pullIn += dt) > 1 / 30) {
246- pullIn = 0;
247- net.send({ t: 'drag', x: pullTo.x, y: pullTo.y });
248- pullTo = null;
249- }
250-
251- const k = 1 - Math.exp(-dt * 12);
252- if (state) {
253- const live = new Set<number>();
254- for (const p of state.players) {
255- live.add(p.id);
256- let s = ships.get(p.id);
257- if (!s) {
258- ships.set(p.id, (s = { ...p }));
259- } else {
260- s.x = ease(s.x, p.x, k);
261- s.y = ease(s.y, p.y, k);
262- s.h = turn(s.h, p.h, k);
263- s.tx = p.tx;
264- s.ty = p.ty;
265- s.fuel = p.fuel; // a gauge has to jump, not ease, or it lies about the tank
266- s.fuelmax = p.fuelmax;
267- s.foe = p.foe;
268- s.pieces = p.pieces; // a hull is never eased: a piece is where the server says
269- }
270- }
271- for (const id of ships.keys()) if (!live.has(id)) ships.delete(id);
272-
273- const looseLive = new Set<number>();
274- for (const l of state.loose) {
275- looseLive.add(l.id);
276- const d = loose.get(l.id);
277- if (!d) loose.set(l.id, { ...l });
278- else {
279- d.x = ease(d.x, l.x, k);
280- d.y = ease(d.y, l.y, k);
281- d.h = turn(d.h, l.h, k);
282- }
283- }
284- for (const id of loose.keys()) if (!looseLive.has(id)) loose.delete(id);
285-
286- const oreLive = new Set<number>();
287- for (const o of state.ore) {
288- oreLive.add(o.id);
289- const d = ore.get(o.id);
290- if (!d) ore.set(o.id, { ...o });
291- else {
292- d.x = ease(d.x, o.x, k);
293- d.y = ease(d.y, o.y, k);
294- d.h = turn(d.h, o.h, k);
295- d.towed = o.towed;
296- }
297- }
298- for (const id of ore.keys()) if (!oreLive.has(id)) ore.delete(id);
299-
300- const shotLive = new Set<number>();
301- for (const s of state.shots ?? []) {
302- shotLive.add(s.id);
303- shots.set(s.id, s); // a round is never eased, it is where the server put it
304- }
305- for (const id of shots.keys()) if (!shotLive.has(id)) shots.delete(id);
306- }
307-
308- const me = state ? ships.get(state.you) : undefined;
309- if (cam.follow && me) {
310- const c = 1 - Math.exp(-dt * 8);
311- cam.x = ease(cam.x, me.x, c);
312- cam.y = ease(cam.y, me.y, c);
313- }
20+ step(dt);
21+ apply(dt);
22+ follow(dt);
31423
31524 // The marker is the order the server is flying: never a click of our own.
316- const marker = me && !state?.held ? { x: me.tx, y: me.ty } : null;
25+ const me = own();
31726 view.draw(
31827 cam,
31928 state?.bodies ?? [],
@@ -322,7 +31,7 @@ function frame(): void {
32231 [...shots.values()],
32332 [...loose.values()],
32433 [...ore.values()],
325- marker,
34+ me && !state?.held ? { x: me.tx, y: me.ty } : null,
32635 );
32736 requestAnimationFrame(frame);
32837 }
@@ -0,0 +1,51 @@
1+// The stage: the canvas the game is drawn on, and the camera over it. Anything that
2+// has to turn a world point into a screen pixel, or back, asks here and nowhere else.
3+import { CELL, CELL_WORLD, ZOOM_MAX, ZOOM_MIN, type Camera } from './view';
4+
5+export const canvas = document.getElementById('view') as HTMLCanvasElement;
6+
7+export const cam: Camera & { follow: boolean } = { x: 0, y: 0, zoom: ZOOM_MIN, follow: true };
8+
9+export const wpc = () => CELL_WORLD / cam.zoom; // world units per character cell
10+export const wpp = () => wpc() / CELL; // world units per css px
11+export const rect = () => canvas.getBoundingClientRect();
12+
13+export const pan = (dx: number, dy: number) => {
14+ cam.x += dx;
15+ cam.y += dy;
16+ cam.follow = false;
17+};
18+export const snap = (x: number, y: number) => {
19+ cam.x = x;
20+ cam.y = y;
21+};
22+
23+export const at = (e: { clientX: number; clientY: number }) => {
24+ const r = rect(); // the camera is centered on the canvas, not the window
25+ return {
26+ x: cam.x + (e.clientX - r.left - r.width / 2) * wpp(),
27+ y: cam.y - (e.clientY - r.top - r.height / 2) * wpp(), // screen y points down, world y up
28+ };
29+};
30+
31+export const screenOf = (r: DOMRect, x: number, y: number) => ({
32+ px: r.left + r.width / 2 + (x - cam.x) / wpp(),
33+ py: r.top + r.height / 2 - (y - cam.y) / wpp(),
34+});
35+export const screen = (x: number, y: number) => screenOf(rect(), x, y);
36+
37+export const cellOf = (px: number, py: number, r = rect()) => ({
38+ cellX: Math.floor((px - r.left) / CELL),
39+ cellY: Math.floor((py - r.top) / CELL),
40+});
41+
42+// Zoom is multiplicative and anchored on the world point under the cursor.
43+export const zoomAt = (e: { clientX: number; clientY: number; deltaY: number }) => {
44+ const a = at(e);
45+ const z = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, cam.zoom * Math.exp(-e.deltaY * 0.0015)));
46+ if (z === cam.zoom) return;
47+ cam.zoom = z;
48+ const b = at(e);
49+ cam.x += a.x - b.x;
50+ cam.y += a.y - b.y;
51+};
@@ -1,590 +0,0 @@
1-// The world is a three.js scene drawn at exactly one texel per character cell,
2-// then a single fullscreen pass quantizes it into glyphs of the amber ramp.
3-// Two channels carry the shading: R = luminance (which glyph), G = palette index.
4-import * as THREE from 'three';
5-import { toWorld, type Body, type Kind, type Loose, type Ore, type Ship, type Shot } from './sim';
6-
7-export const CELL = 12; // css px per character cell
8-export const CELL_WORLD = 2; // world units per character cell at zoom 1
9-export const ZOOM_MIN = 0.5; // furthest out: far enough to frame a whole system
10-export const ZOOM_MAX = 1.8; // closest in
11-const SHIP_R = 11; // world radius of a hull
12-const ORE_R = 6.5; // world radius of an ore piece
13-const SHOT_LEN = 13; // world units of laser line behind a round
14-const SHOT_W = 1.6; // world units thick: one bright cell wide
15-const FUEL_CELLS = 12; // the fuel gauge is this many cells wide at any zoom
16-const FUEL_WORD = 'FUEL'; // a word, not glyphs: letters are spelled out per cell
17-
18-export type Camera = { x: number; y: number; zoom: number };
19-
20-// Snap a world point to the centre of the cell that holds it: a one-cell mark has
21-// to land on a glyph, not straddle four of them.
22-const snapCell = (v: number, c: number, wpc: number) => c + (Math.floor((v - c) / wpc) + 0.5) * wpc;
23-
24-const GLYPHS = ' .:-=+*#%@';
25-// 0-7 is the amber ramp used for everything that flies. 8-12 are reserved for
26-// celestial bodies, so a rust planet and a steel planet never read as each other.
27-// 13-14 are damage: a hurt piece can never be mistaken for a healthy one.
28-const PALETTE = [
29- 0x0c0803, 0x241806, 0x3d2709, 0x57370c, 0x754c11, 0x98631a, 0xc78a20, 0xffe9a8,
30- 0x4a1d0f, 0x9c4f28, 0x1f4453, 0x7fc0d4, 0xfff6dd, 0x7a1512, 0xff4a3d,
31-];
32-const ATLAS_CELL = 32;
33-
34-// R = luminance, G = palette index.
35-const lum = (v: number, idx = 7) => new THREE.Color(v, idx / (PALETTE.length - 1), 0);
36-
37-// One cell of white ink per character, in the same monospace face as the ramp: the
38-// glyph atlas and any hud word are the same kind of texture.
39-function textAtlas(text: string): THREE.Texture {
40- const c = document.createElement('canvas');
41- c.width = text.length * ATLAS_CELL;
42- c.height = ATLAS_CELL;
43- const g = c.getContext('2d')!;
44- g.font = `700 ${ATLAS_CELL - 1}px ui-monospace, SFMono-Regular, Menlo, monospace`;
45- g.textAlign = 'center';
46- g.textBaseline = 'middle';
47- g.fillStyle = '#fff';
48- for (let i = 0; i < text.length; i++) {
49- g.fillText(text[i], i * ATLAS_CELL + ATLAS_CELL / 2, ATLAS_CELL / 2);
50- }
51- const t = new THREE.CanvasTexture(c);
52- t.minFilter = t.magFilter = THREE.LinearFilter;
53- t.generateMipmaps = false;
54- return t;
55-}
56-
57-function paletteTexture(): THREE.DataTexture {
58- const d = new Uint8Array(PALETTE.length * 4);
59- PALETTE.forEach((hex, i) => d.set([(hex >> 16) & 255, (hex >> 8) & 255, hex & 255, 255], i * 4));
60- const t = new THREE.DataTexture(d, PALETTE.length, 1, THREE.RGBAFormat);
61- t.minFilter = t.magFilter = THREE.NearestFilter;
62- t.needsUpdate = true;
63- return t;
64-}
65-
66-const VERT = /* glsl */ `void main() { gl_Position = vec4(position.xy, 0.0, 1.0); }`;
67-
68-const FRAG = /* glsl */ `
69-uniform sampler2D uScene;
70-uniform sampler2D uAtlas;
71-uniform sampler2D uPalette;
72-uniform vec3 uBg;
73-uniform vec2 uCells;
74-uniform float uCellPx;
75-uniform sampler2D uWord; // hud ink, in cells, drawn over the glyphs
76-uniform vec4 uWordCell; // x, y, width, height of the word, in cells from the corner
77-uniform vec3 uWordCol;
78-
79-void main() {
80- vec2 uv = gl_FragCoord.xy / uCellPx;
81- vec3 s = texture2D(uScene, (floor(uv) + 0.5) / uCells).rgb;
82- float band = floor(s.r * ${GLYPHS.length - 1}.0 + 0.5);
83- vec3 col = texture2D(uPalette, vec2((s.g * ${PALETTE.length - 1}.0 + 0.5) / ${PALETTE.length}.0, 0.5)).rgb;
84- vec2 local = clamp(fract(uv), 0.02, 0.98);
85- float ink = texture2D(uAtlas, vec2((band + local.x) / ${GLYPHS.length}.0, local.y)).a;
86- vec3 outCol = mix(uBg, col, ink);
87- vec2 w = (uv - uWordCell.xy) / uWordCell.zw;
88- if (w.x >= 0.0 && w.x < 1.0 && w.y >= 0.0 && w.y < 1.0) {
89- outCol = mix(outCol, uWordCol, texture2D(uWord, w).a);
90- }
91- gl_FragColor = vec4(outCol, 1.0);
92-}
93-`;
94-
95-// Polygon of n points on a circle of radius r. Every piece kind has the same
96-// footprint so slots pack the hull evenly.
97-function poly(n: number, r: number, inner = 0, tilt = 0): THREE.Shape {
98- const s = new THREE.Shape();
99- for (let i = 0; i < n; i++) {
100- const a = tilt + (i * Math.PI * 2) / n;
101- const rr = inner && i % 2 ? inner : r;
102- const x = Math.cos(a) * rr;
103- const y = Math.sin(a) * rr;
104- if (i) s.lineTo(x, y);
105- else s.moveTo(x, y);
106- }
107- s.closePath();
108- return s;
109-}
110-
111-// The four piece kinds are named after their shape. Geometry is identical for every
112-// piece of a kind at a scale, so it is built once and shared; only the materials are
113-// per piece, because a piece's colours are its state.
114-const shapes = new Map<string, THREE.BufferGeometry>();
115-function pieceGeometry(kind: Kind, scale: number): THREE.BufferGeometry {
116- const key = `${kind}:${scale}`;
117- let g = shapes.get(key);
118- if (!g) shapes.set(key, (g = buildPiece(kind, SHIP_R * scale)));
119- return g;
120-}
121-
122-function buildPiece(kind: Kind, r: number): THREE.BufferGeometry {
123- if (kind === 'square') return new THREE.ShapeGeometry(poly(4, r * 0.8, 0, Math.PI / 4));
124- if (kind === 'circle') return new THREE.CircleGeometry(r * 0.75, 18);
125- if (kind === 'star') return new THREE.ShapeGeometry(poly(10, r, r * 0.45, -Math.PI / 2));
126- return new THREE.ShapeGeometry(poly(3, r));
127-}
128-
129-// A removed mesh hands its materials back: the geometry is shared and cached, but
130-// every piece owns the colours that say what it is.
131-function free(o: THREE.Object3D): void {
132- o.traverse((m) => ((m as THREE.Mesh).material as THREE.Material | undefined)?.dispose());
133-}
134-
135-// A plate of a given size is always the same quad, so it is shared: a piece, a shot
136-// or a ray only ever needs its own colour, and a removed mesh only gives that back.
137-const quads = new Map<string, THREE.PlaneGeometry>();
138-function plate(w: number, h: number, v: number): THREE.Mesh<THREE.PlaneGeometry, THREE.MeshBasicMaterial> {
139- const key = `${w}:${h}`;
140- let g = quads.get(key);
141- if (!g) quads.set(key, (g = new THREE.PlaneGeometry(w, h)));
142- return new THREE.Mesh(g, new THREE.MeshBasicMaterial({ color: lum(v) }));
143-}
144-
145-// A piece is a bright silhouette with a dimmer inset plate, so the cel shading
146-// survives the downsample to cell resolution. Three roles must never read as
147-// each other: your hull is the brightest cream, another player's hull is gold,
148-// and loose wreckage is dim sepia. A piece flips shade the moment it is bolted
149-// on or torn off, and turns red for everyone once it starts taking hits.
150-const SHADE = {
151- own: [lum(1, 7), lum(0.5, 7)],
152- other: [lum(0.8, 6), lum(0.4, 6)],
153- loose: [lum(0.55, 5), lum(0.28, 5)],
154- ore: [lum(0.95, 6), lum(0.5, 4)], // ore in a planet's ring
155- towed: [lum(1, 7), lum(0.55, 6)], // ore on someone's line, bright as a hull
156-};
157-export type Role = keyof typeof SHADE;
158-const HURT = [
159- [lum(0.85, 13), lum(0.4, 13)], // hit: rust red
160- [lum(1, 14), lum(0.5, 14)], // nearly gone: hot red
161-];
162-// Upgrade tiers wear a border: gold at one, cream at two. Nothing at zero.
163-const TIER = [lum(0, 0), lum(1, 6), lum(1, 12)];
164-
165-type Part = THREE.Mesh<THREE.BufferGeometry, THREE.MeshBasicMaterial>;
166-
167-const shade = (g: THREE.Group, role: Role) => {
168- const c = SHADE[role];
169- g.children.forEach((m, i) => (m as Part).material.color.copy(c[i]));
170-};
171-
172-// What a piece looks like is entirely its health, its tier and whether the ship it
173-// belongs to is hostile to us. A hostile hull wears a strong red rim, which is a
174-// statement about the ship, not damage to it.
175-type Wear = { hp: number; maxhp: number; tier: number };
176-function paint(g: THREE.Group, role: Role, w: Wear, hostile: boolean): void {
177- const ratio = w.maxhp > 0 ? w.hp / w.maxhp : 1;
178- const [hi, lo] = ratio > 0.66 ? SHADE[role] : ratio > 0.33 ? HURT[0] : HURT[1];
179- const [rim, edge, a, b] = g.children as Part[]; // built in this order
180- rim.visible = hostile;
181- if (hostile) rim.material.color.copy(HURT[1][0]); // the rim of an enemy
182- a.material.color.copy(hi);
183- b.material.color.copy(lo);
184- edge.visible = w.tier > 0 && !hostile; // the rim already says more than a tier
185- if (edge.visible) edge.material.color.copy(TIER[w.tier]);
186-}
187-
188-// The tier border is a larger copy of the same shape drawn first, so the
189-// silhouette covers its middle and only a rim of it shows. A hostile hull gets a
190-// second, fatter copy outside that, so an enemy reads as a strong red border even
191-// when a cell is several world units wide.
192-function piece(kind: Kind): THREE.Group {
193- const g = new THREE.Group();
194- for (const [scale, v] of [[1.9, 0], [1.3, 0], [1, 1], [0.7, 0.5]]) {
195- g.add(new THREE.Mesh(pieceGeometry(kind, scale), new THREE.MeshBasicMaterial({ color: lum(v) })));
196- }
197- return g;
198-}
199-
200-// Ore is a small faceted chunk: a hexagon with a darker core, the one thing in
201-// space that is neither a ship piece nor a body.
202-const ORE_SHELL = new THREE.ShapeGeometry(poly(6, ORE_R));
203-const ORE_CORE = new THREE.ShapeGeometry(poly(6, ORE_R * 0.55, 0, 0.4));
204-function oreChunk(): THREE.Group {
205- const g = new THREE.Group();
206- g.add(new THREE.Mesh(ORE_SHELL, new THREE.MeshBasicMaterial({ color: SHADE.ore[0] })));
207- g.add(new THREE.Mesh(ORE_CORE, new THREE.MeshBasicMaterial({ color: SHADE.ore[1] })));
208- shade(g, 'ore');
209- return g;
210-}
211-
212-// A click target: a plus of 5 cells, bright enough to read past the dust.
213-function crosshair(): THREE.Group {
214- const g = new THREE.Group();
215- for (const [dx, dy] of [[0, 0], [1, 0], [-1, 0], [0, 1], [0, -1]]) {
216- const p = plate(CELL_WORLD * 1.25, CELL_WORLD * 1.25, dx || dy ? 0.75 : 1);
217- p.position.set(dx * CELL_WORLD, dy * CELL_WORLD, 0);
218- g.add(p);
219- }
220- g.position.z = 0.5;
221- return g;
222-}
223-
224-// The dev cursor: a ring of cells around the pointer cell, one cell per plate. The
225-// browser never paints its own pointer into a screenshot, so the game draws one
226-// that lands on the exact cell a click will resolve to. It is a ring and not a
227-// plus, so it can never be read as the order marker the ship is flying to.
228-function reticle(): THREE.Group {
229- const g = new THREE.Group();
230- for (const dx of [-1, 0, 1]) {
231- for (const dy of [-1, 0, 1]) {
232- if (!dx && !dy) continue;
233- const p = plate(0.8, 0.8, 1);
234- p.material.color.copy(lum(0.85, 6));
235- p.position.set(dx, dy, 0);
236- g.add(p);
237- }
238- }
239- g.position.z = 1; // over the fuel gauge
240- return g;
241-}
242-
243-const disk = (r: number, v: number, idx: number, x = 0, y = 0): THREE.Mesh => {
244- const m = new THREE.Mesh(
245- new THREE.CircleGeometry(r, 48),
246- new THREE.MeshBasicMaterial({ color: lum(v, idx) }),
247- );
248- m.position.set(x, y, 0);
249- return m;
250-};
251-
252-// A lit limb: the bright edge that makes a disk pop off the black.
253-const limb = (r: number, v: number, idx: number): THREE.Mesh =>
254- new THREE.Mesh(
255- new THREE.RingGeometry(r * 0.88, r, 64),
256- new THREE.MeshBasicMaterial({ color: lum(v, idx), side: THREE.DoubleSide }),
257- );
258-
259-// A star reads as a hot core with long rays, so it can never be mistaken for a
260-// planet at any zoom: it is the only thing in the scene that shines.
261-function starMesh(r: number): THREE.Group {
262- const g = new THREE.Group();
263- g.add(disk(r, 0.8, 6));
264- g.add(disk(r * 0.62, 1, 7));
265- g.add(disk(r * 0.3, 1, 12));
266- const rays = new THREE.Group();
267- for (let i = 0; i < 8; i++) {
268- const a = (i / 8) * Math.PI * 2;
269- const len = (i % 2 ? 0.5 : 0.9) * r;
270- const m = plate(r * 0.24, len, 0.7);
271- (m.material as THREE.MeshBasicMaterial).color.copy(lum(0.6, 6));
272- m.position.set(Math.cos(a) * (r * 0.8 + len / 2), Math.sin(a) * (r * 0.8 + len / 2), 0);
273- m.rotation.z = a - Math.PI / 2;
274- rays.add(m);
275- }
276- g.add(rays);
277- return g;
278-}
279-
280-// A barren planet: a rust disk lit from one side, with craters punched out of it.
281-// These are the ore bodies of the galaxy.
282-function barrenMesh(r: number): THREE.Group {
283- const g = new THREE.Group();
284- g.add(disk(r, 0.7, 9));
285- g.add(limb(r, 1, 9));
286- for (const [dx, dy, cr] of [[0.3, 0.28, 0.34], [-0.12, 0.5, 0.2], [0.36, -0.34, 0.16]]) {
287- g.add(disk(r * cr, 0.3, 8, dx * r, dy * r)); // craters
288- }
289- return g;
290-}
291-
292-// A shipyard planet: cool steel, a lit cap, and a cream ring studded with gold
293-// docks. It is the only body in the system with anything bolted around it.
294-function shipyardMesh(r: number): THREE.Group {
295- const g = new THREE.Group();
296- g.add(disk(r, 0.55, 10));
297- g.add(disk(r * 0.82, 0.9, 11, -r * 0.07, r * 0.09));
298- // The berth ring floats clear of the hull: a station, not a moon.
299- const ring = new THREE.Mesh(
300- new THREE.RingGeometry(r * 1.18, r * 1.38, 64),
301- new THREE.MeshBasicMaterial({ color: lum(1, 12), side: THREE.DoubleSide }),
302- );
303- g.add(ring);
304- for (let i = 0; i < 4; i++) {
305- const a = (i / 4) * Math.PI * 2 + Math.PI / 4;
306- const d = plate(r * 0.34, r * 0.34, 1);
307- (d.material as THREE.MeshBasicMaterial).color.copy(lum(1, 7));
308- d.position.set(Math.cos(a) * r * 1.5, Math.sin(a) * r * 1.5, 0.06);
309- d.rotation.z = a;
310- g.add(d);
311- }
312- return g;
313-}
314-
315-export class View {
316- private renderer: THREE.WebGLRenderer;
317- private scene = new THREE.Scene();
318- private camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 100);
319- private rt: THREE.WebGLRenderTarget;
320- private pass: THREE.ShaderMaterial;
321- private quad = new THREE.Scene();
322- private pieceMeshes = new Map<number, THREE.Group>();
323- private oreMeshes = new Map<number, THREE.Group>();
324- private shotMeshes = new Map<number, Part>();
325- private bodyMeshes = new Map<number, THREE.Group>();
326- private marker = crosshair();
327- private cursor = reticle();
328- private hud = new THREE.Scene();
329- private hudCam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 100);
330- private fuelBar = new THREE.Group();
331- private fuelCells: Part[] = [];
332- private cols = 0;
333- private rows = 0;
334-
335- constructor(private canvas: HTMLCanvasElement) {
336- THREE.ColorManagement.enabled = false;
337- this.renderer = new THREE.WebGLRenderer({ canvas, antialias: false });
338- this.renderer.outputColorSpace = THREE.LinearSRGBColorSpace;
339- this.scene.add(this.marker);
340- // The fuel gauge is geometry in a HUD layer, not a page overlay: it is built
341- // from the same cells as everything else, so it reads as part of the game,
342- // and it is measured in cells rather than in the world, so flying cannot make
343- // it hop from one cell to the next.
344- this.hudCam.position.z = 10;
345- this.hud.add(this.fuelBar);
346- this.cursor.visible = false;
347- this.hud.add(this.cursor);
348- for (let i = 0; i < FUEL_CELLS; i++) {
349- const m = plate(1, 1, 1);
350- this.fuelCells.push(m);
351- this.fuelBar.add(m);
352- }
353- this.rt = new THREE.WebGLRenderTarget(1, 1, {
354- samples: 4,
355- depthBuffer: false,
356- stencilBuffer: false,
357- minFilter: THREE.LinearFilter,
358- magFilter: THREE.LinearFilter,
359- });
360- this.pass = new THREE.ShaderMaterial({
361- vertexShader: VERT,
362- fragmentShader: FRAG,
363- uniforms: {
364- uScene: { value: this.rt.texture },
365- uAtlas: { value: textAtlas(GLYPHS) },
366- uPalette: { value: paletteTexture() },
367- uBg: { value: new THREE.Color(PALETTE[0]) },
368- uCells: { value: new THREE.Vector2() },
369- uCellPx: { value: CELL },
370- uWord: { value: textAtlas(FUEL_WORD) },
371- uWordCell: { value: new THREE.Vector4() },
372- uWordCol: { value: new THREE.Color(PALETTE[5]) },
373- },
374- });
375- const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), this.pass);
376- quad.frustumCulled = false;
377- this.quad.add(quad);
378- this.resize();
379- }
380-
381- // Built once: a body keeps an identity for the whole run, only its place moves.
382- private bodies(bs: Body[], t: number): void {
383- const seen = new Set<number>();
384- for (const b of bs) {
385- seen.add(b.id);
386- let m = this.bodyMeshes.get(b.id);
387- if (!m) {
388- m = b.kind === 'star' ? starMesh(b.r) : b.kind === 'shipyard' ? shipyardMesh(b.r) : barrenMesh(b.r);
389- m.position.z = -1;
390- m.userData.spin = b.kind === 'star' ? 0.08 : 0.15; // slow enough to read as alive
391- this.scene.add(m);
392- this.bodyMeshes.set(b.id, m);
393- }
394- m.position.set(b.x, b.y, -1);
395- m.rotation.z = t * m.userData.spin;
396- }
397- for (const [id, m] of this.bodyMeshes) {
398- if (seen.has(id)) continue;
399- free(m);
400- this.scene.remove(m);
401- this.bodyMeshes.delete(id);
402- }
403- }
404-
405- resize(): void {
406- // Whole cells only: the canvas, the frustum and the glyph grid must describe
407- // the same rectangle, or world positions land half a cell off their glyph.
408- const dpr = Math.min(devicePixelRatio, 2);
409- this.cols = Math.max(1, Math.floor(innerWidth / CELL));
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.