@pinkaphant/create-kolmo 0.1.4 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +15 -5
  2. package/bin/create-kolmo.mjs +45 -19
  3. package/package.json +2 -1
  4. package/templates/longline/README.md +14 -0
  5. package/templates/longline/index.html +15 -0
  6. package/templates/longline/package.json +38 -0
  7. package/templates/longline/src/App.tsx +48 -0
  8. package/templates/longline/src/components/Boat.tsx +97 -0
  9. package/templates/longline/src/components/CameraRig.tsx +61 -0
  10. package/templates/longline/src/components/Crates.tsx +48 -0
  11. package/templates/longline/src/components/Hud.tsx +197 -0
  12. package/templates/longline/src/components/Longline.tsx +107 -0
  13. package/templates/longline/src/components/Ocean.tsx +27 -0
  14. package/templates/longline/src/components/Radar.tsx +88 -0
  15. package/templates/longline/src/components/Referee.tsx +39 -0
  16. package/templates/longline/src/components/Scene.tsx +56 -0
  17. package/templates/longline/src/components/Sky.tsx +23 -0
  18. package/templates/longline/src/components/ocean-material.ts +143 -0
  19. package/templates/longline/src/components/round-context.ts +26 -0
  20. package/templates/longline/src/game/boat-control.ts +131 -0
  21. package/templates/longline/src/game/constants.ts +98 -0
  22. package/templates/longline/src/game/input.test.ts +83 -0
  23. package/templates/longline/src/game/input.ts +73 -0
  24. package/templates/longline/src/game/logic.test.ts +110 -0
  25. package/templates/longline/src/game/logic.ts +109 -0
  26. package/templates/longline/src/game/physics.test.ts +211 -0
  27. package/templates/longline/src/game/radar.ts +22 -0
  28. package/templates/longline/src/game/registry.ts +53 -0
  29. package/templates/longline/src/game/sea.ts +26 -0
  30. package/templates/longline/src/game/session.ts +6 -0
  31. package/templates/longline/src/game/simulation.test.ts +393 -0
  32. package/templates/longline/src/game/simulation.ts +137 -0
  33. package/templates/longline/src/game/store.test.ts +222 -0
  34. package/templates/longline/src/game/store.ts +195 -0
  35. package/templates/longline/src/game/test-world.ts +128 -0
  36. package/templates/longline/src/main.tsx +8 -0
  37. package/templates/longline/src/sfx.ts +50 -0
  38. package/templates/longline/src/styles.css +374 -0
  39. package/templates/longline/tsconfig.json +18 -0
  40. package/templates/longline/vite.config.ts +28 -0
