motlab.js 0.1.0 → 0.1.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.
@@ -1,163 +1,163 @@
1
- // Rapier as a motlab.js simulation. The world steps at a fixed rate, and Rapier's own snapshots let any time be asked
2
- // for in any order. Use a -deterministic build of Rapier for the same result on every machine.
3
- import { simulate } from '../core/simulate.js'
4
- import { hash } from '../core/hash.js'
5
- import { dmath } from '../core/dmath.js'
6
- import { withClock } from '../core/guard.js'
7
- import { bodyViews } from '../addons/physics.js'
8
-
9
- /** @typedef {typeof import('@dimforge/rapier2d-deterministic-compat')} Rapier */
10
- /** @typedef {import('@dimforge/rapier2d-deterministic-compat').World} World */
11
- /** @typedef {import('@dimforge/rapier2d-deterministic-compat').RigidBody} RigidBody */
12
-
13
- /**
14
- * The followed bodies at one tick, in the order build() named them. Positions are px, angles radians.
15
- * @typedef {object} RapierState
16
- * @property {Float64Array} x
17
- * @property {Float64Array} y
18
- * @property {Float64Array} c Cosine of each body's angle.
19
- * @property {Float64Array} s Sine of each body's angle.
20
- * @property {Float64Array} vx px per second.
21
- * @property {Float64Array} vy
22
- * @property {Float64Array} w Angular velocity in radians per second.
23
- * @property {Uint8Array | null} world Rapier's snapshot of the whole world, on the ticks simulate() keeps.
24
- */
25
-
26
- /**
27
- * What before() gets ahead of each step.
28
- * @template I
29
- * @typedef {object} RapierStep
30
- * @property {World} world
31
- * @property {Readonly<Record<string, RigidBody>>} bodies The followed bodies, by name.
32
- * @property {Rapier} RAPIER
33
- * @property {number} tick
34
- * @property {number} t Scene time of the tick.
35
- * @property {I} input What spec.input gave for this tick.
36
- */
37
-
38
- /**
39
- * A Rapier world as a simulation: query it at any time, in any order. Build it in px; `lengthUnit` (default 100) tells
40
- * Rapier how many px make a metre, which scales its tolerances.
41
- * @template [I=undefined]
42
- * @param {Rapier} RAPIER The Rapier module after `await RAPIER.init()`.
43
- * @param {{ build: (world: World, RAPIER: Rapier) => Record<string, RigidBody>, before?: (step: RapierStep<I>) => void,
44
- * input?: (tick: number, t: number) => I, gravity?: readonly [number, number], lengthUnit?: number, hz?: number,
45
- * start?: number, snapshotEvery?: number, params?: Readonly<Record<string, unknown>> }} spec
46
- * build adds bodies and colliders, and returns the bodies to follow by name. before runs ahead of every step, to set
47
- * kinematic targets or apply forces; it must act the same whenever a tick is stepped again. gravity defaults to
48
- * [0, 980] px/s² and hz to 120; params, like the source of build and before, goes into the bake key.
49
- */
50
- export function rapier(RAPIER, { build, before, input, gravity = [0, 980], lengthUnit = 100, hz = 120, start = 0, snapshotEvery, params = {} }) {
51
- if (typeof RAPIER?.World?.restoreSnapshot !== 'function') throw new TypeError('rapier: pass the Rapier module, after await RAPIER.init()')
52
- if (typeof build !== 'function') throw new TypeError('rapier: build(world, RAPIER) must add the bodies and return the ones to follow, by name')
53
- const every = snapshotEvery ?? Math.max(1, Math.round(hz / 2))
54
-
55
- let live = new RAPIER.World({ x: gravity[0], y: gravity[1] })
56
- let freed = false
57
- live.timestep = 1 / hz
58
- live.lengthUnit = lengthUnit
59
- const made = build(live, RAPIER)
60
- if (!made || typeof made !== 'object') throw new TypeError('rapier: build must return the bodies to follow, such as { ball, box }')
61
- const names = Object.keys(made)
62
- if (names.length === 0) throw new TypeError('rapier: build must return at least one body to follow')
63
- const handles = names.map(name => {
64
- const handle = made[name]?.handle
65
- if (typeof handle !== 'number') throw new TypeError(`rapier: "${name}" from build is not a rigid body`)
66
- return handle
67
- })
68
- const n = names.length
69
- /** @type {Readonly<Record<string, RigidBody>>} */
70
- let followed = Object.freeze({ ...made })
71
- // The tick the live world is at. A step for any other tick starts from the snapshot in its state.
72
- let liveTick = 0
73
-
74
- /** @param {World} world @param {RapierState} st */
75
- const read = (world, st) => {
76
- handles.forEach((handle, i) => {
77
- const body = world.getRigidBody(handle)
78
- const p = body.translation()
79
- const v = body.linvel()
80
- const angle = body.rotation()
81
- st.x[i] = p.x
82
- st.y[i] = p.y
83
- st.c[i] = dmath.cos(angle)
84
- st.s[i] = dmath.sin(angle)
85
- st.vx[i] = v.x
86
- st.vy[i] = v.y
87
- st.w[i] = body.angvel()
88
- })
89
- }
90
-
91
- /** @type {RapierState} */
92
- const first = { x: new Float64Array(n), y: new Float64Array(n), c: new Float64Array(n), s: new Float64Array(n), vx: new Float64Array(n), vy: new Float64Array(n), w: new Float64Array(n), world: null }
93
- read(live, first)
94
- first.world = live.takeSnapshot()
95
-
96
- /** @param {RapierState} st @param {I} tickInput @param {number} dt @param {number} tick */
97
- const step = (st, tickInput, dt, tick) => {
98
- if (freed) throw new Error('rapier: this world has been disposed')
99
- if (tick !== liveTick) {
100
- if (!st.world) throw new Error(`rapier: no snapshot to step tick ${tick} from`)
101
- live.free()
102
- live = RAPIER.World.restoreSnapshot(st.world)
103
- followed = Object.freeze(Object.fromEntries(names.map((name, i) => [name, live.getRigidBody(handles[i])])))
104
- }
105
- before?.({ world: live, bodies: followed, RAPIER, tick, t: start + tick * dt, input: tickInput })
106
- // Rapier times its own stages with performance.now(); the readings never reach the result.
107
- withClock(() => live.step())
108
- liveTick = tick + 1
109
- read(live, st)
110
- st.world = liveTick % every === 0 ? live.takeSnapshot() : null
111
- }
112
-
113
- /** @param {RapierState} a @param {RapierState} b @param {number} k @returns {RapierState} */
114
- const lerp = (a, b, k) => {
115
- const out = { ...a, x: a.x.slice(), y: a.y.slice(), c: a.c.slice(), s: a.s.slice(), world: null }
116
- for (let i = 0; i < n; i++) {
117
- out.x[i] += (b.x[i] - a.x[i]) * k
118
- out.y[i] += (b.y[i] - a.y[i]) * k
119
- const c = a.c[i] + (b.c[i] - a.c[i]) * k
120
- const s = a.s[i] + (b.s[i] - a.s[i]) * k
121
- const len = Math.sqrt(c * c + s * s) || 1
122
- out.c[i] = c / len
123
- out.s[i] = s / len
124
- }
125
- return out
126
- }
127
-
128
- const sim = simulate({
129
- init: () => first, step, lerp, input, hz, start, snapshotEvery: every,
130
- params: { ...params, build: build.toString(), before: before?.toString() ?? null, gravity, lengthUnit, rapier: RAPIER.version() },
131
- })
132
-
133
- /** @param {string | number} ref */
134
- const index = ref => {
135
- const i = typeof ref === 'number' ? ref : names.indexOf(ref)
136
- if (!(i >= 0 && i < n)) throw new RangeError(`rapier: no followed body "${ref}". Bodies are ${names.join(', ')}`)
137
- return i
138
- }
139
-
140
- const dispose = () => {
141
- if (freed) return
142
- freed = true
143
- live.free()
144
- }
145
-
146
- return Object.freeze({
147
- sim,
148
- /** The followed bodies' names, in state order. */
149
- names: Object.freeze(names),
150
- /** @param {number} t */
151
- at: t => sim.at(t),
152
- index,
153
- ...bodyViews(sim, index),
154
- /** Frees the underlying Rapier WASM world. */
155
- dispose,
156
- free: dispose,
157
- /** A hash of the followed bodies at a tick, for checking that two machines agree. @param {number} tick */
158
- hash: tick => {
159
- const { world, ...bodies } = sim.tick(tick)
160
- return hash(bodies)
161
- },
162
- })
163
- }
1
+ // Rapier as a motlab.js simulation. The world steps at a fixed rate, and Rapier's own snapshots let any time be asked
2
+ // for in any order. Use a -deterministic build of Rapier for the same result on every machine.
3
+ import { simulate } from '../core/simulate.js'
4
+ import { hash } from '../core/hash.js'
5
+ import { dmath } from '../core/dmath.js'
6
+ import { withClock } from '../core/guard.js'
7
+ import { bodyViews } from '../addons/physics.js'
8
+
9
+ /** @typedef {typeof import('@dimforge/rapier2d-deterministic-compat')} Rapier */
10
+ /** @typedef {import('@dimforge/rapier2d-deterministic-compat').World} World */
11
+ /** @typedef {import('@dimforge/rapier2d-deterministic-compat').RigidBody} RigidBody */
12
+
13
+ /**
14
+ * The followed bodies at one tick, in the order build() named them. Positions are px, angles radians.
15
+ * @typedef {object} RapierState
16
+ * @property {Float64Array} x
17
+ * @property {Float64Array} y
18
+ * @property {Float64Array} c Cosine of each body's angle.
19
+ * @property {Float64Array} s Sine of each body's angle.
20
+ * @property {Float64Array} vx px per second.
21
+ * @property {Float64Array} vy
22
+ * @property {Float64Array} w Angular velocity in radians per second.
23
+ * @property {Uint8Array | null} world Rapier's snapshot of the whole world, on the ticks simulate() keeps.
24
+ */
25
+
26
+ /**
27
+ * What before() gets ahead of each step.
28
+ * @template I
29
+ * @typedef {object} RapierStep
30
+ * @property {World} world
31
+ * @property {Readonly<Record<string, RigidBody>>} bodies The followed bodies, by name.
32
+ * @property {Rapier} RAPIER
33
+ * @property {number} tick
34
+ * @property {number} t Scene time of the tick.
35
+ * @property {I} input What spec.input gave for this tick.
36
+ */
37
+
38
+ /**
39
+ * A Rapier world as a simulation: query it at any time, in any order. Build it in px; `lengthUnit` (default 100) tells
40
+ * Rapier how many px make a metre, which scales its tolerances.
41
+ * @template [I=undefined]
42
+ * @param {Rapier} RAPIER The Rapier module after `await RAPIER.init()`.
43
+ * @param {{ build: (world: World, RAPIER: Rapier) => Record<string, RigidBody>, before?: (step: RapierStep<I>) => void,
44
+ * input?: (tick: number, t: number) => I, gravity?: readonly [number, number], lengthUnit?: number, hz?: number,
45
+ * start?: number, snapshotEvery?: number, params?: Readonly<Record<string, unknown>> }} spec
46
+ * build adds bodies and colliders, and returns the bodies to follow by name. before runs ahead of every step, to set
47
+ * kinematic targets or apply forces; it must act the same whenever a tick is stepped again. gravity defaults to
48
+ * [0, 980] px/s² and hz to 120; params, like the source of build and before, goes into the bake key.
49
+ */
50
+ export function rapier(RAPIER, { build, before, input, gravity = [0, 980], lengthUnit = 100, hz = 120, start = 0, snapshotEvery, params = {} }) {
51
+ if (typeof RAPIER?.World?.restoreSnapshot !== 'function') throw new TypeError('rapier: pass the Rapier module, after await RAPIER.init()')
52
+ if (typeof build !== 'function') throw new TypeError('rapier: build(world, RAPIER) must add the bodies and return the ones to follow, by name')
53
+ const every = snapshotEvery ?? Math.max(1, Math.round(hz / 2))
54
+
55
+ let live = new RAPIER.World({ x: gravity[0], y: gravity[1] })
56
+ let freed = false
57
+ live.timestep = 1 / hz
58
+ live.lengthUnit = lengthUnit
59
+ const made = build(live, RAPIER)
60
+ if (!made || typeof made !== 'object') throw new TypeError('rapier: build must return the bodies to follow, such as { ball, box }')
61
+ const names = Object.keys(made)
62
+ if (names.length === 0) throw new TypeError('rapier: build must return at least one body to follow')
63
+ const handles = names.map(name => {
64
+ const handle = made[name]?.handle
65
+ if (typeof handle !== 'number') throw new TypeError(`rapier: "${name}" from build is not a rigid body`)
66
+ return handle
67
+ })
68
+ const n = names.length
69
+ /** @type {Readonly<Record<string, RigidBody>>} */
70
+ let followed = Object.freeze({ ...made })
71
+ // The tick the live world is at. A step for any other tick starts from the snapshot in its state.
72
+ let liveTick = 0
73
+
74
+ /** @param {World} world @param {RapierState} st */
75
+ const read = (world, st) => {
76
+ handles.forEach((handle, i) => {
77
+ const body = world.getRigidBody(handle)
78
+ const p = body.translation()
79
+ const v = body.linvel()
80
+ const angle = body.rotation()
81
+ st.x[i] = p.x
82
+ st.y[i] = p.y
83
+ st.c[i] = dmath.cos(angle)
84
+ st.s[i] = dmath.sin(angle)
85
+ st.vx[i] = v.x
86
+ st.vy[i] = v.y
87
+ st.w[i] = body.angvel()
88
+ })
89
+ }
90
+
91
+ /** @type {RapierState} */
92
+ const first = { x: new Float64Array(n), y: new Float64Array(n), c: new Float64Array(n), s: new Float64Array(n), vx: new Float64Array(n), vy: new Float64Array(n), w: new Float64Array(n), world: null }
93
+ read(live, first)
94
+ first.world = live.takeSnapshot()
95
+
96
+ /** @param {RapierState} st @param {I} tickInput @param {number} dt @param {number} tick */
97
+ const step = (st, tickInput, dt, tick) => {
98
+ if (freed) throw new Error('rapier: this world has been disposed')
99
+ if (tick !== liveTick) {
100
+ if (!st.world) throw new Error(`rapier: no snapshot to step tick ${tick} from`)
101
+ live.free()
102
+ live = RAPIER.World.restoreSnapshot(st.world)
103
+ followed = Object.freeze(Object.fromEntries(names.map((name, i) => [name, live.getRigidBody(handles[i])])))
104
+ }
105
+ before?.({ world: live, bodies: followed, RAPIER, tick, t: start + tick * dt, input: tickInput })
106
+ // Rapier times its own stages with performance.now(); the readings never reach the result.
107
+ withClock(() => live.step())
108
+ liveTick = tick + 1
109
+ read(live, st)
110
+ st.world = liveTick % every === 0 ? live.takeSnapshot() : null
111
+ }
112
+
113
+ /** @param {RapierState} a @param {RapierState} b @param {number} k @returns {RapierState} */
114
+ const lerp = (a, b, k) => {
115
+ const out = { ...a, x: a.x.slice(), y: a.y.slice(), c: a.c.slice(), s: a.s.slice(), world: null }
116
+ for (let i = 0; i < n; i++) {
117
+ out.x[i] += (b.x[i] - a.x[i]) * k
118
+ out.y[i] += (b.y[i] - a.y[i]) * k
119
+ const c = a.c[i] + (b.c[i] - a.c[i]) * k
120
+ const s = a.s[i] + (b.s[i] - a.s[i]) * k
121
+ const len = Math.sqrt(c * c + s * s) || 1
122
+ out.c[i] = c / len
123
+ out.s[i] = s / len
124
+ }
125
+ return out
126
+ }
127
+
128
+ const sim = simulate({
129
+ init: () => first, step, lerp, input, hz, start, snapshotEvery: every,
130
+ params: { ...params, build: build.toString(), before: before?.toString() ?? null, gravity, lengthUnit, rapier: RAPIER.version() },
131
+ })
132
+
133
+ /** @param {string | number} ref */
134
+ const index = ref => {
135
+ const i = typeof ref === 'number' ? ref : names.indexOf(ref)
136
+ if (!(i >= 0 && i < n)) throw new RangeError(`rapier: no followed body "${ref}". Bodies are ${names.join(', ')}`)
137
+ return i
138
+ }
139
+
140
+ const dispose = () => {
141
+ if (freed) return
142
+ freed = true
143
+ live.free()
144
+ }
145
+
146
+ return Object.freeze({
147
+ sim,
148
+ /** The followed bodies' names, in state order. */
149
+ names: Object.freeze(names),
150
+ /** @param {number} t */
151
+ at: t => sim.at(t),
152
+ index,
153
+ ...bodyViews(sim, index),
154
+ /** Frees the underlying Rapier WASM world. */
155
+ dispose,
156
+ free: dispose,
157
+ /** A hash of the followed bodies at a tick, for checking that two machines agree. @param {number} tick */
158
+ hash: tick => {
159
+ const { world, ...bodies } = sim.tick(tick)
160
+ return hash(bodies)
161
+ },
162
+ })
163
+ }