@zaisma/physics 0.0.0-stage → 2.4.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.
package/declare.js ADDED
@@ -0,0 +1,495 @@
1
+ // A physics world as a game declares it: its bodies (the floor, the walls, the furniture), its characters' size,
2
+ // and where they start. Plain data, checked once, with no engine in it: a game writes it in one file that its page
3
+ // and its game server both import, so every side builds exactly the same world. The reference is index.d.ts.
4
+ import { PieceError } from "../piece/index.js";
5
+
6
+ export const PIECE_NAME = "@zaisma/physics";
7
+
8
+ /** Throws this piece's error: code stable, field the argument at fault (or null), fix what to do. */
9
+ export function refuse(code, message, field, fix) {
10
+ throw new PieceError(PIECE_NAME, code, { message, field: field ?? null, fix });
11
+ }
12
+
13
+ export const MOTION_KINDS = ["moving", "kinematic", "fixed"];
14
+ export const SHAPE_KINDS = ["box", "ball", "capsule", "cylinder", "hull", "mesh", "heightfield"];
15
+ export const JOINT_KINDS = ["fixed", "ball", "hinge", "slider", "spring", "rope"];
16
+ export const PLAYER_CHARACTER_MODES = ["on_join", "by_game"];
17
+ const ID_PATTERN = /^[A-Za-z0-9_.:-]{1,64}$/;
18
+
19
+ /** Bodies one world holds at most, declared and added while playing together. */
20
+ export const MAXIMUM_BODY_COUNT = 1000;
21
+ /** Characters one world holds at most: players' and bots'. */
22
+ export const MAXIMUM_CHARACTER_COUNT = 64;
23
+ const MAXIMUM_SHAPE_COUNT = 16;
24
+ const MAXIMUM_HULL_POINT_COUNT = 255;
25
+ const MAXIMUM_MESH_TRIANGLE_COUNT = 50_000;
26
+ /** A mesh read from a data file may be a whole level's ground: this many triangles at most. */
27
+ export const MAXIMUM_DATA_MESH_TRIANGLE_COUNT = 2_000_000;
28
+ /** A heightfield's rows and columns of heights, at most: 4,096 by 4,096 is a 4 km valley at a metre a cell. */
29
+ const MAXIMUM_HEIGHTFIELD_SIDE_COUNT = 4096;
30
+ /** Collision layers one world declares at most (the engine's groups are 16 bits), the built-in "riding" among them. */
31
+ export const MAXIMUM_COLLISION_LAYER_COUNT = 16;
32
+ /** Joints one world holds at most, declared and added while playing together. */
33
+ export const MAXIMUM_JOINT_COUNT = 1000;
34
+ const MAXIMUM_WHEEL_COUNT = 8;
35
+ const MAXIMUM_SEAT_COUNT = 8;
36
+ /** The layer a character riding in a seat is on: it touches nothing, not its seat nor the body under it. */
37
+ export const RIDING_LAYER_NAME = "riding";
38
+ /** The layers a world has when it declares none: everything touches everything. */
39
+ const DEFAULT_LAYER_NAMES = ["world", "body", "character"];
40
+ /** How far from the middle of the world anything may be, in metres. */
41
+ export const WORLD_REACH_M = 10_000;
42
+ /** How heavy a cubic metre of a body is when it doesn't say its mass: furniture is mostly air. */
43
+ export const DEFAULT_DENSITY_KG_PER_M3_NUMBER = 250;
44
+
45
+ const WORLD_KEYS = ["bodies", "bodyKinds", "character", "playerCharacterMode", "startPositionsM", "fallOutHeightM", "collisionLayers", "joints", "substepCount", "groundReachM"];
46
+ const BODY_KEYS = ["id", "bodyKindName", "motionKind", "positionM", "rotationDeg", "massKg", "bouncePct", "gripPct", "linearDampingNumber", "angularDampingNumber", "canBeGrabbed", "shapes", "collisionLayerName", "wheels", "vehicle", "seats"];
47
+ const BODY_KIND_KEYS = ["massKg", "bouncePct", "gripPct", "linearDampingNumber", "angularDampingNumber", "canBeGrabbed", "shapes", "collisionLayerName", "wheels", "vehicle", "seats"];
48
+ const WHEEL_KEYS = ["positionM", "radiusM", "suspensionRestM", "suspensionTravelM", "isSteered", "isDriven"];
49
+ const VEHICLE_KEYS = ["maximumEngineForceNewtons", "maximumBrakeForceNewtons", "maximumSteerDeg", "suspensionStiffnessNumber", "suspensionDampingNumber", "frictionSlipNumber", "sideFrictionNumber", "maximumSuspensionForceNewtons", "wheelCollisionLayerNames"];
50
+ const SEAT_KEYS = ["positionM", "facingYawDeg"];
51
+ const JOINT_KEYS = ["id", "jointKind", "bodyId", "otherBodyId", "anchorM", "otherAnchorM", "axis", "minimumNumber", "maximumNumber", "restLengthM", "stiffnessNumber", "dampingNumber"];
52
+ const COLLISION_LAYER_KEYS = ["touches"];
53
+ const DATA_PATH_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9_./-]{0,199}$/;
54
+ const BODY_KIND_NAME_PATTERN = /^[a-z][a-z0-9_]{0,39}$/;
55
+ /** Kinds of body one world declares at most. */
56
+ export const MAXIMUM_BODY_KIND_COUNT = 250;
57
+ const SHAPE_KEYS = ["shapeKind", "sizeM", "radiusM", "heightM", "pointsM", "triangleIndices", "triangleGroupNumbers", "positionM", "rotationDeg", "dataPath", "heightsM", "rowCount", "columnCount", "cellSizeM"];
58
+ /** A mesh's triangle groups a world switches on and off while playing (doors, bridges): numbered 1 to this; 0 is always there. */
59
+ export const MAXIMUM_TRIANGLE_GROUP_NUMBER = 31;
60
+ const CHARACTER_KEYS = ["heightM", "radiusM", "stepHeightM", "maximumSlopeDeg"];
61
+
62
+ const isPlainObject = (given) => given !== null && typeof given === "object" && !Array.isArray(given);
63
+ const isFiniteNumber = (given) => typeof given === "number" && Number.isFinite(given);
64
+
65
+ function refuseUnknownKeys(given, known, code, what) {
66
+ if (!isPlainObject(given)) refuse(code, `${what} isn't an object.`, what, `Give { ${known.join(", ")} }.`);
67
+ for (const key of Object.keys(given)) if (!known.includes(key)) refuse(code, `${what} has no "${key}".`, `${what}.${key}`, `It takes: ${known.join(", ")}.`);
68
+ }
69
+
70
+ /** A point given as { x, y, z } in metres, checked; fallback when left out. */
71
+ function pointOf(given, fallback, code, what) {
72
+ if (given === undefined) return { ...fallback };
73
+ if (!isPlainObject(given) || !["x", "y", "z"].every((axis) => isFiniteNumber(given[axis]) && Math.abs(given[axis]) <= WORLD_REACH_M)) {
74
+ refuse(code, `${what} isn't a point in the world.`, what, `Give { x, y, z } in metres, each within ${WORLD_REACH_M} of the middle.`);
75
+ }
76
+ return { x: given.x, y: given.y, z: given.z };
77
+ }
78
+
79
+ /**
80
+ * A turn given the way a level is written, { x, y, z } in degrees about each axis (x first, then y, then z, as
81
+ * three.js turns an object), as the rotation the engine and three.js hold: { x, y, z, w }.
82
+ */
83
+ export function rotationFromDeg(turnDeg) {
84
+ const halfXRad = (turnDeg.x * Math.PI) / 360;
85
+ const halfYRad = (turnDeg.y * Math.PI) / 360;
86
+ const halfZRad = (turnDeg.z * Math.PI) / 360;
87
+ const cosX = Math.cos(halfXRad);
88
+ const sinX = Math.sin(halfXRad);
89
+ const cosY = Math.cos(halfYRad);
90
+ const sinY = Math.sin(halfYRad);
91
+ const cosZ = Math.cos(halfZRad);
92
+ const sinZ = Math.sin(halfZRad);
93
+ return {
94
+ x: sinX * cosY * cosZ + cosX * sinY * sinZ,
95
+ y: cosX * sinY * cosZ - sinX * cosY * sinZ,
96
+ z: cosX * cosY * sinZ + sinX * sinY * cosZ,
97
+ w: cosX * cosY * cosZ - sinX * sinY * sinZ,
98
+ };
99
+ }
100
+
101
+ function rotationOf(given, code, what) {
102
+ if (given === undefined) return { x: 0, y: 0, z: 0, w: 1 };
103
+ if (!isPlainObject(given) || !["x", "y", "z"].every((axis) => isFiniteNumber(given[axis]))) refuse(code, `${what} isn't a turn.`, what, "Give { x, y, z } in degrees about each axis, like { x: 0, y: 90, z: 0 }.");
104
+ return rotationFromDeg(given);
105
+ }
106
+
107
+ function lengthOf(given, code, what, { minimumM = 0.01, maximumM = WORLD_REACH_M } = {}) {
108
+ if (!isFiniteNumber(given) || given < minimumM || given > maximumM) refuse(code, `${what} is ${JSON.stringify(given)}.`, what, `Give a length in metres from ${minimumM} to ${maximumM}.`);
109
+ return given;
110
+ }
111
+
112
+ /** One shape of a body, checked. Answers it with how much room it takes, for a body's mass when it gives none. */
113
+ function shapeOf(given, isFixed, what) {
114
+ refuseUnknownKeys(given, SHAPE_KEYS, "bad_body", what);
115
+ const { shapeKind } = given;
116
+ if (!SHAPE_KINDS.includes(shapeKind)) refuse("bad_body", `${what}.shapeKind is ${JSON.stringify(shapeKind)}.`, `${what}.shapeKind`, `Use: ${SHAPE_KINDS.join(", ")}.`);
117
+ if (shapeKind === "heightfield" || (shapeKind === "mesh" && given.dataPath !== undefined)) return groundShapeOf(given, isFixed, what);
118
+ if (shapeKind !== "mesh" && given.triangleGroupNumbers !== undefined) refuse("bad_body", `${what} is a ${shapeKind}, which has no triangleGroupNumbers.`, `${what}.triangleGroupNumbers`, "Only a mesh's triangles come in groups.");
119
+ for (const key of ["dataPath", "heightsM", "rowCount", "columnCount", "cellSizeM"]) if (given[key] !== undefined) refuse("bad_body", `${what} is a ${shapeKind}, which has no ${key}.`, `${what}.${key}`, key === "dataPath" ? "Only a mesh or a heightfield is read from a data file." : "rowCount, columnCount, cellSizeM and heightsM are a heightfield's.");
120
+ const takes = { box: ["sizeM"], ball: ["radiusM"], capsule: ["radiusM", "heightM"], cylinder: ["radiusM", "heightM"], hull: ["pointsM"], mesh: ["pointsM", "triangleIndices"] }[shapeKind];
121
+ for (const key of ["sizeM", "radiusM", "heightM", "pointsM", "triangleIndices"]) {
122
+ if (takes.includes(key) !== (given[key] !== undefined)) {
123
+ refuse("bad_body", takes.includes(key) ? `${what} is a ${shapeKind} with no ${key}.` : `${what} is a ${shapeKind}, which has no ${key}.`, `${what}.${key}`, `A ${shapeKind} takes: ${takes.join(", ")}.`);
124
+ }
125
+ }
126
+ const shape = { shapeKind, sizeM: null, radiusM: null, heightM: null, pointsM: null, triangleIndices: null, triangleGroupNumbers: null, dataPath: null, heightsM: null, rowCount: null, columnCount: null, cellSizeM: null, positionM: pointOf(given.positionM, { x: 0, y: 0, z: 0 }, "bad_body", `${what}.positionM`), rotation: rotationOf(given.rotationDeg, "bad_body", `${what}.rotationDeg`) };
127
+ let volumeNumber = 0;
128
+ if (shapeKind === "box") {
129
+ if (!isPlainObject(given.sizeM)) refuse("bad_body", `${what}.sizeM isn't a size.`, `${what}.sizeM`, "Give { x, y, z }: how wide, tall and deep the box is, in metres.");
130
+ shape.sizeM = { x: lengthOf(given.sizeM.x, "bad_body", `${what}.sizeM.x`), y: lengthOf(given.sizeM.y, "bad_body", `${what}.sizeM.y`), z: lengthOf(given.sizeM.z, "bad_body", `${what}.sizeM.z`) };
131
+ volumeNumber = shape.sizeM.x * shape.sizeM.y * shape.sizeM.z;
132
+ } else if (shapeKind === "ball") {
133
+ shape.radiusM = lengthOf(given.radiusM, "bad_body", `${what}.radiusM`);
134
+ volumeNumber = (4 / 3) * Math.PI * shape.radiusM ** 3;
135
+ } else if (shapeKind === "capsule" || shapeKind === "cylinder") {
136
+ shape.radiusM = lengthOf(given.radiusM, "bad_body", `${what}.radiusM`);
137
+ shape.heightM = lengthOf(given.heightM, "bad_body", `${what}.heightM`);
138
+ if (shapeKind === "capsule" && shape.heightM < shape.radiusM * 2) refuse("bad_body", `${what} is a capsule shorter than it is wide.`, `${what}.heightM`, "A capsule's heightM is its whole height, round ends included: at least twice its radiusM. Use a ball for a round thing.");
139
+ volumeNumber = Math.PI * shape.radiusM ** 2 * shape.heightM;
140
+ } else {
141
+ const points = given.pointsM;
142
+ // A level's collision may come as a typed array the game already holds: taken as it is, never copied.
143
+ const isTyped = points instanceof Float32Array;
144
+ if (!(Array.isArray(points) || isTyped) || points.length < 12 || points.length % 3 !== 0 || Array.prototype.some.call(points, (part) => !isFiniteNumber(part) || Math.abs(part) > WORLD_REACH_M)) {
145
+ refuse("bad_body", `${what}.pointsM isn't a list of points.`, `${what}.pointsM`, "Give the points as numbers in a row, x, y, z of each in metres (a list, or a Float32Array): at least four points.");
146
+ }
147
+ shape.pointsM = isTyped ? points : points.slice();
148
+ const low = { x: Infinity, y: Infinity, z: Infinity };
149
+ const high = { x: -Infinity, y: -Infinity, z: -Infinity };
150
+ for (let index = 0; index < points.length; index += 3) {
151
+ low.x = Math.min(low.x, points[index]);
152
+ low.y = Math.min(low.y, points[index + 1]);
153
+ low.z = Math.min(low.z, points[index + 2]);
154
+ high.x = Math.max(high.x, points[index]);
155
+ high.y = Math.max(high.y, points[index + 1]);
156
+ high.z = Math.max(high.z, points[index + 2]);
157
+ }
158
+ // Half the box round it: near enough for a made-up mass, and a body that minds says its own.
159
+ volumeNumber = ((high.x - low.x) * (high.y - low.y) * (high.z - low.z)) / 2;
160
+ if (shapeKind === "hull") {
161
+ if (points.length / 3 > MAXIMUM_HULL_POINT_COUNT) refuse("bad_body", `${what} is a hull of ${points.length / 3} points.`, `${what}.pointsM`, `Give at most ${MAXIMUM_HULL_POINT_COUNT} points: a hull is the simple shape round a thing, never its every corner.`);
162
+ } else {
163
+ if (!isFixed) refuse("bad_body", `${what} is a mesh on a body that moves.`, `${what}.shapeKind`, 'A mesh is for the fixed world (a level\'s ground and walls). Give a moving body boxes, balls, capsules, cylinders or hulls: they collide well and cheaply.');
164
+ const indices = given.triangleIndices;
165
+ const pointCount = points.length / 3;
166
+ const isTypedIndices = indices instanceof Uint32Array;
167
+ const maximumTriangleCount = isTyped && isTypedIndices ? MAXIMUM_DATA_MESH_TRIANGLE_COUNT : MAXIMUM_MESH_TRIANGLE_COUNT;
168
+ if (!(Array.isArray(indices) || isTypedIndices) || !indices.length || indices.length % 3 !== 0 || indices.length / 3 > maximumTriangleCount || Array.prototype.some.call(indices, (pointIndex) => !Number.isInteger(pointIndex) || pointIndex < 0 || pointIndex >= pointCount)) {
169
+ refuse("bad_body", `${what}.triangleIndices isn't a list of triangles.`, `${what}.triangleIndices`, `Give three point indexes for each triangle, each from 0 to ${pointCount - 1}, for at most ${MAXIMUM_MESH_TRIANGLE_COUNT} triangles (${MAXIMUM_DATA_MESH_TRIANGLE_COUNT} as a Float32Array and a Uint32Array).`);
170
+ }
171
+ shape.triangleIndices = isTypedIndices ? indices : indices.slice();
172
+ shape.triangleGroupNumbers = triangleGroupsOf(given.triangleGroupNumbers, indices.length / 3, what);
173
+ }
174
+ }
175
+ return { shape, volumeNumber };
176
+ }
177
+
178
+ /** A mesh's triangle groups, checked: one number a triangle, 0 (always there) or a group from 1 to 31 the world switches. */
179
+ function triangleGroupsOf(given, triangleCount, what) {
180
+ if (given === undefined) return null;
181
+ const isList = Array.isArray(given) || given instanceof Uint8Array;
182
+ if (!isList || given.length !== triangleCount || Array.prototype.some.call(given, (groupNumber) => !Number.isInteger(groupNumber) || groupNumber < 0 || groupNumber > MAXIMUM_TRIANGLE_GROUP_NUMBER)) {
183
+ refuse("bad_body", `${what}.triangleGroupNumbers isn't a group for each of its ${triangleCount} triangles.`, `${what}.triangleGroupNumbers`, `Give one number a triangle (a list or a Uint8Array): 0 for always there, or a group from 1 to ${MAXIMUM_TRIANGLE_GROUP_NUMBER} that setTriangleGroup switches on and off (a door, a bridge).`);
184
+ }
185
+ return Uint8Array.from(given);
186
+ }
187
+
188
+ /**
189
+ * A level's ground, checked: a heightfield (rows of heights a cell apart, given or read from a data file) or a mesh
190
+ * read from a data file. Only the fixed world has one. A heightfield's file is its heights as 32-bit floats, little
191
+ * endian, row after row (a row runs along +x; the next row is cellSizeM further along +z); a mesh's file is its point
192
+ * count and triangle count as 32-bit whole numbers, then the points' x, y, z as 32-bit floats, then three point
193
+ * indexes a triangle as 32-bit whole numbers.
194
+ */
195
+ function groundShapeOf(given, isFixed, what) {
196
+ const { shapeKind } = given;
197
+ if (!isFixed) refuse("bad_body", `${what} is a ${shapeKind} on a body that moves.`, `${what}.shapeKind`, "A heightfield or a mesh read from a file is the fixed world's ground: give its body motionKind \"fixed\".");
198
+ const shape = { shapeKind, sizeM: null, radiusM: null, heightM: null, pointsM: null, triangleIndices: null, triangleGroupNumbers: null, dataPath: null, heightsM: null, rowCount: null, columnCount: null, cellSizeM: null, positionM: pointOf(given.positionM, { x: 0, y: 0, z: 0 }, "bad_body", `${what}.positionM`), rotation: rotationOf(given.rotationDeg, "bad_body", `${what}.rotationDeg`) };
199
+ for (const key of ["sizeM", "radiusM", "heightM", "pointsM", "triangleIndices", ...(shapeKind === "heightfield" ? ["triangleGroupNumbers"] : [])]) if (given[key] !== undefined) refuse("bad_body", `${what} is a ${shapeKind} ${shapeKind === "mesh" ? "read from a file" : ""}, which has no ${key}.`, `${what}.${key}`, shapeKind === "mesh" ? "A mesh gives either pointsM and triangleIndices, or dataPath." : "A heightfield takes rowCount, columnCount, cellSizeM, and heightsM or dataPath.");
200
+ if (given.dataPath !== undefined) {
201
+ if (typeof given.dataPath !== "string" || !DATA_PATH_PATTERN.test(given.dataPath) || given.dataPath.includes("..")) refuse("bad_body", `${what}.dataPath is ${JSON.stringify(given.dataPath)}.`, `${what}.dataPath`, 'Give the data file\'s path from the game\'s folder (and the same from zaisma-server/), like "levels/valley-heights.bin".');
202
+ shape.dataPath = given.dataPath;
203
+ }
204
+ if (shapeKind === "mesh") {
205
+ // A mesh read from a file may still say its triangles' groups; how many it has is known once the file is read.
206
+ if (given.triangleGroupNumbers !== undefined) shape.triangleGroupNumbers = triangleGroupsOf(given.triangleGroupNumbers, given.triangleGroupNumbers?.length, what);
207
+ return { shape, volumeNumber: 0 };
208
+ }
209
+ for (const key of ["rowCount", "columnCount"]) {
210
+ if (!Number.isInteger(given[key]) || given[key] < 2 || given[key] > MAXIMUM_HEIGHTFIELD_SIDE_COUNT) refuse("bad_body", `${what}.${key} is ${JSON.stringify(given[key])}.`, `${what}.${key}`, `Give how many ${key === "rowCount" ? "rows (along +z)" : "columns (along +x)"} of heights it has, from 2 to ${MAXIMUM_HEIGHTFIELD_SIDE_COUNT}.`);
211
+ shape[key] = given[key];
212
+ }
213
+ shape.cellSizeM = lengthOf(given.cellSizeM, "bad_body", `${what}.cellSizeM`, { minimumM: 0.05, maximumM: 100 });
214
+ if ((given.heightsM === undefined) === (given.dataPath === undefined)) refuse("bad_body", `${what} needs heightsM or dataPath, one of them.`, `${what}.heightsM`, "Give the heights as a list (rowCount times columnCount numbers, row after row), or dataPath for a file of them.");
215
+ if (given.heightsM !== undefined) {
216
+ const heights = given.heightsM;
217
+ const isList = Array.isArray(heights) || heights instanceof Float32Array || heights instanceof Float64Array;
218
+ if (!isList || heights.length !== shape.rowCount * shape.columnCount || Array.prototype.some.call(heights, (heightM) => !isFiniteNumber(heightM) || Math.abs(heightM) > WORLD_REACH_M)) refuse("bad_body", `${what}.heightsM isn't ${shape.rowCount * shape.columnCount} heights.`, `${what}.heightsM`, "Give rowCount times columnCount heights in metres, row after row.");
219
+ shape.heightsM = Float32Array.from(heights);
220
+ }
221
+ return { shape, volumeNumber: 0 };
222
+ }
223
+
224
+ function dampingOf(given, isFixed, what) {
225
+ if (given === undefined || given === null) return null;
226
+ if (isFixed || !isFiniteNumber(given) || given < 0 || given > 100) refuse("bad_body", `${what} is ${JSON.stringify(given)}.`, what, "Give how quickly it slows by itself, from 0 (never) to 100, on a body that moves; or leave it out for the world's.");
227
+ return given;
228
+ }
229
+
230
+ function percentOf(given, maximumPct, what) {
231
+ if (given === undefined || given === null) return null;
232
+ if (!isFiniteNumber(given) || given < 0 || given > maximumPct) refuse("bad_body", `${what} is ${JSON.stringify(given)}.`, what, `Give a number from 0 to ${maximumPct}, or leave it out for the feel's own.`);
233
+ return given;
234
+ }
235
+
236
+ /**
237
+ * One body's declaration, checked: a thing in the world with shapes of its own, or one of the world's kinds of body
238
+ * (bodyKinds: checkBodyKinds's answer) by its bodyKindName. Answers it whole, every field there, as the simulation
239
+ * takes it. Throws PieceError "bad_body" naming the field at fault.
240
+ */
241
+ export function checkBody(declared, what = "body", bodyKinds = []) {
242
+ refuseUnknownKeys(declared, BODY_KEYS, "bad_body", what);
243
+ let given = declared;
244
+ let bodyKindNumber = 0;
245
+ if (declared.bodyKindName !== undefined) {
246
+ bodyKindNumber = bodyKinds.findIndex((bodyKind) => bodyKind.name === declared.bodyKindName) + 1;
247
+ if (bodyKindNumber === 0) refuse("bad_body", `${what}.bodyKindName is ${JSON.stringify(declared.bodyKindName)}.`, `${what}.bodyKindName`, bodyKinds.length ? `Use one of the world's bodyKinds: ${bodyKinds.map((bodyKind) => bodyKind.name).join(", ")}.` : "Declare the kind in the world's bodyKinds first, or give the body shapes of its own.");
248
+ for (const key of [...BODY_KIND_KEYS, "motionKind"]) if (declared[key] !== undefined) refuse("bad_body", `${what} has a bodyKindName and its own ${key}.`, `${what}.${key}`, `Leave ${key} out: a body of a kind is what the kind says. Give it shapes of its own instead of a bodyKindName to make it different.`);
249
+ given = { ...bodyKinds[bodyKindNumber - 1].declared, id: declared.id, positionM: declared.positionM, rotationDeg: declared.rotationDeg };
250
+ for (const key of Object.keys(given)) if (given[key] === undefined) delete given[key];
251
+ }
252
+ const { id, motionKind = "moving" } = given;
253
+ if (typeof id !== "string" || !ID_PATTERN.test(id)) refuse("bad_body", `${what}.id is ${JSON.stringify(id)}.`, `${what}.id`, 'Give 1 to 64 letters, digits, "_", ".", ":" or "-", like "sofa" or "crate:3".');
254
+ if (!MOTION_KINDS.includes(motionKind)) refuse("bad_body", `${what}.motionKind is ${JSON.stringify(motionKind)}.`, `${what}.motionKind`, 'Use "moving" for a thing physics moves (the default), "fixed" for the world that never moves.');
255
+ const isFixed = motionKind === "fixed";
256
+ if (given.collisionLayerName !== undefined && (typeof given.collisionLayerName !== "string" || !BODY_KIND_NAME_PATTERN.test(given.collisionLayerName))) refuse("bad_body", `${what}.collisionLayerName is ${JSON.stringify(given.collisionLayerName)}.`, `${what}.collisionLayerName`, "Give the name of one of the world's collisionLayers.");
257
+ if (!Array.isArray(given.shapes) || !given.shapes.length || given.shapes.length > MAXIMUM_SHAPE_COUNT) refuse("bad_body", `${what}.shapes isn't a list of 1 to ${MAXIMUM_SHAPE_COUNT} shapes.`, `${what}.shapes`, 'Give its shapes, like [{ shapeKind: "box", sizeM: { x: 2, y: 0.8, z: 0.9 } }].');
258
+ const shaped = given.shapes.map((shape, shapeIndex) => shapeOf(shape, isFixed, `${what}.shapes[${shapeIndex}]`));
259
+ let massKg = null;
260
+ if (!isFixed) {
261
+ if (given.massKg === undefined || given.massKg === null) massKg = Math.min(Math.max(shaped.reduce((totalNumber, each) => totalNumber + each.volumeNumber, 0) * DEFAULT_DENSITY_KG_PER_M3_NUMBER, 0.05), 100_000);
262
+ else if (!isFiniteNumber(given.massKg) || given.massKg < 0.01 || given.massKg > 100_000) refuse("bad_body", `${what}.massKg is ${JSON.stringify(given.massKg)}.`, `${what}.massKg`, "Give how heavy it is in kilograms, from 0.01 to 100000, or leave it out for one worked out from its size.");
263
+ else massKg = given.massKg;
264
+ } else if (given.massKg !== undefined && given.massKg !== null) refuse("bad_body", `${what} is fixed, which has no massKg.`, `${what}.massKg`, "Leave massKg out: the fixed world never moves, however hard it's hit.");
265
+ const wheels = checkWheels(given.wheels, isFixed, what);
266
+ const vehicle = checkVehicle(given.vehicle, wheels, what);
267
+ const seats = checkSeats(given.seats, isFixed, what);
268
+ if (given.canBeGrabbed !== undefined && typeof given.canBeGrabbed !== "boolean") refuse("bad_body", `${what}.canBeGrabbed isn't true or false.`, `${what}.canBeGrabbed`, "Give true or false, or leave it out: a moving body can be grabbed, the fixed world can't.");
269
+ if (given.canBeGrabbed === true && isFixed) refuse("bad_body", `${what} is fixed and canBeGrabbed.`, `${what}.canBeGrabbed`, "Only a moving body can be grabbed and carried.");
270
+ return {
271
+ id,
272
+ // 0 for a body with shapes of its own; else the place of its kind among the world's bodyKinds, from 1.
273
+ bodyKindNumber,
274
+ motionKind,
275
+ positionM: pointOf(given.positionM, { x: 0, y: 0, z: 0 }, "bad_body", `${what}.positionM`),
276
+ rotation: rotationOf(given.rotationDeg, "bad_body", `${what}.rotationDeg`),
277
+ massKg,
278
+ bouncePct: percentOf(given.bouncePct, 100, `${what}.bouncePct`),
279
+ gripPct: percentOf(given.gripPct, 300, `${what}.gripPct`),
280
+ // null: the world's (0.05 and 0.2): how quickly a body's speed and spin die away by themselves.
281
+ linearDampingNumber: dampingOf(given.linearDampingNumber, isFixed, `${what}.linearDampingNumber`),
282
+ angularDampingNumber: dampingOf(given.angularDampingNumber, isFixed, `${what}.angularDampingNumber`),
283
+ canBeGrabbed: given.canBeGrabbed ?? motionKind === "moving",
284
+ shapes: shaped.map((each) => each.shape),
285
+ collisionLayerName: given.collisionLayerName ?? (isFixed ? "world" : "body"),
286
+ wheels,
287
+ vehicle,
288
+ seats,
289
+ };
290
+ }
291
+
292
+ /** A vehicle's wheels, checked: each where it hangs from the body, its size and its springs. */
293
+ function checkWheels(given, isFixed, what) {
294
+ if (given === undefined) return [];
295
+ if (isFixed || !Array.isArray(given) || !given.length || given.length > MAXIMUM_WHEEL_COUNT) refuse("bad_body", `${what}.wheels isn't a list of 1 to ${MAXIMUM_WHEEL_COUNT} wheels on a body that moves.`, `${what}.wheels`, 'Give each wheel as { positionM, radiusM, isSteered, isDriven }: where it hangs from the body, like { x: -0.8, y: -0.2, z: 1.3 } for the front left.');
296
+ return given.map((wheel, wheelIndex) => {
297
+ const wheelWhat = `${what}.wheels[${wheelIndex}]`;
298
+ refuseUnknownKeys(wheel, WHEEL_KEYS, "bad_body", wheelWhat);
299
+ for (const key of ["isSteered", "isDriven"]) if (wheel[key] !== undefined && typeof wheel[key] !== "boolean") refuse("bad_body", `${wheelWhat}.${key} isn't true or false.`, `${wheelWhat}.${key}`, "Give true or false.");
300
+ return {
301
+ positionM: pointOf(wheel.positionM, { x: 0, y: 0, z: 0 }, "bad_body", `${wheelWhat}.positionM`),
302
+ radiusM: lengthOf(wheel.radiusM, "bad_body", `${wheelWhat}.radiusM`, { minimumM: 0.02, maximumM: 5 }),
303
+ suspensionRestM: wheel.suspensionRestM === undefined ? 0.3 : lengthOf(wheel.suspensionRestM, "bad_body", `${wheelWhat}.suspensionRestM`, { minimumM: 0.01, maximumM: 3 }),
304
+ suspensionTravelM: wheel.suspensionTravelM === undefined ? 0.25 : lengthOf(wheel.suspensionTravelM, "bad_body", `${wheelWhat}.suspensionTravelM`, { minimumM: 0.01, maximumM: 3 }),
305
+ isSteered: wheel.isSteered ?? false,
306
+ isDriven: wheel.isDriven ?? true,
307
+ };
308
+ });
309
+ }
310
+
311
+ const positiveNumberOf = (given, fallbackNumber, maximumNumber, what) => {
312
+ if (given === undefined) return fallbackNumber;
313
+ if (!isFiniteNumber(given) || given < 0 || given > maximumNumber) refuse("bad_body", `${what} is ${JSON.stringify(given)}.`, what, `Give a number from 0 to ${maximumNumber}, or leave it out.`);
314
+ return given;
315
+ };
316
+
317
+ /** How a vehicle drives, checked: its engine, brakes, steering and springs. Only a body with wheels has one. */
318
+ function checkVehicle(given, wheels, what) {
319
+ if (given === undefined) return wheels.length ? checkVehicle({}, wheels, what) : null;
320
+ if (!wheels.length) refuse("bad_body", `${what} has a vehicle but no wheels.`, `${what}.vehicle`, "Give it wheels too, or leave vehicle out.");
321
+ refuseUnknownKeys(given, VEHICLE_KEYS, "bad_body", `${what}.vehicle`);
322
+ return {
323
+ maximumEngineForceNewtons: positiveNumberOf(given.maximumEngineForceNewtons, 4000, 1_000_000, `${what}.vehicle.maximumEngineForceNewtons`),
324
+ maximumBrakeForceNewtons: positiveNumberOf(given.maximumBrakeForceNewtons, 60, 1_000_000, `${what}.vehicle.maximumBrakeForceNewtons`),
325
+ maximumSteerDeg: positiveNumberOf(given.maximumSteerDeg, 32, 80, `${what}.vehicle.maximumSteerDeg`),
326
+ suspensionStiffnessNumber: positiveNumberOf(given.suspensionStiffnessNumber, 28, 1000, `${what}.vehicle.suspensionStiffnessNumber`),
327
+ suspensionDampingNumber: positiveNumberOf(given.suspensionDampingNumber, 2.3, 100, `${what}.vehicle.suspensionDampingNumber`),
328
+ frictionSlipNumber: positiveNumberOf(given.frictionSlipNumber, 10.5, 1000, `${what}.vehicle.frictionSlipNumber`),
329
+ sideFrictionNumber: positiveNumberOf(given.sideFrictionNumber, 1, 10, `${what}.vehicle.sideFrictionNumber`),
330
+ // null: the engine's 6,000 N, or more for a heavy vehicle (two and a half times its weight on each wheel).
331
+ maximumSuspensionForceNewtons: given.maximumSuspensionForceNewtons === undefined ? null : positiveNumberOf(given.maximumSuspensionForceNewtons, null, 10_000_000, `${what}.vehicle.maximumSuspensionForceNewtons`),
332
+ // null: every layer the vehicle touches but characters'.
333
+ wheelCollisionLayerNames: wheelLayerNamesOf(given.wheelCollisionLayerNames, `${what}.vehicle.wheelCollisionLayerNames`),
334
+ };
335
+ }
336
+
337
+ function wheelLayerNamesOf(given, what) {
338
+ if (given === undefined) return null;
339
+ if (!Array.isArray(given) || given.length > MAXIMUM_COLLISION_LAYER_COUNT || given.some((name) => typeof name !== "string" || !BODY_KIND_NAME_PATTERN.test(name))) refuse("bad_body", `${what} isn't a list of collision layers' names.`, what, 'Give the layers the wheels stand on, like ["world"]; or leave it out for every layer the vehicle touches but characters\'.');
340
+ return [...given];
341
+ }
342
+
343
+ /** Where characters sit on a body (a car's seats, a cart's bench), checked. */
344
+ function checkSeats(given, isFixed, what) {
345
+ if (given === undefined) return [];
346
+ if (!Array.isArray(given) || !given.length || given.length > MAXIMUM_SEAT_COUNT) refuse("bad_body", `${what}.seats isn't a list of 1 to ${MAXIMUM_SEAT_COUNT} seats.`, `${what}.seats`, "Give where each sitter's feet go on the body, like [{ positionM: { x: -0.4, y: 0.2, z: 0.1 } }]: the first is the driver's.");
347
+ return given.map((seat, seatIndex) => {
348
+ const seatWhat = `${what}.seats[${seatIndex}]`;
349
+ refuseUnknownKeys(seat, SEAT_KEYS, "bad_body", seatWhat);
350
+ if (seat.facingYawDeg !== undefined && !isFiniteNumber(seat.facingYawDeg)) refuse("bad_body", `${seatWhat}.facingYawDeg isn't a number.`, `${seatWhat}.facingYawDeg`, "Give which way a sitter faces, in degrees about the body's up, or leave it out for the body's forward (+z).");
351
+ return { positionM: pointOf(seat.positionM, { x: 0, y: 0, z: 0 }, "bad_body", `${seatWhat}.positionM`), facingYawRad: ((seat.facingYawDeg ?? 0) * Math.PI) / 180 };
352
+ });
353
+ }
354
+
355
+ /** The world's collision layers, checked: names, and which touch which (both ways). Answers [{ name, touchedNames }], "riding" last. */
356
+ function checkCollisionLayers(given) {
357
+ const declared = given === undefined ? Object.fromEntries(DEFAULT_LAYER_NAMES.map((name) => [name, { touches: DEFAULT_LAYER_NAMES }])) : given;
358
+ if (!isPlainObject(declared) || !Object.keys(declared).length || Object.keys(declared).length > MAXIMUM_COLLISION_LAYER_COUNT - 1) refuse("bad_world", `world.collisionLayers isn't an object of 1 to ${MAXIMUM_COLLISION_LAYER_COUNT - 1} layers, by name.`, "world.collisionLayers", 'Give an object like { world: { touches: ["world", "body", "character"] }, body: { touches: ["world", "body", "character"] }, character: { touches: ["world", "body"] } }.');
359
+ const names = Object.keys(declared);
360
+ for (const name of names) {
361
+ if (!BODY_KIND_NAME_PATTERN.test(name) || name === RIDING_LAYER_NAME) refuse("bad_world", `"${name}" isn't a collision layer's name.`, `world.collisionLayers.${name}`, `Give lowercase words joined by underscores, like "vehicle"; "${RIDING_LAYER_NAME}" is the piece's own (what sits in a seat touches nothing).`);
362
+ refuseUnknownKeys(declared[name], COLLISION_LAYER_KEYS, "bad_world", `world.collisionLayers.${name}`);
363
+ const touches = declared[name].touches ?? [];
364
+ if (!Array.isArray(touches) || touches.some((touched) => !names.includes(touched))) refuse("bad_world", `world.collisionLayers.${name}.touches names a layer the world doesn't have.`, `world.collisionLayers.${name}.touches`, `Give names from: ${names.join(", ")}.`);
365
+ }
366
+ for (const needed of ["world", "body", "character"]) if (!names.includes(needed)) refuse("bad_world", `world.collisionLayers has no "${needed}".`, "world.collisionLayers", 'Declare "world" (the fixed world\'s), "body" (moving bodies\') and "character" (characters\') too: they\'re where things are unless they name another.');
367
+ // Touching goes both ways: a layer touches another when either says so.
368
+ const layers = names.map((name) => ({ name, touchedNames: new Set(declared[name].touches ?? []) }));
369
+ for (const layer of layers) for (const other of layers) if (other.touchedNames.has(layer.name)) layer.touchedNames.add(other.name);
370
+ return [...layers.map((layer) => ({ name: layer.name, touchedNames: [...layer.touchedNames] })), { name: RIDING_LAYER_NAME, touchedNames: [] }];
371
+ }
372
+
373
+ /** A joint's declaration, checked: two bodies (or a body and the world) held together as its kind holds them. */
374
+ export function checkJoint(given, what, bodyIdOf = () => true) {
375
+ refuseUnknownKeys(given, JOINT_KEYS, "bad_joint", what);
376
+ const { id, jointKind, bodyId, otherBodyId = null } = given;
377
+ if (typeof id !== "string" || !ID_PATTERN.test(id)) refuse("bad_joint", `${what}.id is ${JSON.stringify(id)}.`, `${what}.id`, 'Give 1 to 64 letters, digits, "_", ".", ":" or "-", like "cart:1:hitch".');
378
+ if (!JOINT_KINDS.includes(jointKind)) refuse("bad_joint", `${what}.jointKind is ${JSON.stringify(jointKind)}.`, `${what}.jointKind`, `Use: ${JOINT_KINDS.join(", ")}.`);
379
+ for (const [key, given] of [["bodyId", bodyId], ["otherBodyId", otherBodyId]]) {
380
+ if (key === "otherBodyId" && given === null) continue;
381
+ if (typeof given !== "string" || !bodyIdOf(given)) refuse("bad_joint", `${what}.${key} is ${JSON.stringify(given)}.`, `${what}.${key}`, key === "otherBodyId" ? "Give the id of the other body or character it holds, or leave it out to hold the body to where it is in the world." : "Give the id of a body (or a character) in the world.");
382
+ }
383
+ const numberOf = (key, fallbackNumber, minimumNumber, maximumNumber) => {
384
+ if (given[key] === undefined) return fallbackNumber;
385
+ if (!isFiniteNumber(given[key]) || given[key] < minimumNumber || given[key] > maximumNumber) refuse("bad_joint", `${what}.${key} is ${JSON.stringify(given[key])}.`, `${what}.${key}`, `Give a number from ${minimumNumber} to ${maximumNumber}, or leave it out.`);
386
+ return given[key];
387
+ };
388
+ const axis = pointOf(given.axis, { x: 0, y: 1, z: 0 }, "bad_joint", `${what}.axis`);
389
+ if (Math.hypot(axis.x, axis.y, axis.z) < 1e-6) refuse("bad_joint", `${what}.axis has no length.`, `${what}.axis`, "Give the direction it turns about (a hinge) or slides along (a slider), like { x: 0, y: 1, z: 0 }.");
390
+ return {
391
+ id,
392
+ jointKind,
393
+ bodyId,
394
+ otherBodyId,
395
+ anchorM: pointOf(given.anchorM, { x: 0, y: 0, z: 0 }, "bad_joint", `${what}.anchorM`),
396
+ otherAnchorM: pointOf(given.otherAnchorM, { x: 0, y: 0, z: 0 }, "bad_joint", `${what}.otherAnchorM`),
397
+ axis,
398
+ minimumNumber: given.minimumNumber === undefined ? null : numberOf("minimumNumber", 0, -WORLD_REACH_M, WORLD_REACH_M),
399
+ maximumNumber: given.maximumNumber === undefined ? null : numberOf("maximumNumber", 0, -WORLD_REACH_M, WORLD_REACH_M),
400
+ restLengthM: numberOf("restLengthM", 0, 0, WORLD_REACH_M),
401
+ stiffnessNumber: numberOf("stiffnessNumber", 2000, 0, 1e9),
402
+ dampingNumber: numberOf("dampingNumber", 100, 0, 1e9),
403
+ };
404
+ }
405
+
406
+ /**
407
+ * A world's kinds of body, checked: what a body is made of, by a name, for bodies that are alike (three boxes) and
408
+ * for bodies added while playing, which every side must already know how to make. Answers [{ name, declared }].
409
+ */
410
+ function checkBodyKinds(given) {
411
+ if (given === undefined) return [];
412
+ if (!isPlainObject(given) || Object.keys(given).length > MAXIMUM_BODY_KIND_COUNT) refuse("bad_world", `world.bodyKinds isn't an object of up to ${MAXIMUM_BODY_KIND_COUNT} kinds of body, by name.`, "world.bodyKinds", 'Give an object like { crate: { massKg: 8, shapes: [{ shapeKind: "box", sizeM: { x: 0.6, y: 0.6, z: 0.6 } }] } }.');
413
+ return Object.entries(given).map(([name, declared]) => {
414
+ const what = `world.bodyKinds.${name}`;
415
+ if (!BODY_KIND_NAME_PATTERN.test(name)) refuse("bad_world", `"${name}" isn't a kind of body's name.`, what, 'Give lowercase words joined by underscores, like "crate" or "garden_chair".');
416
+ refuseUnknownKeys(declared, BODY_KIND_KEYS, "bad_body", what);
417
+ // Checked as a body of that kind would be: a kind is always of bodies that move.
418
+ checkBody({ ...declared, id: "kind" }, what);
419
+ return { name, declared: { ...declared } };
420
+ });
421
+ }
422
+
423
+ /**
424
+ * A physics world, checked: what createPhysics and physicsKind take. Write it in a file of its own that the game's
425
+ * page and, with a game server, the game server both import, so both build the same world. Throws PieceError
426
+ * "bad_world" or "bad_body" naming the field at fault.
427
+ */
428
+ export function definePhysicsWorld(given = {}) {
429
+ refuseUnknownKeys(given, WORLD_KEYS, "bad_world", "world");
430
+ const { bodies = [], character = {}, playerCharacterMode = "on_join", startPositionsM = [{ x: 0, y: 0, z: 0 }], fallOutHeightM = -30, joints = [], substepCount = 2, groundReachM = 24 } = given;
431
+ const collisionLayers = checkCollisionLayers(given.collisionLayers);
432
+ const bodyKinds = checkBodyKinds(given.bodyKinds);
433
+ if (!Array.isArray(bodies) || bodies.length > MAXIMUM_BODY_COUNT) refuse("bad_world", `world.bodies isn't a list of up to ${MAXIMUM_BODY_COUNT} bodies.`, "world.bodies", 'Give the world\'s bodies, like [{ id: "floor", motionKind: "fixed", shapes: [...] }].');
434
+ const ids = new Set();
435
+ const checkedBodies = bodies.map((body, bodyIndex) => {
436
+ const checked = checkBody(body, `world.bodies[${bodyIndex}]`, bodyKinds);
437
+ if (ids.has(checked.id)) refuse("bad_world", `world.bodies names "${checked.id}" twice.`, `world.bodies[${bodyIndex}].id`, "Give each body its own id.");
438
+ ids.add(checked.id);
439
+ return checked;
440
+ });
441
+ const layerNames = collisionLayers.map((layer) => layer.name);
442
+ for (const [bodyIndex, body] of checkedBodies.entries()) if (!layerNames.includes(body.collisionLayerName)) refuse("bad_world", `world.bodies[${bodyIndex}].collisionLayerName is "${body.collisionLayerName}".`, `world.bodies[${bodyIndex}].collisionLayerName`, `Use one of the world's collisionLayers: ${layerNames.join(", ")}.`);
443
+ for (const bodyKind of bodyKinds) {
444
+ const layerName = bodyKind.declared.collisionLayerName ?? "body";
445
+ if (!layerNames.includes(layerName)) refuse("bad_world", `world.bodyKinds.${bodyKind.name}.collisionLayerName is "${layerName}".`, `world.bodyKinds.${bodyKind.name}.collisionLayerName`, `Use one of the world's collisionLayers: ${layerNames.join(", ")}.`);
446
+ }
447
+ const wheelLayerNamesOfKinds = bodyKinds.map((bodyKind) => [`world.bodyKinds.${bodyKind.name}`, bodyKind.declared.vehicle?.wheelCollisionLayerNames]);
448
+ for (const [what, wheelLayerNames] of [...checkedBodies.map((body, bodyIndex) => [`world.bodies[${bodyIndex}]`, body.vehicle?.wheelCollisionLayerNames]), ...wheelLayerNamesOfKinds]) {
449
+ for (const name of wheelLayerNames ?? []) if (!layerNames.includes(name)) refuse("bad_world", `${what}.vehicle.wheelCollisionLayerNames names "${name}".`, `${what}.vehicle.wheelCollisionLayerNames`, `Use the world's collisionLayers: ${layerNames.join(", ")}.`);
450
+ }
451
+ if (!Array.isArray(joints) || joints.length > MAXIMUM_JOINT_COUNT) refuse("bad_world", `world.joints isn't a list of up to ${MAXIMUM_JOINT_COUNT} joints.`, "world.joints", 'Give joints like [{ id: "door:hinge", jointKind: "hinge", bodyId: "door", anchorM: { x: -0.45, y: 0, z: 0 } }].');
452
+ const jointIds = new Set();
453
+ const checkedJoints = joints.map((joint, jointIndex) => {
454
+ const checked = checkJoint(joint, `world.joints[${jointIndex}]`, (bodyId) => ids.has(bodyId));
455
+ if (jointIds.has(checked.id)) refuse("bad_world", `world.joints names "${checked.id}" twice.`, `world.joints[${jointIndex}].id`, "Give each joint its own id.");
456
+ jointIds.add(checked.id);
457
+ return checked;
458
+ });
459
+ if (!Number.isInteger(substepCount) || substepCount < 1 || substepCount > 8) refuse("bad_world", `world.substepCount is ${JSON.stringify(substepCount)}.`, "world.substepCount", "Give how many times the engine steps in each of the room's fixed steps, from 1 to 8: 2 (the default) steps a 30-a-second room 60 times a second, which cars and quick things want.");
460
+ const groundReach = lengthOf(groundReachM, "bad_world", "world.groundReachM", { minimumM: 2, maximumM: 1000 });
461
+ refuseUnknownKeys(character, CHARACTER_KEYS, "bad_world", "world.character");
462
+ const radiusM = character.radiusM === undefined ? 0.28 : lengthOf(character.radiusM, "bad_world", "world.character.radiusM", { minimumM: 0.05, maximumM: 5 });
463
+ const heightM = character.heightM === undefined ? 1.5 : lengthOf(character.heightM, "bad_world", "world.character.heightM", { minimumM: 0.2, maximumM: 20 });
464
+ if (heightM < radiusM * 2) refuse("bad_world", "world.character is shorter than it is wide.", "world.character.heightM", "Give a heightM of at least twice the radiusM: a character is a capsule standing up.");
465
+ const stepHeightM = character.stepHeightM === undefined ? 0.35 : lengthOf(character.stepHeightM, "bad_world", "world.character.stepHeightM", { minimumM: 0, maximumM: 5 });
466
+ if (character.maximumSlopeDeg !== undefined && (!isFiniteNumber(character.maximumSlopeDeg) || character.maximumSlopeDeg < 0 || character.maximumSlopeDeg > 89)) refuse("bad_world", `world.character.maximumSlopeDeg is ${JSON.stringify(character.maximumSlopeDeg)}.`, "world.character.maximumSlopeDeg", "Give the steepest ground a character walks up, in degrees from 0 to 89.");
467
+ const maximumSlopeDeg = character.maximumSlopeDeg ?? 50;
468
+ if (!PLAYER_CHARACTER_MODES.includes(playerCharacterMode)) refuse("bad_world", `world.playerCharacterMode is ${JSON.stringify(playerCharacterMode)}.`, "world.playerCharacterMode", `Use: ${PLAYER_CHARACTER_MODES.join(", ")}.`);
469
+ if (!Array.isArray(startPositionsM) || !startPositionsM.length || startPositionsM.length > MAXIMUM_CHARACTER_COUNT) refuse("bad_world", "world.startPositionsM isn't a list of places.", "world.startPositionsM", "Give where characters start, their feet on the ground, like [{ x: 0, y: 0, z: 0 }, { x: 2, y: 0, z: 0 }]: each new character takes the next.");
470
+ if (!isFiniteNumber(fallOutHeightM) || Math.abs(fallOutHeightM) > WORLD_REACH_M) refuse("bad_world", `world.fallOutHeightM is ${JSON.stringify(fallOutHeightM)}.`, "world.fallOutHeightM", "Give the height in metres below which anything that falls is put back where it started, like -30.");
471
+ return {
472
+ bodies: checkedBodies,
473
+ bodyKinds,
474
+ character: { heightM, radiusM, stepHeightM, maximumSlopeDeg },
475
+ collisionLayers,
476
+ joints: checkedJoints,
477
+ substepCount,
478
+ groundReachM: groundReach,
479
+ playerCharacterMode,
480
+ startPositionsM: startPositionsM.map((position, positionIndex) => pointOf(position, { x: 0, y: 0, z: 0 }, "bad_world", `world.startPositionsM[${positionIndex}]`)),
481
+ fallOutHeightM,
482
+ isPhysicsWorld: true,
483
+ };
484
+ }
485
+
486
+ /** The world something was given as: one definePhysicsWorld made, or a declaration to make one from. */
487
+ export function worldOf(given) {
488
+ return given?.isPhysicsWorld === true ? given : definePhysicsWorld(given);
489
+ }
490
+
491
+ /** An id as a body or a character takes one, checked. */
492
+ export function checkId(given, code, field) {
493
+ if (typeof given !== "string" || !ID_PATTERN.test(given)) refuse(code, `${JSON.stringify(given)} isn't an id.`, field, 'Give 1 to 64 letters, digits, "_", ".", ":" or "-".');
494
+ return given;
495
+ }
package/engine.js ADDED
@@ -0,0 +1,48 @@
1
+ // The engine under the physics piece: Rapier, as the one version this piece ships (rapier/), started once. A
2
+ // player's game fetches its WebAssembly and starts it before the first world is made (loadPhysics); a game server
3
+ // has it as it loads (server.js), since importing the file gives it there. Both run the same engine, which is what
4
+ // lets a player's game step ahead of the game server and agree with it.
5
+ import * as rapier from "./rapier/rapier.js";
6
+ import { refuse } from "./declare.js";
7
+
8
+ let isStarted = false;
9
+ let starting = null;
10
+
11
+ /** Starts the engine at once from its compiled WebAssembly (a WebAssembly.Module). For a game server. */
12
+ export function startPhysicsEngine(wasmModule) {
13
+ if (!isStarted) {
14
+ rapier.startEngine(wasmModule);
15
+ isStarted = true;
16
+ }
17
+ return rapier;
18
+ }
19
+
20
+ /**
21
+ * Loads and starts the engine, once: later calls answer the same promise. In a browser it fetches rapier/rapier.wasm
22
+ * from beside this file; give { wasm } (bytes, a WebAssembly.Module, or a fetch's response) to bring it another way.
23
+ */
24
+ export function loadPhysics(given = {}) {
25
+ if (given === null || typeof given !== "object" || Object.keys(given).some((key) => key !== "wasm")) refuse("unknown_argument", "loadPhysics takes { wasm }, or nothing.", "given", "Call loadPhysics() to fetch the engine from beside the piece, or loadPhysics({ wasm }) with its bytes.");
26
+ if (isStarted) return Promise.resolve();
27
+ if (!starting) {
28
+ starting = rapier
29
+ .startEngineLater(given.wasm ?? fetch(new URL("./rapier/rapier.wasm", import.meta.url)))
30
+ .then(() => {
31
+ isStarted = true;
32
+ })
33
+ .catch((error) => {
34
+ starting = null;
35
+ refuse("engine_unreachable", `The physics engine didn't load: ${error?.message ?? error}`, "wasm", "Check that pieces/@zaisma/physics/rapier/rapier.wasm is served beside the piece's other files, then call loadPhysics() again.");
36
+ });
37
+ }
38
+ return starting;
39
+ }
40
+
41
+ /** The engine, started. Throws PieceError "engine_not_loaded" before loadPhysics has finished. */
42
+ export function physicsEngine() {
43
+ if (!isStarted) refuse("engine_not_loaded", "The physics engine isn't loaded yet.", null, "Call await loadPhysics() once, before the first createPhysics or net.use(physicsKind(...)).");
44
+ return rapier;
45
+ }
46
+
47
+ /** The engine's version, part of what two sides must share to step alike. */
48
+ export const ENGINE_VERSION = rapier.ENGINE_VERSION;