@pinkaphant/create-kolmo 0.1.4 → 0.3.0

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 +50 -27
  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 +169 -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,169 @@
1
+ import * as THREE from "three";
2
+ import type { WaveField } from "@pinkaphant/kolmo/water";
3
+
4
+ /** The colours of the scene: the sea fades into the horizon colour, and the sky is that colour at the horizon. */
5
+ export const PALETTE = {
6
+ deep: "#0a3a5c",
7
+ shallow: "#2f9fb3",
8
+ horizon: "#b9dbea",
9
+ zenith: "#4f93c9",
10
+ foam: "#f2f8fb",
11
+ } as const;
12
+
13
+ /** Where the sun is: a unit vector toward it. */
14
+ export const SUN = new THREE.Vector3(-0.45, 0.62, -0.64).normalize();
15
+
16
+ /** The sea mesh: a square that follows the boat, with a vertex every `size / segments` metres. */
17
+ export const OCEAN = { size: 220, segments: 300, fogNear: 55, fogFar: 105 } as const;
18
+
19
+ const vertex = /* glsl */ `
20
+ uniform float uTime;
21
+ uniform vec2 uOrigin;
22
+ uniform float uLevel;
23
+ uniform vec4 uDirKW[WAVE_COUNT];
24
+ uniform vec4 uAmp[WAVE_COUNT];
25
+ varying vec3 vWorld;
26
+ varying vec3 vNormal;
27
+
28
+ // The same Gerstner sum as WaveField.displace in @pinkaphant/kolmo/water, on the arrays of WaveField.toUniforms():
29
+ // uDirKW is (Dx, Dz, k, omega) per wave and uAmp is (A, s, phase, q) per wave. The normal is the field's exact one.
30
+ void main() {
31
+ vec2 rest = position.xz + uOrigin;
32
+ vec3 p = vec3(rest.x, uLevel, rest.y);
33
+ float a = 1.0;
34
+ float b = 1.0;
35
+ float c = 0.0;
36
+ float gp = 0.0;
37
+ float gq = 0.0;
38
+ for (int i = 0; i < WAVE_COUNT; i++) {
39
+ vec4 d = uDirKW[i];
40
+ vec4 w = uAmp[i];
41
+ float theta = d.z * (d.x * rest.x + d.y * rest.y) - d.w * uTime + w.z;
42
+ float s = sin(theta);
43
+ float co = cos(theta);
44
+ p.x += w.w * d.x * co;
45
+ p.z += w.w * d.y * co;
46
+ p.y += w.x * s;
47
+ float ss = w.y * s;
48
+ a -= ss * d.x * d.x;
49
+ b -= ss * d.y * d.y;
50
+ c -= ss * d.x * d.y;
51
+ float ak = w.x * d.z * co;
52
+ gp += ak * d.x;
53
+ gq += ak * d.y;
54
+ }
55
+ float det = a * b - c * c;
56
+ vNormal = normalize(vec3(gq * c - b * gp, det, c * gp - gq * a));
57
+ vWorld = p;
58
+ gl_Position = projectionMatrix * viewMatrix * vec4(p, 1.0);
59
+ }
60
+ `;
61
+
62
+ const fragment = /* glsl */ `
63
+ uniform vec3 uDeep;
64
+ uniform vec3 uShallow;
65
+ uniform vec3 uHorizon;
66
+ uniform vec3 uFoam;
67
+ uniform vec3 uSun;
68
+ uniform float uLevel;
69
+ uniform float uCrest;
70
+ uniform float uFoamAmount;
71
+ uniform float uFogNear;
72
+ uniform float uFogFar;
73
+ varying vec3 vWorld;
74
+ varying vec3 vNormal;
75
+
76
+ void main() {
77
+ vec3 n = normalize(vNormal);
78
+ vec3 v = normalize(cameraPosition - vWorld);
79
+ float fresnel = pow(1.0 - max(dot(n, v), 0.0), 4.0);
80
+ float lift = clamp((vWorld.y - uLevel) / max(uCrest, 0.05) * 0.5 + 0.5, 0.0, 1.0);
81
+ float diffuse = max(dot(n, uSun), 0.0);
82
+ vec3 col = mix(uDeep, uShallow, clamp(lift * 0.5 + diffuse * 0.45, 0.0, 1.0));
83
+ col = mix(col, uHorizon, fresnel * 0.7);
84
+ vec3 h = normalize(uSun + v);
85
+ col += vec3(1.0, 0.95, 0.85) * pow(max(dot(n, h), 0.0), 140.0) * 0.7;
86
+ col = mix(col, uFoam, smoothstep(0.78, 0.98, lift) * uFoamAmount);
87
+ col = mix(col, uHorizon, smoothstep(uFogNear, uFogFar, distance(cameraPosition, vWorld)));
88
+ gl_FragColor = vec4(col, 1.0);
89
+ #include <colorspace_fragment>
90
+ }
91
+ `;
92
+
93
+ export interface OceanUniforms {
94
+ [name: string]: THREE.IUniform;
95
+ uTime: THREE.IUniform<number>;
96
+ uOrigin: THREE.IUniform<THREE.Vector2>;
97
+ }
98
+
99
+ /** The sea's material for one wave field. `uTime` and `uOrigin` are the two things that change every frame. */
100
+ export function createOceanMaterial(field: WaveField, foam: number): THREE.ShaderMaterial & { uniforms: OceanUniforms } {
101
+ const u = field.toUniforms();
102
+ const uniforms: OceanUniforms = {
103
+ uTime: { value: 0 },
104
+ uOrigin: { value: new THREE.Vector2() },
105
+ uLevel: { value: u.level },
106
+ uDirKW: { value: u.dirKW },
107
+ uAmp: { value: u.ampSteepPhase },
108
+ uCrest: { value: field.maxCrest },
109
+ uFoamAmount: { value: foam },
110
+ uDeep: { value: new THREE.Color(PALETTE.deep) },
111
+ uShallow: { value: new THREE.Color(PALETTE.shallow) },
112
+ uHorizon: { value: new THREE.Color(PALETTE.horizon) },
113
+ uFoam: { value: new THREE.Color(PALETTE.foam) },
114
+ uSun: { value: SUN },
115
+ uFogNear: { value: OCEAN.fogNear },
116
+ uFogFar: { value: OCEAN.fogFar },
117
+ };
118
+ return new THREE.ShaderMaterial({
119
+ vertexShader: vertex,
120
+ fragmentShader: fragment,
121
+ uniforms,
122
+ defines: { WAVE_COUNT: u.count },
123
+ }) as THREE.ShaderMaterial & { uniforms: OceanUniforms };
124
+ }
125
+
126
+ /** The sea mesh's geometry: a flat grid of rest positions in the XZ plane, centred on the origin. */
127
+ export function createOceanGeometry(): THREE.PlaneGeometry {
128
+ const g = new THREE.PlaneGeometry(OCEAN.size, OCEAN.size, OCEAN.segments, OCEAN.segments);
129
+ g.rotateX(-Math.PI / 2);
130
+ return g;
131
+ }
132
+
133
+ const skyVertex = /* glsl */ `
134
+ varying vec3 vDir;
135
+ void main() {
136
+ vDir = normalize(position);
137
+ vec4 pos = projectionMatrix * mat4(mat3(viewMatrix)) * vec4(position, 1.0);
138
+ gl_Position = pos.xyww;
139
+ }
140
+ `;
141
+
142
+ const skyFragment = /* glsl */ `
143
+ uniform vec3 uHorizon;
144
+ uniform vec3 uZenith;
145
+ uniform vec3 uSun;
146
+ varying vec3 vDir;
147
+ void main() {
148
+ vec3 d = normalize(vDir);
149
+ vec3 col = mix(uHorizon, uZenith, pow(max(d.y, 0.0), 0.55));
150
+ float s = max(dot(d, uSun), 0.0);
151
+ col += vec3(1.0, 0.9, 0.7) * (pow(s, 600.0) * 2.0 + pow(s, 14.0) * 0.25);
152
+ gl_FragColor = vec4(col, 1.0);
153
+ #include <colorspace_fragment>
154
+ }
155
+ `;
156
+
157
+ export function createSkyMaterial(): THREE.ShaderMaterial {
158
+ return new THREE.ShaderMaterial({
159
+ vertexShader: skyVertex,
160
+ fragmentShader: skyFragment,
161
+ uniforms: {
162
+ uHorizon: { value: new THREE.Color(PALETTE.horizon) },
163
+ uZenith: { value: new THREE.Color(PALETTE.zenith) },
164
+ uSun: { value: SUN },
165
+ },
166
+ side: THREE.BackSide,
167
+ depthWrite: false,
168
+ });
169
+ }
@@ -0,0 +1,26 @@
1
+ import type { PhysicsClock } from "@pinkaphant/kolmo/water/react";
2
+ import { createContext, useContext } from "react";
3
+ import type { Helm } from "../game/input.js";
4
+ import type { Registry } from "../game/registry.js";
5
+ import type { Sea } from "../game/sea.js";
6
+ import type { Simulation } from "../game/simulation.js";
7
+ import type { Game } from "../game/store.js";
8
+
9
+ /** What every part of one round's scene shares. */
10
+ export interface Round {
11
+ sea: Sea;
12
+ /** The water's time: the sum of the physics steps taken. The hulls and the shader read this same clock. */
13
+ clock: PhysicsClock;
14
+ registry: Registry;
15
+ simulation: Simulation;
16
+ game: Game;
17
+ helm: Helm;
18
+ }
19
+
20
+ export const RoundContext = createContext<Round | null>(null);
21
+
22
+ export function useRound(): Round {
23
+ const round = useContext(RoundContext);
24
+ if (round === null) throw new Error("useRound: no round here; this component belongs inside <Scene>");
25
+ return round;
26
+ }
@@ -0,0 +1,131 @@
1
+ import { BOAT } from "./constants.js";
2
+
3
+ export interface Vec3 {
4
+ x: number;
5
+ y: number;
6
+ z: number;
7
+ }
8
+
9
+ export interface Quat {
10
+ x: number;
11
+ y: number;
12
+ z: number;
13
+ w: number;
14
+ }
15
+
16
+ /** What the helm needs of a body. Rapier's `RigidBody` satisfies it, so the tests drive a real Rapier body. */
17
+ export interface DrivableBody {
18
+ rotation(): Quat;
19
+ linvel(): Vec3;
20
+ angvel(): Vec3;
21
+ mass(): number;
22
+ principalInertia(): Vec3;
23
+ applyImpulse(impulse: Vec3, wakeUp: boolean): void;
24
+ applyTorqueImpulse(torque: Vec3, wakeUp: boolean): void;
25
+ }
26
+
27
+ /** throttle: +1 full ahead, -1 full astern. steer: +1 hard to starboard (right), -1 hard to port. */
28
+ export interface DriveInput {
29
+ throttle: number;
30
+ steer: number;
31
+ }
32
+
33
+ const clamp = (v: number, lo: number, hi: number): number => (v < lo ? lo : v > hi ? hi : v);
34
+
35
+ /**
36
+ * The hull's forward direction on the water plane (unit length, y = 0) and its starboard side. Forward is -Z in the
37
+ * hull's frame. A hull standing on its end has no heading on the plane and gets the world's -Z.
38
+ */
39
+ export function planeHeading(q: Quat, out: { fx: number; fz: number; rx: number; rz: number }): void {
40
+ // (0, 0, -1) rotated by q, x and z parts
41
+ let fx = -2 * (q.x * q.z + q.y * q.w);
42
+ let fz = -(1 - 2 * (q.x * q.x + q.y * q.y));
43
+ const len = Math.hypot(fx, fz);
44
+ if (len < 1e-6) {
45
+ fx = 0;
46
+ fz = -1;
47
+ } else {
48
+ fx /= len;
49
+ fz /= len;
50
+ }
51
+ out.fx = fx;
52
+ out.fz = fz;
53
+ // starboard is forward x up
54
+ out.rx = -fz;
55
+ out.rz = fx;
56
+ }
57
+
58
+ /** How much of the helm's grip the hull has: nothing when it is clear of the water, all of it from a third submerged. */
59
+ export function wetGrip(submergedFraction: number): number {
60
+ return clamp(submergedFraction / 0.3, 0, 1);
61
+ }
62
+
63
+ /** The yaw rate the helm asks for at full lock, rad/s: tighter when slow, gentler at speed. */
64
+ export function yawRateAt(speed: number): number {
65
+ const t = clamp(speed / BOAT.yawFastSpeed, 0, 1);
66
+ return BOAT.yawRate + (BOAT.yawRateFast - BOAT.yawRate) * t;
67
+ }
68
+
69
+ const heading = { fx: 0, fz: -1, rx: 1, rz: 0 };
70
+
71
+ /** Rotates v by q (or by q's inverse), into `out`. `out` may be `v`. */
72
+ export function rotateByQuat(q: Quat, v: Vec3, inverse: boolean, out: Vec3): Vec3 {
73
+ const qx = inverse ? -q.x : q.x;
74
+ const qy = inverse ? -q.y : q.y;
75
+ const qz = inverse ? -q.z : q.z;
76
+ const vx = v.x;
77
+ const vy = v.y;
78
+ const vz = v.z;
79
+ const tx = 2 * (qy * vz - qz * vy);
80
+ const ty = 2 * (qz * vx - qx * vz);
81
+ const tz = 2 * (qx * vy - qy * vx);
82
+ out.x = vx + q.w * tx + (qy * tz - qz * ty);
83
+ out.y = vy + q.w * ty + (qz * tx - qx * tz);
84
+ out.z = vz + q.w * tz + (qx * ty - qy * tx);
85
+ return out;
86
+ }
87
+
88
+ const spin = { x: 0, y: 0, z: 0 };
89
+ const damp = { x: 0, y: 0, z: 0 };
90
+
91
+ /**
92
+ * One step of the helm, called before the world steps: thrust along the heading, a yaw torque that chases the asked-for
93
+ * yaw rate, and the keel's grip on sideways motion. All three are impulses of this step, scaled by `grip` (0 to 1, how
94
+ * much of the hull is in the water), so a hull flung clear of a wave cannot push, steer or grip.
95
+ */
96
+ export function driveBoat(body: DrivableBody, input: DriveInput, grip: number, dt: number): void {
97
+ const throttle = clamp(input.throttle, -1, 1);
98
+ const steer = clamp(input.steer, -1, 1);
99
+ const g = clamp(grip, 0, 1);
100
+ planeHeading(body.rotation(), heading);
101
+ const v = body.linvel();
102
+ const speed = Math.hypot(v.x, v.z);
103
+
104
+ // thrust
105
+ const push = (throttle >= 0 ? BOAT.thrust : BOAT.reverseThrust) * throttle * g * dt;
106
+ // keel: the sideways part of the velocity, bled off exponentially
107
+ const lateral = v.x * heading.rx + v.z * heading.rz;
108
+ const keel = -body.mass() * lateral * (1 - Math.exp(-BOAT.keel * dt)) * g;
109
+ body.applyImpulse(
110
+ { x: heading.fx * push + heading.rx * keel, y: 0, z: heading.fz * push + heading.rz * keel },
111
+ true,
112
+ );
113
+
114
+ // helm: turning to starboard is a negative rotation about +Y
115
+ const inertia = body.principalInertia().y;
116
+ const wanted = -steer * yawRateAt(speed);
117
+ const error = wanted - body.angvel().y;
118
+ const alpha = clamp(BOAT.yawGain * error, -BOAT.yawGain * 2, BOAT.yawGain * 2);
119
+ body.applyTorqueImpulse({ x: 0, y: inertia * alpha * g * dt, z: 0 }, true);
120
+
121
+ // roll and pitch damping, in the hull's frame where each axis has its own inertia: the bilge keels of a small boat
122
+ const q = body.rotation();
123
+ const principal = body.principalInertia();
124
+ rotateByQuat(q, body.angvel(), true, spin);
125
+ const bleed = 1 - Math.exp(-BOAT.tiltDamping * dt);
126
+ damp.x = -principal.x * spin.x * bleed * g;
127
+ damp.y = 0;
128
+ damp.z = -principal.z * spin.z * bleed * g;
129
+ rotateByQuat(q, damp, false, damp);
130
+ body.applyTorqueImpulse(damp, true);
131
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Every number the game is tuned with. The headless physics tests (physics.test.ts) run the same numbers against a
3
+ * real Rapier world, so a change here is checked there.
4
+ */
5
+
6
+ /** The one physics step. `<Physics timeStep>` and every `useBuoyancy` get this number; Kolmo refuses a mismatch. */
7
+ export const FIXED_DT = 1 / 60;
8
+
9
+ /** 9.8125 is exact in f32, so the engine's gravity and the solver's are the same number. */
10
+ export const GRAVITY = 9.8125;
11
+
12
+ /** The boat: a 3.6 m x 1.6 m hull at half the density of water, so it draws 0.25 m. Forward is -Z, the stern is +Z. */
13
+ export const BOAT = {
14
+ halfExtents: [0.8, 0.25, 1.8] as const,
15
+ density: 500,
16
+ /** Per-slab wave sampling: the hull sees the wave under its bow and its stern. */
17
+ slices: 4,
18
+ drag: { linear: 0.12, quadratic: 0.1, angular: 0.3 },
19
+ /** Forward push in newtons: about 7.3 m/s in calm water. */
20
+ thrust: 6000,
21
+ reverseThrust: 2400,
22
+ /** Yaw rate the helm asks for, rad/s, from standstill and at full speed. */
23
+ yawRate: 1.15,
24
+ yawRateFast: 0.65,
25
+ /** Speed at which the helm has dropped to `yawRateFast`, m/s. */
26
+ yawFastSpeed: 7,
27
+ /** How hard the steering torque chases the asked-for yaw rate, 1/s. */
28
+ yawGain: 5,
29
+ /** Roll and pitch rate the bilge keels take out of the hull, 1/s. */
30
+ tiltDamping: 4,
31
+ /** Sideways speed the keel takes out of the hull, 1/s. */
32
+ keel: 3.5,
33
+ /** Where the line is made fast, in the hull's frame. */
34
+ tow: [0, 0.15, 1.85] as const,
35
+ } as const;
36
+
37
+ /** The longline: floats on rope joints behind the stern. */
38
+ export const LINE = {
39
+ floats: 8,
40
+ /** Rope between neighbours, metres. */
41
+ spacing: 1.7,
42
+ floatRadius: 0.22,
43
+ floatDensity: 400,
44
+ } as const;
45
+
46
+ /** A drifting crate. Any part of the line within `catchRadius` of a crate's centre hauls it in. */
47
+ export const CRATE = {
48
+ halfExtents: [0.4, 0.25, 0.4] as const,
49
+ density: 350,
50
+ count: 9,
51
+ catchRadius: 1.1,
52
+ /** Points per crate before the combo. */
53
+ points: 100,
54
+ } as const;
55
+
56
+ /** The play area: a circle of this radius around the start. Past it the boat is pushed back and crates are lost. */
57
+ export const ARENA = {
58
+ radius: 80,
59
+ /** Crates enter in a band this far inside the upstream edge. */
60
+ spawnBand: 18,
61
+ /** Push back on the boat, m/s^2 per metre past the edge. */
62
+ push: 0.9,
63
+ } as const;
64
+
65
+ export const ROUND = {
66
+ seconds: 90,
67
+ /** A haul within this many seconds of the last one raises the combo. */
68
+ comboWindow: 4,
69
+ maxCombo: 5,
70
+ } as const;
71
+
72
+ export type SeaStateId = "calm" | "choppy" | "rough";
73
+
74
+ export interface SeaState {
75
+ id: SeaStateId;
76
+ label: string;
77
+ /** Longest wavelength in metres and the amplitude of that wave. */
78
+ wavelength: number;
79
+ amplitude: number;
80
+ steepness: number;
81
+ /** Current that carries the crates, m/s, along +X. */
82
+ current: number;
83
+ /** How much of the highest crests the shader whitens, 0 to 1. */
84
+ foam: number;
85
+ /** Seed of the wave spectrum. */
86
+ seed: number;
87
+ }
88
+
89
+ export const SEA_STATES: Readonly<Record<SeaStateId, SeaState>> = {
90
+ calm: { id: "calm", label: "Calm", wavelength: 26, amplitude: 0.08, steepness: 0.5, current: 0.3, foam: 0.1, seed: 11 },
91
+ choppy: { id: "choppy", label: "Choppy", wavelength: 24, amplitude: 0.17, steepness: 0.7, current: 0.55, foam: 0.5, seed: 7 },
92
+ rough: { id: "rough", label: "Rough", wavelength: 28, amplitude: 0.3, steepness: 0.7, current: 0.8, foam: 0.9, seed: 23 },
93
+ };
94
+
95
+ export const SEA_STATE_IDS: readonly SeaStateId[] = ["calm", "choppy", "rough"];
96
+
97
+ /** Heading of the swell in radians (the wave field's convention: 0 is +X). It runs with the current, so the crates ride it. */
98
+ export const SWELL_HEADING = 0.35;
@@ -0,0 +1,83 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { Helm, attachKeyboard } from "./input.js";
4
+
5
+ test("W and S are throttle, D and A are the rudder, and the arrow keys do the same", () => {
6
+ const h = new Helm();
7
+ assert.deepEqual(h.read(), { throttle: 0, steer: 0 });
8
+ h.press("KeyW");
9
+ h.press("KeyD");
10
+ assert.deepEqual(h.read(), { throttle: 1, steer: 1 });
11
+ h.release("KeyW");
12
+ h.release("KeyD");
13
+ h.press("ArrowDown");
14
+ h.press("ArrowLeft");
15
+ assert.deepEqual(h.read(), { throttle: -1, steer: -1 });
16
+ });
17
+
18
+ test("opposite keys cancel, and holding both ways of one axis through two keys does not exceed 1", () => {
19
+ const h = new Helm();
20
+ h.press("KeyW");
21
+ h.press("KeyS");
22
+ assert.equal(h.read().throttle, 0);
23
+ h.release("KeyS");
24
+ h.press("ArrowUp");
25
+ assert.equal(h.read().throttle, 1, "W and the up arrow together are still full ahead");
26
+ });
27
+
28
+ test("the on-screen buttons add to the keys, within -1 and 1, and letting go clears them", () => {
29
+ const h = new Helm();
30
+ h.setTouch(1, -1);
31
+ assert.deepEqual(h.read(), { throttle: 1, steer: -1 });
32
+ h.press("KeyW");
33
+ assert.equal(h.read().throttle, 1);
34
+ h.setTouch(0, 0);
35
+ h.release("KeyW");
36
+ assert.deepEqual(h.read(), { throttle: 0, steer: 0 });
37
+ });
38
+
39
+ test("releaseAll lets go of keys and buttons both", () => {
40
+ const h = new Helm();
41
+ h.press("KeyW");
42
+ h.press("KeyA");
43
+ h.setTouch(-1, 1);
44
+ h.releaseAll();
45
+ assert.deepEqual(h.read(), { throttle: 0, steer: 0 });
46
+ });
47
+
48
+ test("keys the helm does not use are not held", () => {
49
+ const h = new Helm();
50
+ h.press("KeyQ");
51
+ h.press("Space");
52
+ assert.deepEqual(h.read(), { throttle: 0, steer: 0 });
53
+ });
54
+
55
+ test("read fills the object it is given, so a caller can reuse one", () => {
56
+ const h = new Helm();
57
+ const out = { throttle: 9, steer: 9 };
58
+ h.press("KeyS");
59
+ assert.equal(h.read(out), out);
60
+ assert.deepEqual(out, { throttle: -1, steer: 0 });
61
+ });
62
+
63
+ test("attachKeyboard follows key events, swallows the ones it uses, loses them on blur and unhooks cleanly", () => {
64
+ const target = new EventTarget();
65
+ const h = new Helm();
66
+ const off = attachKeyboard(h, target as unknown as Window);
67
+ const key = (type: string, code: string) => {
68
+ const e = Object.assign(new Event(type, { cancelable: true }), { code });
69
+ target.dispatchEvent(e);
70
+ return e;
71
+ };
72
+ assert.equal(key("keydown", "KeyW").defaultPrevented, true, "the page must not scroll");
73
+ assert.equal(key("keydown", "KeyD").defaultPrevented, true);
74
+ assert.deepEqual(h.read(), { throttle: 1, steer: 1 });
75
+ assert.equal(key("keydown", "KeyP").defaultPrevented, false, "other keys are left alone");
76
+ key("keyup", "KeyD");
77
+ assert.equal(h.read().steer, 0);
78
+ target.dispatchEvent(new Event("blur"));
79
+ assert.deepEqual(h.read(), { throttle: 0, steer: 0 }, "a key-up lost to another window");
80
+ off();
81
+ key("keydown", "KeyW");
82
+ assert.equal(h.read().throttle, 0, "no longer listening");
83
+ });
@@ -0,0 +1,73 @@
1
+ import type { DriveInput } from "./boat-control.js";
2
+
3
+ const AHEAD = new Set(["KeyW", "ArrowUp"]);
4
+ const ASTERN = new Set(["KeyS", "ArrowDown"]);
5
+ const STARBOARD = new Set(["KeyD", "ArrowRight"]);
6
+ const PORT = new Set(["KeyA", "ArrowLeft"]);
7
+
8
+ /** Which of the helm's controls are held, from the keyboard and from the on-screen buttons. */
9
+ export class Helm {
10
+ private readonly keys = new Set<string>();
11
+ private touchThrottle = 0;
12
+ private touchSteer = 0;
13
+
14
+ press(code: string): void {
15
+ this.keys.add(code);
16
+ }
17
+
18
+ release(code: string): void {
19
+ this.keys.delete(code);
20
+ }
21
+
22
+ /** On-screen controls: -1, 0 or +1 on each axis. */
23
+ setTouch(throttle: number, steer: number): void {
24
+ this.touchThrottle = throttle;
25
+ this.touchSteer = steer;
26
+ }
27
+
28
+ /** Lets go of everything, e.g. when the window loses focus and the browser will never send the key-up. */
29
+ releaseAll(): void {
30
+ this.keys.clear();
31
+ this.touchThrottle = 0;
32
+ this.touchSteer = 0;
33
+ }
34
+
35
+ private axis(positive: ReadonlySet<string>, negative: ReadonlySet<string>): number {
36
+ let v = 0;
37
+ for (const k of this.keys) {
38
+ if (positive.has(k)) v += 1;
39
+ else if (negative.has(k)) v -= 1;
40
+ }
41
+ return v;
42
+ }
43
+
44
+ read(out: DriveInput = { throttle: 0, steer: 0 }): DriveInput {
45
+ const clamp = (v: number): number => (v < -1 ? -1 : v > 1 ? 1 : v);
46
+ out.throttle = clamp(this.axis(AHEAD, ASTERN) + this.touchThrottle);
47
+ out.steer = clamp(this.axis(STARBOARD, PORT) + this.touchSteer);
48
+ return out;
49
+ }
50
+ }
51
+
52
+ /** Hooks a helm up to the window's keyboard events. Returns the function that unhooks it. */
53
+ export function attachKeyboard(helm: Helm, target: Window = window): () => void {
54
+ const handled = new Set([...AHEAD, ...ASTERN, ...STARBOARD, ...PORT]);
55
+ const down = (e: KeyboardEvent): void => {
56
+ if (!handled.has(e.code)) return;
57
+ e.preventDefault();
58
+ helm.press(e.code);
59
+ };
60
+ const up = (e: KeyboardEvent): void => {
61
+ if (!handled.has(e.code)) return;
62
+ helm.release(e.code);
63
+ };
64
+ const blur = (): void => helm.releaseAll();
65
+ target.addEventListener("keydown", down);
66
+ target.addEventListener("keyup", up);
67
+ target.addEventListener("blur", blur);
68
+ return () => {
69
+ target.removeEventListener("keydown", down);
70
+ target.removeEventListener("keyup", up);
71
+ target.removeEventListener("blur", blur);
72
+ };
73
+ }
@@ -0,0 +1,110 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { ARENA, CRATE, ROUND } from "./constants.js";
4
+ import { LOSS_MARGIN, boundaryAcceleration, cratesOnLine, distanceToSegment, isLost, mulberry32, nextCombo, scatter, upstreamSpawn } from "./logic.js";
5
+
6
+ const near = (a: number, b: number, eps = 1e-9, what = "") => assert.ok(Math.abs(a - b) <= eps, `${what} ${a} vs ${b}`);
7
+
8
+ test("mulberry32 repeats for a seed, differs between seeds and stays in [0, 1)", () => {
9
+ const a = mulberry32(5);
10
+ const b = mulberry32(5);
11
+ const c = mulberry32(6);
12
+ const xs = Array.from({ length: 50 }, () => a());
13
+ assert.deepEqual(xs, Array.from({ length: 50 }, () => b()));
14
+ assert.notDeepEqual(xs, Array.from({ length: 50 }, () => c()));
15
+ for (const x of xs) assert.ok(x >= 0 && x < 1);
16
+ });
17
+
18
+ test("distanceToSegment: on the segment, beside it, past either end, and for a segment that is a point", () => {
19
+ near(distanceToSegment(2, 0, 0, 0, 4, 0), 0);
20
+ near(distanceToSegment(2, 3, 0, 0, 4, 0), 3);
21
+ near(distanceToSegment(-3, 4, 0, 0, 4, 0), 5);
22
+ near(distanceToSegment(7, 4, 0, 0, 4, 0), 5);
23
+ near(distanceToSegment(3, 4, 0, 0, 0, 0), 5);
24
+ // a slanted segment: the distance from (0, 2) to the line y = x is sqrt(2)
25
+ near(distanceToSegment(0, 2, -5, -5, 5, 5), Math.SQRT2);
26
+ });
27
+
28
+ test("cratesOnLine finds exactly the crates within the radius of any span, and nothing for a line of one point", () => {
29
+ // an L: (0,0) -> (10,0) -> (10,10)
30
+ const line = [0, 0, 10, 0, 10, 10];
31
+ const crates = [
32
+ 5, 0.5, // on the first span
33
+ 10.4, 6, // beside the second span
34
+ 4, 4, // inside the corner, 4 m from both spans
35
+ -1.0, 0, // just past the start, 1 m from its end
36
+ 12.5, 12.5, // beyond the far end
37
+ ];
38
+ const out: number[] = [];
39
+ const n = cratesOnLine(line, 3, crates, 5, 1.1, out);
40
+ assert.equal(n, 3);
41
+ assert.deepEqual(out.slice(0, n), [0, 1, 3]);
42
+ assert.equal(cratesOnLine([0, 0], 1, crates, 5, 1.1, out), 0, "one point is not a line");
43
+ assert.equal(cratesOnLine(line, 3, crates, 0, 1.1, out), 0, "no crates");
44
+ });
45
+
46
+ test("a crate right at the radius is hauled and one past it is not", () => {
47
+ const line = [0, 0, 10, 0];
48
+ const out: number[] = [];
49
+ assert.equal(cratesOnLine(line, 2, [5, CRATE.catchRadius], 1, CRATE.catchRadius, out), 1);
50
+ assert.equal(cratesOnLine(line, 2, [5, CRATE.catchRadius + 1e-6], 1, CRATE.catchRadius, out), 0);
51
+ });
52
+
53
+ test("the combo starts at 1, grows inside the window, stops at the cap and starts again after a gap", () => {
54
+ assert.equal(nextCombo(0, Infinity), 1);
55
+ assert.equal(nextCombo(1, 2), 2);
56
+ assert.equal(nextCombo(2, ROUND.comboWindow), 3, "exactly the window still counts");
57
+ assert.equal(nextCombo(ROUND.maxCombo, 1), ROUND.maxCombo);
58
+ assert.equal(nextCombo(3, ROUND.comboWindow + 0.01), 1);
59
+ assert.equal(nextCombo(3, Infinity), 1);
60
+ });
61
+
62
+ test("boundaryAcceleration is zero inside the radius and pushes toward the centre in proportion to the overshoot", () => {
63
+ const out = { x: 9, z: 9 };
64
+ boundaryAcceleration(30, 40, 50, 0.9, out);
65
+ assert.deepEqual(out, { x: 0, z: 0 }, "exactly on the edge is inside");
66
+ boundaryAcceleration(60, 80, 50, 0.9, out);
67
+ // 100 m out, 50 over: a = 45 toward the centre, along (-0.6, -0.8)
68
+ near(out.x, -0.6 * 45, 1e-9, "x");
69
+ near(out.z, -0.8 * 45, 1e-9, "z");
70
+ boundaryAcceleration(-70, 0, 50, 1, out);
71
+ near(out.x, 20, 1e-9, "x from the west");
72
+ near(Math.abs(out.z), 0, 1e-12, "z");
73
+ });
74
+
75
+ test("a crate is lost only past the edge plus the margin", () => {
76
+ assert.equal(isLost(ARENA.radius, 0, ARENA.radius), false);
77
+ assert.equal(isLost(ARENA.radius + LOSS_MARGIN, 0, ARENA.radius), false);
78
+ assert.equal(isLost(ARENA.radius + LOSS_MARGIN + 0.01, 0, ARENA.radius), true);
79
+ assert.equal(isLost(0, -(ARENA.radius + LOSS_MARGIN + 1), ARENA.radius), true);
80
+ });
81
+
82
+ test("upstreamSpawn always lands inside the arena, on the side the current comes from", () => {
83
+ const rand = mulberry32(99);
84
+ const p = { x: 0, z: 0 };
85
+ for (let i = 0; i < 500; i++) {
86
+ upstreamSpawn(rand, ARENA.radius, ARENA.spawnBand, p);
87
+ const d = Math.hypot(p.x, p.z);
88
+ assert.ok(d <= ARENA.radius - 3 + 1e-9 && d >= ARENA.radius - 3 - ARENA.spawnBand - 1e-9, `distance ${d}`);
89
+ assert.ok(p.x < 0, `x ${p.x}: upstream is -X`);
90
+ }
91
+ });
92
+
93
+ test("scatter gives the count inside the ring, apart from each other, and the same for a seed", () => {
94
+ const pts = scatter(mulberry32(3), 9, 14, 56, 12);
95
+ assert.equal(pts.length, 9);
96
+ for (const p of pts) {
97
+ const d = Math.hypot(p.x, p.z);
98
+ assert.ok(d >= 14 - 1e-9 && d <= 56 + 1e-9, `ring ${d}`);
99
+ }
100
+ for (let i = 0; i < pts.length; i++) {
101
+ for (let j = i + 1; j < pts.length; j++) assert.ok(Math.hypot(pts[i]!.x - pts[j]!.x, pts[i]!.z - pts[j]!.z) >= 12 - 1e-9, "apart");
102
+ }
103
+ assert.deepEqual(scatter(mulberry32(3), 9, 14, 56, 12), pts);
104
+ assert.notDeepEqual(scatter(mulberry32(4), 9, 14, 56, 12), pts);
105
+ });
106
+
107
+ test("scatter relaxes the separation when the ring is too crowded for it, and still returns", () => {
108
+ const pts = scatter(mulberry32(1), 30, 5, 10, 50);
109
+ assert.equal(pts.length, 30);
110
+ });