@@ -0,0 +1,211 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { driveBoat, planeHeading, rotateByQuat, type DrivableBody, type Vec3 } from "./boat-control.js";
4
+ import { BOAT, FIXED_DT, LINE, SEA_STATE_IDS } from "./constants.js";
5
+ import { createSea } from "./sea.js";
6
+ import { createTestWorld, initRapier, planarSpeed, tilt } from "./test-world.js";
7
+
8
+ // These run the game's own numbers against a real Rapier world: the boat, the line and the crates float on the same
9
+ // buoyancy controllers the scene uses, the helm is the same `driveBoat`, and the sea is the same `createSea`.
10
+
11
+ await initRapier();
12
+
13
+ const heading = { fx: 0, fz: -1, rx: 1, rz: 0 };
14
+
15
+ /** The bow's heading in radians: 0 is -Z and positive turns toward +X, to starboard. */
16
+ function yawOf(body: { rotation(): { x: number; y: number; z: number; w: number } }): number {
17
+ planeHeading(body.rotation(), heading);
18
+ return Math.atan2(heading.fx, -heading.fz);
19
+ }
20
+
21
+ const wrap = (a: number): number => Math.atan2(Math.sin(a), Math.cos(a));
22
+
23
+ test("a boat at rest in still water draws half its height: that is its density against the water's", () => {
24
+ const w = createTestWorld({ withLine: false });
25
+ w.run(6);
26
+ assert.ok(Math.abs(w.boat.translation().y) < 1e-3, `y ${w.boat.translation().y}`);
27
+ assert.ok(Math.abs(w.boatController.stats.submergedFraction - 0.5) < 1e-3, `submerged ${w.boatController.stats.submergedFraction}`);
28
+ assert.ok(Math.abs(w.boat.mass() - 1440) < 0.01, `3.6 x 1.6 x 0.5 m at 500 kg/m3 is 1440 kg, not ${w.boat.mass()}`);
29
+ assert.ok(tilt(w.boat) < 1e-3, "and it sits level");
30
+ });
31
+
32
+ test("full ahead takes the boat to about 7.3 m/s; with the line in tow it is a little slower", () => {
33
+ const bare = createTestWorld({ withLine: false });
34
+ bare.run(15, { throttle: 1, steer: 0 });
35
+ const free = planarSpeed(bare.boat);
36
+ assert.ok(free > 7.0 && free < 7.6, `free speed ${free}`);
37
+ assert.ok(bare.boat.translation().z < -80, "and it went forward, which is -Z");
38
+
39
+ const towing = createTestWorld({ withLine: true });
40
+ towing.run(20, { throttle: 1, steer: 0 });
41
+ const towed = planarSpeed(towing.boat);
42
+ assert.ok(towed > 6.4 && towed < free, `towing speed ${towed}`);
43
+ });
44
+
45
+ test("the water stops the boat once the throttle is closed", () => {
46
+ const w = createTestWorld({ withLine: false });
47
+ w.run(15, { throttle: 1, steer: 0 });
48
+ w.run(10);
49
+ assert.ok(planarSpeed(w.boat) < 1.2, `coasting at ${planarSpeed(w.boat)}`);
50
+ });
51
+
52
+ test("astern backs the boat up, slower than ahead", () => {
53
+ const w = createTestWorld({ withLine: false });
54
+ w.run(5, { throttle: -1, steer: 0 });
55
+ assert.ok(w.boat.translation().z > 8, `z ${w.boat.translation().z}`);
56
+ const ahead = createTestWorld({ withLine: false });
57
+ ahead.run(5, { throttle: 1, steer: 0 });
58
+ assert.ok(planarSpeed(w.boat) < planarSpeed(ahead.boat));
59
+ });
60
+
61
+ test("the helm turns the bow the way it is told, at speed and from a stand", () => {
62
+ const right = createTestWorld({ withLine: true });
63
+ right.run(15, { throttle: 1, steer: 0 });
64
+ const y0 = yawOf(right.boat);
65
+ right.run(3, { throttle: 1, steer: 1 });
66
+ const turned = wrap(yawOf(right.boat) - y0);
67
+ assert.ok(turned > 1.2 && turned < 2.4, `hard to starboard turned ${turned} rad in 3 s`);
68
+ assert.ok(right.boat.angvel().y < 0, "turning to starboard is a negative spin about +Y");
69
+ assert.ok(planarSpeed(right.boat) > 5, "it keeps its way in the turn");
70
+
71
+ const left = createTestWorld({ withLine: true });
72
+ left.run(15, { throttle: 1, steer: 0 });
73
+ const l0 = yawOf(left.boat);
74
+ left.run(3, { throttle: 1, steer: -1 });
75
+ const turnedLeft = wrap(yawOf(left.boat) - l0);
76
+ assert.ok(turnedLeft < -1.2 && turnedLeft > -2.4, `hard to port turned ${turnedLeft} rad`);
77
+
78
+ // from a stand the helm asks for the full yaw rate, which is what makes the boat easy to point at a crate
79
+ const still = createTestWorld({ withLine: false });
80
+ still.run(2, { throttle: 0, steer: 1 });
81
+ const spin = -still.boat.angvel().y;
82
+ assert.ok(spin > 0.9 && spin < 1.3, `standing turn at ${spin} rad/s`);
83
+ });
84
+
85
+ test("the keel takes the sideways speed out of the hull", () => {
86
+ const w = createTestWorld({ withLine: false });
87
+ w.run(3);
88
+ w.boat.setLinvel({ x: 3, y: 0, z: 0 }, true);
89
+ w.run(2);
90
+ assert.ok(Math.abs(w.boat.linvel().x) < 0.05, `still sliding at ${w.boat.linvel().x}`);
91
+ });
92
+
93
+ test("a hull clear of the water gets no push, no rudder and no grip", () => {
94
+ const impulses: Vec3[] = [];
95
+ const torques: Vec3[] = [];
96
+ const body: DrivableBody = {
97
+ rotation: () => ({ x: 0, y: 0, z: 0, w: 1 }),
98
+ linvel: () => ({ x: 4, y: 0, z: 0 }),
99
+ angvel: () => ({ x: 0, y: 0, z: 0 }),
100
+ mass: () => 1440,
101
+ principalInertia: () => ({ x: 1585, y: 1862, z: 337 }),
102
+ applyImpulse: (i) => void impulses.push({ ...i }),
103
+ applyTorqueImpulse: (t) => void torques.push({ ...t }),
104
+ };
105
+ driveBoat(body, { throttle: 1, steer: 1 }, 0, FIXED_DT);
106
+ assert.ok(impulses.length > 0 && torques.length > 0, "the helm still calls the body, it just asks for nothing");
107
+ // -0 is as good as 0 here, which deepEqual would not say
108
+ for (const v of [...impulses, ...torques]) assert.equal(Math.abs(v.x) + Math.abs(v.y) + Math.abs(v.z), 0, `asked for ${v.x}, ${v.y}, ${v.z}`);
109
+ // and the same call in the water pushes forward (-Z) and turns to starboard
110
+ impulses.length = 0;
111
+ torques.length = 0;
112
+ driveBoat(body, { throttle: 1, steer: 1 }, 1, FIXED_DT);
113
+ assert.ok(impulses[0]!.z < 0 && Math.abs(impulses[0]!.z - -BOAT.thrust * FIXED_DT) < 20, `push ${impulses[0]!.z}`);
114
+ assert.ok(torques[0]!.y < 0);
115
+ });
116
+
117
+ test("the controls are clamped: asking for more than full does not push harder", () => {
118
+ const full: Vec3[] = [];
119
+ const over: Vec3[] = [];
120
+ const make = (log: Vec3[]): DrivableBody => ({
121
+ rotation: () => ({ x: 0, y: 0, z: 0, w: 1 }),
122
+ linvel: () => ({ x: 0, y: 0, z: 0 }),
123
+ angvel: () => ({ x: 0, y: 0, z: 0 }),
124
+ mass: () => 1440,
125
+ principalInertia: () => ({ x: 1585, y: 1862, z: 337 }),
126
+ applyImpulse: (i) => void log.push({ ...i }),
127
+ applyTorqueImpulse: () => {},
128
+ });
129
+ driveBoat(make(full), { throttle: 1, steer: 0 }, 1, FIXED_DT);
130
+ driveBoat(make(over), { throttle: 50, steer: 0 }, 5, FIXED_DT);
131
+ assert.deepEqual(over[0], full[0]);
132
+ });
133
+
134
+ test("planeHeading follows the hull's yaw and survives a hull on its end", () => {
135
+ const h = { fx: 0, fz: 0, rx: 0, rz: 0 };
136
+ planeHeading({ x: 0, y: 0, z: 0, w: 1 }, h);
137
+ assert.deepEqual([h.fx, h.fz, h.rx, h.rz].map((v) => Math.round(v * 1e9) / 1e9 + 0), [0, -1, 1, 0], "unrotated: bow to -Z, starboard +X");
138
+ // a quarter turn about +Y (counter-clockwise from above) points the bow at -X
139
+ const s = Math.SQRT1_2;
140
+ planeHeading({ x: 0, y: s, z: 0, w: s }, h);
141
+ assert.ok(Math.abs(h.fx + 1) < 1e-9 && Math.abs(h.fz) < 1e-9, `bow ${h.fx}, ${h.fz}`);
142
+ assert.ok(Math.abs(h.rx) < 1e-9 && Math.abs(h.rz + 1) < 1e-9, `starboard ${h.rx}, ${h.rz}`);
143
+ // bow straight up: nothing to take a heading from
144
+ planeHeading({ x: -s, y: 0, z: 0, w: s }, h);
145
+ assert.deepEqual([h.fx, h.fz], [0, -1]);
146
+ });
147
+
148
+ for (const id of SEA_STATE_IDS) {
149
+ test(`${id} sea: the boat follows the water, the line holds and nothing blows up under forty seconds of weaving`, () => {
150
+ const sea = createSea(id);
151
+ const w = createTestWorld({ sea, withLine: true });
152
+ let maxStretch = 0;
153
+ let maxTilt = 0;
154
+ let sum = 0;
155
+ let n = 0;
156
+ const tow = { x: 0, y: 0, z: 0 };
157
+ for (let i = 0; i < 40 * 60; i++) {
158
+ w.step({ throttle: 1, steer: Math.sin(w.time * 0.9) });
159
+ maxTilt = Math.max(maxTilt, tilt(w.boat));
160
+ // the first rope is made fast to the stern, not to the middle of the hull
161
+ const b = w.boat.translation();
162
+ rotateByQuat(w.boat.rotation(), { x: BOAT.tow[0], y: BOAT.tow[1], z: BOAT.tow[2] }, false, tow);
163
+ let prev = { x: b.x + tow.x, y: b.y + tow.y, z: b.z + tow.z };
164
+ for (const f of w.floats) {
165
+ const p = f.translation();
166
+ assert.ok(Number.isFinite(p.x + p.y + p.z), "a float went to NaN");
167
+ maxStretch = Math.max(maxStretch, Math.hypot(p.x - prev.x, p.y - prev.y, p.z - prev.z) - LINE.spacing);
168
+ prev = p;
169
+ }
170
+ sum += Math.abs(b.y - sea.field.heightAt(b.x, b.z, w.time));
171
+ n++;
172
+ }
173
+ assert.ok(maxStretch < 0.02, `a rope stretched ${maxStretch} m`);
174
+ assert.ok(sum / n < 0.08, `the hull rode ${sum / n} m from the surface on average`);
175
+ assert.ok(maxTilt < 0.5, `the hull rolled ${(maxTilt * 57.3).toFixed(0)} degrees`);
176
+ const speed = planarSpeed(w.boat);
177
+ assert.ok(speed > 5.5 && speed < 8.2, `speed ${speed}`);
178
+ const last = w.floats[w.floats.length - 1]!.translation();
179
+ const b = w.boat.translation();
180
+ const behind = Math.hypot(last.x - b.x, last.z - b.z);
181
+ assert.ok(behind > 8 && behind < 17, `the last float is ${behind} m from the boat`);
182
+ });
183
+ }
184
+
185
+ test("crates float at their draft and the current carries them, harder in a rougher sea", () => {
186
+ const drift: number[] = [];
187
+ for (const id of SEA_STATE_IDS) {
188
+ const sea = createSea(id);
189
+ const w = createTestWorld({ sea, withLine: false, withCrates: true });
190
+ const x0 = w.crates.map((c) => c.translation().x);
191
+ w.run(40);
192
+ const dx = w.crates.map((c, i) => c.translation().x - x0[i]!);
193
+ const meanDx = dx.reduce((a, b) => a + b, 0) / dx.length;
194
+ drift.push(meanDx);
195
+ assert.ok(meanDx > 0.8 * 40 * sea.state.current * 0.8, `${id}: drifted ${meanDx} m at ${sea.state.current} m/s`);
196
+ assert.ok(meanDx < 40 * sea.state.current * 1.1, `${id}: drifted ${meanDx} m, faster than the current`);
197
+ for (const c of w.crates) {
198
+ const p = c.translation();
199
+ assert.ok(Math.abs(p.y - sea.field.heightAt(p.x, p.z, w.time) - 0.075) < 0.15, `${id}: a crate rides ${p.y}`);
200
+ assert.equal(c.isSleeping(), false);
201
+ }
202
+ }
203
+ assert.ok(drift[0]! < drift[1]! && drift[1]! < drift[2]!, `drift by sea ${drift.join(", ")}`);
204
+ });
205
+
206
+ test("crates at rest in still water sit at the draft their density gives", () => {
207
+ const w = createTestWorld({ withLine: false, withCrates: true });
208
+ w.run(8);
209
+ // 350 kg/m3 in a 0.5 m crate: 0.175 m below the surface, so the centre is 0.075 m above it
210
+ for (const c of w.crates) assert.ok(Math.abs(c.translation().y - 0.075) < 0.005, `y ${c.translation().y}`);
211
+ });
@@ -0,0 +1,22 @@
1
+ import { CRATE } from "./constants.js";
2
+
3
+ /**
4
+ * What the radar in the corner draws: the boat and the crates on the water plane. The scene writes it every physics
5
+ * step and the radar reads it every frame; it is not React state, so it costs no render.
6
+ */
7
+ export interface RadarState {
8
+ ready: boolean;
9
+ boatX: number;
10
+ boatZ: number;
11
+ /** Where the bow points, radians, atan2(forward x, -forward z): 0 is -Z, positive turns to +X. */
12
+ heading: number;
13
+ crates: Float64Array;
14
+ }
15
+
16
+ export const radar: RadarState = {
17
+ ready: false,
18
+ boatX: 0,
19
+ boatZ: 0,
20
+ heading: 0,
21
+ crates: new Float64Array(CRATE.count * 2),
22
+ };
@@ -0,0 +1,53 @@
1
+ import type { BuoyancyController } from "@pinkaphant/kolmo/water";
2
+ import type { RapierRigidBody } from "@react-three/rapier";
3
+ import type { Object3D } from "three";
4
+ import { CRATE, LINE } from "./constants.js";
5
+ import type { CrateBody, Fleet, PointBody } from "./simulation.js";
6
+
7
+ /** A ref the scene's components fill in: react-three-rapier hands the body over through it once the world has made it. */
8
+ export interface BodyRef {
9
+ current: RapierRigidBody | null;
10
+ }
11
+
12
+ const makeRefs = (n: number): BodyRef[] => Array.from({ length: n }, () => ({ current: null }));
13
+
14
+ /**
15
+ * The bodies of one round, by role. The components of the scene put their body in the ref of their slot, and the
16
+ * rules read them back through `fleet()` every step; nothing here is React state.
17
+ */
18
+ export class Registry {
19
+ readonly boat: BodyRef = { current: null };
20
+ readonly floats: BodyRef[] = makeRefs(LINE.floats);
21
+ readonly crates: BodyRef[] = makeRefs(CRATE.count);
22
+
23
+ /** The boat's buoyancy controller: the helm reads how much of the hull is in the water from it. */
24
+ boatController: BuoyancyController | null = null;
25
+ /** An object that rides the boat's interpolated pose, for the camera and the rope. */
26
+ boatObject: Object3D | null = null;
27
+ /** The same for every float of the line. */
28
+ readonly floatObjects: Array<Object3D | null> = new Array<Object3D | null>(LINE.floats).fill(null);
29
+
30
+ private readonly view: { boat: RapierRigidBody | null; floats: PointBody[]; crates: CrateBody[] } = {
31
+ boat: null,
32
+ floats: new Array<PointBody>(LINE.floats),
33
+ crates: new Array<CrateBody>(CRATE.count),
34
+ };
35
+
36
+ /** Every body of the round, or null while some of them have not been made yet. Allocation-free. */
37
+ fleet(): Fleet | null {
38
+ const boat = this.boat.current;
39
+ if (boat === null) return null;
40
+ for (let i = 0; i < this.floats.length; i++) {
41
+ const b = this.floats[i]!.current;
42
+ if (b === null) return null;
43
+ this.view.floats[i] = b;
44
+ }
45
+ for (let i = 0; i < this.crates.length; i++) {
46
+ const b = this.crates[i]!.current;
47
+ if (b === null) return null;
48
+ this.view.crates[i] = b;
49
+ }
50
+ this.view.boat = boat;
51
+ return this.view as Fleet;
52
+ }
53
+ }
@@ -0,0 +1,26 @@
1
+ import { WaveField, createWaveSpectrum, createWaveSurface, type WaterSurface } from "@pinkaphant/kolmo/water";
2
+ import { SEA_STATES, SWELL_HEADING, type SeaState, type SeaStateId } from "./constants.js";
3
+
4
+ /** One sea: the wave field the shader draws and the surface the hulls float on are made from the same components. */
5
+ export interface Sea {
6
+ readonly state: SeaState;
7
+ readonly field: WaveField;
8
+ readonly surface: WaterSurface;
9
+ }
10
+
11
+ export function createSea(id: SeaStateId): Sea {
12
+ const state = SEA_STATES[id];
13
+ const field = new WaveField({
14
+ waves: createWaveSpectrum({
15
+ seed: state.seed,
16
+ count: 4,
17
+ wavelength: state.wavelength,
18
+ amplitude: state.amplitude,
19
+ heading: SWELL_HEADING,
20
+ spread: 0.45,
21
+ steepness: state.steepness,
22
+ }),
23
+ });
24
+ const surface = createWaveSurface(field, { current: { x: state.current, y: 0, z: 0 } });
25
+ return { state, field, surface };
26
+ }
@@ -0,0 +1,6 @@
1
+ import { Helm } from "./input.js";
2
+ import { Game, browserStore } from "./store.js";
3
+
4
+ /** The one round and the one helm of the page. The tests make their own. */
5
+ export const game = new Game(browserStore());
6
+ export const helm = new Helm();