space-browser / commits / f2fbe78
feat: other shapes and ship composition
- All shapes. - Grab, drag, attach around ship pieces
@@ -1,5 +1,16 @@
11 import { connect, type Remote } from './net';
2-import { makeShip, step, type Ship } from './sim';
2+import {
3+ attach,
4+ detach,
5+ nextPieceId,
6+ toWorld,
7+ GRAB,
8+ makeShip,
9+ step,
10+ type Loose,
11+ type Piece,
12+ type Ship,
13+} from './sim';
314 import { View, CELL, CELL_WORLD, ZOOM_MIN, ZOOM_MAX, type Camera } from './view';
415
516 const canvas = document.getElementById('view') as HTMLCanvasElement;
@@ -8,6 +19,14 @@ addEventListener('resize', () => view.resize());
819
920 const own = makeShip(0, '', 0, 0);
1021 const others = new Map<number, Ship>();
22+// A few pieces lying around the spawn, to build onto the starting triangle.
23+const loose: Loose[] = [
24+ { id: nextPieceId(), kind: 'armor', x: 30, y: -20, h: 0 },
25+ { id: nextPieceId(), kind: 'cargo', x: 37, y: 18, h: 0 },
26+ { id: nextPieceId(), kind: 'engine', x: -29, y: 26, h: 0 },
27+ { id: nextPieceId(), kind: 'gun', x: -35, y: -22, h: 0 },
28+];
29+let held: Loose | null = null;
1130 let marker: { x: number; y: number } | null = null;
1231 const cam: Camera & { follow: boolean } = { x: 0, y: 0, zoom: 1, follow: true };
1332 const keys = new Set<string>();
@@ -31,9 +50,14 @@ const at = (e: MouseEvent) => {
3150
3251 const net = connect(
3352 (w) => {
53+ if (own.id) return; // spawn once
3454 own.id = w.id;
3555 own.name = w.name;
3656 own.x = own.tx = (w.id - 1) * 40;
57+ for (const l of loose) {
58+ l.x += own.x; // the wreckage lies where we wake up
59+ l.y += own.y;
60+ }
3761 marker = null;
3862 },
3963 (players: Remote[]) => {
@@ -42,7 +66,8 @@ const net = connect(
4266 if (p.id === own.id) continue;
4367 const s = others.get(p.id);
4468 if (!s) {
45- others.set(p.id, { ...p, vx: 0, vy: 0, tx: p.x, ty: p.y });
69+ const n = makeShip(p.id, p.name, p.x, p.y);
70+ others.set(p.id, n);
4671 continue;
4772 }
4873 s.tx = p.x;
@@ -53,23 +78,58 @@ const net = connect(
5378 },
5479 );
5580
81+// A piece under the cursor is picked up: loose ones straight off the ground, hull
82+// pieces torn off their ship (with whatever hung below them). Root stays put.
83+function grab(x: number, y: number): Loose | null {
84+ const l = loose.find((l) => Math.hypot(l.x - x, l.y - y) < GRAB);
85+ if (l) return l;
86+ let hit: Piece | null = null;
87+ let best = GRAB;
88+ for (const p of own.pieces) {
89+ const w = toWorld(own, p);
90+ const d = Math.hypot(w.x - x, w.y - y);
91+ if (d < best) {
92+ best = d;
93+ hit = p;
94+ }
95+ }
96+ const off = hit && detach(own, hit.id);
97+ if (!off) return null;
98+ loose.push(...off);
99+ return loose.find((l) => l.id === hit!.id)!;
100+}
101+
56102 addEventListener('pointerdown', (e) => {
57103 if (e.button !== 0) {
58104 drag = { x: e.clientX, y: e.clientY };
59105 return;
60106 }
61107 const p = at(e);
108+ held = grab(p.x, p.y);
109+ if (held) return;
62110 own.tx = p.x;
63111 own.ty = p.y;
64112 marker = { x: p.x, y: p.y };
65113 });
66114
67115 addEventListener('pointermove', (e) => {
116+ if (held) {
117+ const p = at(e);
118+ held.x = p.x;
119+ held.y = p.y;
120+ return;
121+ }
68122 if (!drag) return;
69123 pan(-(e.clientX - drag.x) * wpp(), (e.clientY - drag.y) * wpp());
70124 drag = { x: e.clientX, y: e.clientY };
71125 });
72-addEventListener('pointerup', () => (drag = null));
126+addEventListener('pointerup', () => {
127+ drag = null;
128+ if (!held) return;
129+ // Dropped on the hull it bolts on; dropped in space it stays where it lands.
130+ if (attach(own, held)) loose.splice(loose.indexOf(held), 1);
131+ held = null;
132+});
73133 addEventListener('contextmenu', (e) => e.preventDefault());
74134
75135 // Zoom is multiplicative and anchored on the world point under the cursor.
@@ -120,7 +180,7 @@ function frame(): void {
120180 net.send({ t: 'pos', x: own.x, y: own.y, h: own.h });
121181 }
122182
123- view.draw(cam, [own, ...others.values()], own.id, marker);
183+ view.draw(cam, [own, ...others.values()], own.id, loose, marker);
124184 requestAnimationFrame(frame);
125185 }
126186 requestAnimationFrame(frame);
@@ -1,8 +1,19 @@
1-// One ship is one rigid body. Client simulates its own; the server relays.
1+// A ship is a connected graph of pieces that flies as one rigid body.
2+// Client simulates its own; the server relays.
23 const MAX_SPEED = 90; // world units / second
34 const ACCEL = 260;
45 const ARRIVE = 2.2; // slowdown radius factor
56
7+const SLOTS = 6; // attachment directions around a hull piece
8+export const SPACING = 17; // world distance between attached piece centers
9+export const GRAB = 13; // world radius to pick a piece up
10+
11+export type Kind = 'gun' | 'armor' | 'cargo' | 'engine';
12+
13+// Piece position is local to the ship: the graph is rigid, so only the hull moves.
14+export type Piece = { id: number; kind: Kind; lx: number; ly: number; parent: number };
15+export type Loose = { id: number; kind: Kind; x: number; y: number; h: number };
16+
617 export type Ship = {
718 id: number;
819 name: string;
@@ -13,10 +24,80 @@ export type Ship = {
1324 vy: number;
1425 tx: number;
1526 ty: number;
27+ pieces: Piece[]; // pieces[0] is the root
1628 };
1729
30+let pid = 0;
31+export const nextPieceId = () => ++pid;
32+
1833 export function makeShip(id: number, name: string, x: number, y: number): Ship {
19- return { id, name, x, y, h: 0, vx: 0, vy: 0, tx: x, ty: y };
34+ const pieces = [{ id: nextPieceId(), kind: 'gun' as const, lx: 0, ly: 0, parent: 0 }];
35+ return { id, name, x, y, h: 0, vx: 0, vy: 0, tx: x, ty: y, pieces };
36+}
37+
38+export function toWorld(s: Ship, p: Piece): { x: number; y: number } {
39+ const c = Math.cos(s.h);
40+ const n = Math.sin(s.h);
41+ return { x: s.x + p.lx * c - p.ly * n, y: s.y + p.lx * n + p.ly * c };
42+}
43+
44+export function toLocal(s: Ship, x: number, y: number): { x: number; y: number } {
45+ const c = Math.cos(s.h);
46+ const n = Math.sin(s.h);
47+ const dx = x - s.x;
48+ const dy = y - s.y;
49+ return { x: dx * c + dy * n, y: -dx * n + dy * c };
50+}
51+
52+const TAU = Math.PI * 2;
53+const wrap = (a: number) => Math.atan2(Math.sin(a), Math.cos(a));
54+
55+// Snap a dropped piece onto the free slot closest to where it was let go.
56+export function attach(s: Ship, l: Loose): boolean {
57+ const at = toLocal(s, l.x, l.y);
58+ const near = [...s.pieces].sort(
59+ (a, b) => Math.hypot(a.lx - at.x, a.ly - at.y) - Math.hypot(b.lx - at.x, b.ly - at.y),
60+ );
61+ if (Math.hypot(near[0].lx - at.x, near[0].ly - at.y) > SPACING * 1.5) return false; // not dropped on the hull
62+ for (const p of near) {
63+ let slot = -1;
64+ let best = TAU;
65+ for (let i = 0; i < SLOTS; i++) {
66+ const a = (i / SLOTS) * TAU;
67+ const x = p.lx + Math.cos(a) * SPACING;
68+ const y = p.ly + Math.sin(a) * SPACING;
69+ if (s.pieces.some((q) => Math.hypot(q.lx - x, q.ly - y) < SPACING * 0.5)) continue; // slot taken
70+ const d = Math.abs(wrap(a - Math.atan2(at.y - p.ly, at.x - p.lx)));
71+ if (d < best) {
72+ best = d;
73+ slot = i;
74+ }
75+ }
76+ if (slot < 0) continue; // piece is surrounded, try the next one out
77+ const a = (slot / SLOTS) * TAU;
78+ s.pieces.push({ id: l.id, kind: l.kind, lx: p.lx + Math.cos(a) * SPACING, ly: p.ly + Math.sin(a) * SPACING, parent: p.id });
79+ return true;
80+ }
81+ return false;
82+}
83+
84+// Remove a piece and everything hanging off it. The root never detaches; what
85+// comes off is dropped in space at the spot it already occupied.
86+export function detach(s: Ship, id: number): Loose[] | null {
87+ if (s.pieces.length < 2 || s.pieces[0].id === id) return null;
88+ const gone = new Set([id]);
89+ for (let grew = true; grew; ) {
90+ grew = false;
91+ for (const p of s.pieces) {
92+ if (!gone.has(p.id) && gone.has(p.parent)) {
93+ gone.add(p.id);
94+ grew = true;
95+ }
96+ }
97+ }
98+ const out = s.pieces.filter((p) => gone.has(p.id)).map((p) => ({ id: p.id, kind: p.kind, h: s.h, ...toWorld(s, p) }));
99+ s.pieces = s.pieces.filter((p) => !gone.has(p.id));
100+ return out;
20101 }
21102
22103 export function step(s: Ship, dt: number): void {
@@ -2,7 +2,7 @@
22 // then a single fullscreen pass quantizes it into glyphs of the amber ramp.
33 // Two channels carry the shading: R = luminance (which glyph), G = palette index.
44 import * as THREE from 'three';
5-import type { Ship } from './sim';
5+import { toWorld, type Kind, type Loose, type Ship } from './sim';
66
77 export const CELL = 12; // css px per character cell
88 export const CELL_WORLD = 2; // world units per character cell at zoom 1
@@ -67,26 +67,54 @@ void main() {
6767 }
6868 `;
6969
70-// One hull is a bright triangle with a dimmer plate inset, so the cel shading
71-// survives the downsample to cell resolution.
72-function hullGeometry(scale: number): THREE.ShapeGeometry {
70+// Polygon of n points on a circle of radius r. Every piece kind has the same
71+// footprint so slots pack the hull evenly.
72+function poly(n: number, r: number, inner = 0, tilt = 0): THREE.Shape {
73+ const s = new THREE.Shape();
74+ for (let i = 0; i < n; i++) {
75+ const a = tilt + (i * Math.PI * 2) / n;
76+ const rr = inner && i % 2 ? inner : r;
77+ const x = Math.cos(a) * rr;
78+ const y = Math.sin(a) * rr;
79+ if (i) s.lineTo(x, y);
80+ else s.moveTo(x, y);
81+ }
82+ s.closePath();
83+ return s;
84+}
85+
86+// Triangle gun, square armor, circle cargo, star engine.
87+function pieceGeometry(kind: Kind, scale: number): THREE.BufferGeometry {
7388 const r = SHIP_R * scale;
74- const shape = new THREE.Shape();
75- shape.moveTo(r, 0);
76- shape.lineTo(-r * 0.75, r * 0.72);
77- shape.lineTo(-r * 0.75, -r * 0.72);
78- return new THREE.ShapeGeometry(shape);
89+ if (kind === 'armor') return new THREE.ShapeGeometry(poly(4, r * 0.8, 0, Math.PI / 4));
90+ if (kind === 'cargo') return new THREE.CircleGeometry(r * 0.75, 18);
91+ if (kind === 'engine') return new THREE.ShapeGeometry(poly(10, r, r * 0.45, -Math.PI / 2));
92+ return new THREE.ShapeGeometry(poly(3, r));
7993 }
8094
8195 function plate(w: number, h: number, v: number): THREE.Mesh {
8296 return new THREE.Mesh(new THREE.PlaneGeometry(w, h), new THREE.MeshBasicMaterial({ color: lum(v) }));
8397 }
8498
85-function hull(own: boolean): THREE.Group {
99+// A piece is a bright silhouette with a dimmer inset plate, so the cel shading
100+// survives the downsample to cell resolution. Owned pieces read brighter than
101+// loose wreckage, and a piece flips shade the moment it is bolted on or torn off.
102+const SHADE = {
103+ own: [lum(1, 7), lum(0.5, 7)],
104+ loose: [lum(0.7, 5), lum(0.35, 5)],
105+};
106+const shade = (g: THREE.Group, own: boolean) => {
107+ if (g.userData.own === own) return;
108+ g.userData.own = own;
109+ const c = own ? SHADE.own : SHADE.loose;
110+ g.children.forEach((m, i) => (m as THREE.Mesh<THREE.BufferGeometry, THREE.MeshBasicMaterial>).material.color.copy(c[i]));
111+};
112+
113+function piece(kind: Kind): THREE.Group {
86114 const g = new THREE.Group();
87- const idx = own ? 7 : 5;
88- g.add(new THREE.Mesh(hullGeometry(1), new THREE.MeshBasicMaterial({ color: lum(own ? 1 : 0.7, idx) })));
89- g.add(new THREE.Mesh(hullGeometry(0.7), new THREE.MeshBasicMaterial({ color: lum(own ? 0.5 : 0.35, idx) })));
115+ g.add(new THREE.Mesh(pieceGeometry(kind, 1), new THREE.MeshBasicMaterial({ color: SHADE.loose[0] })));
116+ g.add(new THREE.Mesh(pieceGeometry(kind, 0.7), new THREE.MeshBasicMaterial({ color: SHADE.loose[1] })));
117+ shade(g, false);
90118 return g;
91119 }
92120
@@ -109,7 +137,7 @@ export class View {
109137 private rt: THREE.WebGLRenderTarget;
110138 private pass: THREE.ShaderMaterial;
111139 private quad = new THREE.Scene();
112- private hulls = new Map<number, THREE.Group>();
140+ private pieceMeshes = new Map<number, THREE.Group>();
113141 private marker = crosshair();
114142 private cols = 0;
115143 private rows = 0;
@@ -161,7 +189,27 @@ export class View {
161189 this.pass.uniforms.uCellPx.value = CELL * dpr;
162190 }
163191
164- draw(cam: Camera, ships: Ship[], ownId: number, marker: { x: number; y: number } | null): void {
192+ // One mesh per piece id, whether it is bolted to a hull or drifting loose.
193+ private place(id: number, kind: Kind, own: boolean, x: number, y: number, h: number, seen: Set<number>): void {
194+ seen.add(id);
195+ let g = this.pieceMeshes.get(id);
196+ if (!g) {
197+ g = piece(kind);
198+ this.pieceMeshes.set(id, g);
199+ this.scene.add(g);
200+ }
201+ shade(g, own);
202+ g.position.set(x, y, 0);
203+ g.rotation.z = h;
204+ }
205+
206+ draw(
207+ cam: Camera,
208+ ships: Ship[],
209+ ownId: number,
210+ loose: Loose[],
211+ marker: { x: number; y: number } | null,
212+ ): void {
165213 // Zoom is world units per character cell: the raster keeps one texel per
166214 // cell, so zooming only changes how much world a cell covers.
167215 const wpc = CELL_WORLD / cam.zoom;
@@ -172,20 +220,18 @@ export class View {
172220 this.camera.top = hh;
173221 this.camera.bottom = -hh;
174222 this.camera.updateProjectionMatrix();
223+ const seen = new Set<number>();
175224 for (const s of ships) {
176- let g = this.hulls.get(s.id);
177- if (!g) {
178- g = hull(s.id === ownId);
179- this.hulls.set(s.id, g);
180- this.scene.add(g);
225+ for (const p of s.pieces) {
226+ const w = toWorld(s, p);
227+ this.place(p.id, p.kind, s.id === ownId, w.x, w.y, s.h, seen);
181228 }
182- g.position.set(s.x, s.y, 0);
183- g.rotation.z = s.h;
184229 }
185- for (const [id, g] of this.hulls) {
186- if (ships.some((s) => s.id === id)) continue;
230+ for (const l of loose) this.place(l.id, l.kind, false, l.x, l.y, l.h, seen);
231+ for (const [id, g] of this.pieceMeshes) {
232+ if (seen.has(id)) continue;
187233 this.scene.remove(g);
188- this.hulls.delete(id);
234+ this.pieceMeshes.delete(id);
189235 }
190236 this.marker.visible = marker !== null;
191237 if (marker) {