@zaisma/physics 0.0.0-stage → 2.4.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.
package/sync.js ADDED
@@ -0,0 +1,1035 @@
1
+ // Physics as a world on the online core (@zaisma/net's worldKind), and the same world played alone.
2
+ //
3
+ // The core does everything about sharing: who is the word on the world (the game server, or the host's game),
4
+ // every player's game running it ahead from its own input, going back and running again when the word differs,
5
+ // saying only what changed, and nothing at all while the world rests. This file gives the core the world to do it
6
+ // with: what a body, a character, a joint and the world's rules share, field by field, and how the simulation is
7
+ // added to, read, written and stepped (openWorld). Every place steps on exactly the numbers the wire carries
8
+ // (isStateOnSteps), so a player's game and the game server never drift apart between words. The rest is what a game
9
+ // calls (physicsCalls), the same alone and online.
10
+ import statement from "./piece.json.js";
11
+ import { camelName, openPiece, openSettings } from "../piece/index.js";
12
+ import { checkBody, checkId, checkJoint, refuse, rotationFromDeg, worldOf, MAXIMUM_BODY_COUNT, MAXIMUM_CHARACTER_COUNT, MAXIMUM_JOINT_COUNT, MAXIMUM_TRIANGLE_GROUP_NUMBER, MOTION_KINDS, WORLD_REACH_M } from "./declare.js";
13
+ import { physicsEngine } from "./engine.js";
14
+ import { defineCharacterKind, walkingCharacters } from "./characters.js";
15
+ import { createSimulation, turned } from "./simulation.js";
16
+
17
+ /** The one thing in every world that holds its rules: the settings every side must step by. */
18
+ const RULES_ID = "physics:rules";
19
+ /** The one thing that says which of the world's triangle groups are off (a door, a bridge), in a world whose meshes have them. */
20
+ const TRIANGLE_GROUPS_ID = "physics:triangle_groups";
21
+ const TRIANGLE_GROUP_FIELDS = [{ name: "offMaskNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: 2 ** MAXIMUM_TRIANGLE_GROUP_NUMBER - 1 }];
22
+ const hasTriangleGroups = (world) => world.bodies.some((body) => body.shapes.some((shape) => shape.triangleGroupNumbers));
23
+ /** The piece's settings every side steps by, in the order they're sent. */
24
+ const BASE_SYNCED_SETTING_NAMES = ["gravityMPerSecPerSec", "bouncePct", "gripPct", "walkSpeedMPerSec", "jumpHeightM", "characterMassKg"];
25
+ const LISTENED_EVENT_NAMES = ["bodyAdded", "bodyRemoved", "characterAdded", "characterRemoved"];
26
+ const SET_BODY_KEYS = ["positionM", "rotationDeg", "velocityMPerSec", "spinRadPerSec", "motionKind", "collisionLayerName", "massKg"];
27
+ const SET_CHARACTER_KEYS = ["positionM", "velocityMPerSec", "facingYawRad", "collisionLayerName", "own"];
28
+ // How far a game may be off the room's word, field by field, before it goes back and runs again: two copies of the
29
+ // engine drift a hair apart after going back, and nobody sees three centimetres. Whole numbers and yes-or-no fields
30
+ // are never off at all.
31
+ const place = (name) => ({ name, valueKind: "number", minimumNumber: -WORLD_REACH_M, maximumNumber: WORLD_REACH_M, stepSizeNumber: 0.001, toleranceNumber: 0.03, snapAboveNumber: 3 });
32
+ const speed = (name) => ({ name, valueKind: "number", minimumNumber: -250, maximumNumber: 250, stepSizeNumber: 0.02, toleranceNumber: 0.6 });
33
+ const BODY_FIELDS = [
34
+ place("x"),
35
+ place("y"),
36
+ place("z"),
37
+ { name: "rotation", valueKind: "rotation", componentBitCount: 12, toleranceNumber: 0.05 },
38
+ speed("velocityX"),
39
+ speed("velocityY"),
40
+ speed("velocityZ"),
41
+ ...["spinX", "spinY", "spinZ"].map((name) => ({ name, valueKind: "number", minimumNumber: -120, maximumNumber: 120, stepSizeNumber: 0.05, toleranceNumber: 1.5 })),
42
+ // Which body it is in every side's simulation, so a joint and a seat can name it; and which of the world's kinds it's made as (0: declared with shapes of its own).
43
+ { name: "bodyNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: MAXIMUM_BODY_COUNT },
44
+ { name: "bodyKindNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: 255 },
45
+ // Which of the world's collision layers it's on, and how it moves now (moving, kinematic or fixed): a parked cart made fixed.
46
+ { name: "layerNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: 15, defaultValue: 1 },
47
+ { name: "motionNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: 2 },
48
+ // A vehicle's steering, for drawing its wheels.
49
+ { name: "steerNumber", valueKind: "number", minimumNumber: -1, maximumNumber: 1, stepSizeNumber: 0.01, toleranceNumber: 0.2 },
50
+ // How heavy it is now (0 for one that doesn't move): what rides in a cart's bed weighs on it.
51
+ { name: "massKg", valueKind: "number", minimumNumber: 0, maximumNumber: 100_000, stepSizeNumber: 0.01 },
52
+ ];
53
+ const CHARACTER_BASE_FIELDS = [
54
+ place("x"),
55
+ place("y"),
56
+ place("z"),
57
+ speed("velocityX"),
58
+ speed("velocityY"),
59
+ speed("velocityZ"),
60
+ { name: "facingYawRad", valueKind: "angle", toleranceNumber: 0.05 },
61
+ { name: "isGrounded", valueKind: "boolean" },
62
+ { name: "airTickCount", valueKind: "integer", minimumNumber: 0, maximumNumber: 250 },
63
+ // The body it rides in (its number and one more, 0 for none), and which of its seats.
64
+ { name: "rideBodyNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: MAXIMUM_BODY_COUNT + 1 },
65
+ { name: "seatIndex", valueKind: "integer", minimumNumber: 0, maximumNumber: 7 },
66
+ { name: "layerNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: 15, defaultValue: 2 },
67
+ ];
68
+ const JOINT_FIELDS = [{ name: "isEnabled", valueKind: "boolean", defaultValue: true }];
69
+
70
+ /** A rules field for a setting, as its statement states it. */
71
+ const ruleFieldOf = (stated) => (stated.valueKind === "choice" ? { name: stated.name, valueKind: "choice", choices: stated.choices, defaultValue: stated.defaultValue } : { name: stated.name, valueKind: "number", minimumNumber: stated.minimumNumber, maximumNumber: stated.maximumNumber, stepSizeNumber: 0.001, defaultValue: stated.defaultValue });
72
+ const isSameRules = (names, first, second) => names.every((name) => (typeof first[name] === "number" ? Math.abs(first[name] - second[name]) < 1e-6 : first[name] === second[name]));
73
+
74
+ /** The world's numbers from the piece's settings: what the simulation steps by before a character kind turns them. */
75
+ function baseTuningOf(rules) {
76
+ const gravityMPerSecPerSec = rules.gravityMPerSecPerSec;
77
+ return {
78
+ gravityMPerSecPerSec,
79
+ bouncePct: rules.bouncePct,
80
+ gripPct: rules.gripPct,
81
+ linearDampingNumber: 0.05,
82
+ angularDampingNumber: 0.2,
83
+ characterMassKg: rules.characterMassKg,
84
+ walkSpeedMPerSec: rules.walkSpeedMPerSec,
85
+ // The speed that reaches jump_height_m against this gravity.
86
+ jumpSpeedMPerSec: Math.sqrt(2 * Math.max(gravityMPerSecPerSec, 0.01) * rules.jumpHeightM),
87
+ };
88
+ }
89
+
90
+ function pointOrRefuse(given, what, fix) {
91
+ if (!given || !["x", "y", "z"].every((axis) => Number.isFinite(given[axis]))) refuse("bad_argument", `${what} isn't { x, y, z }.`, what, fix);
92
+ return given;
93
+ }
94
+
95
+ /**
96
+ * Everything one world needs that's the same wherever it's opened: the world, its character kind, the fields each
97
+ * thing shares, and which settings every side steps by.
98
+ */
99
+ function worldPlan(world, kind) {
100
+ const kindSyncedNames = kind.syncedSettingNames ?? [];
101
+ const baseStated = new Map(openSettings(statement).list().map((stated) => [stated.name, stated]));
102
+ const kindStated = kind.settingsStatement ? new Map(openSettings(kind.settingsStatement).list().map((stated) => [stated.name, stated])) : new Map();
103
+ const rulesFields = [...BASE_SYNCED_SETTING_NAMES.map((name) => ruleFieldOf(baseStated.get(name))), ...kindSyncedNames.map((name) => ruleFieldOf(kindStated.get(name)))];
104
+ const defaultRules = Object.fromEntries(rulesFields.map((field) => [field.name, field.defaultValue]));
105
+ // A field the kind keeps locally (isShared: false) is worked out by each step and never goes on the wire.
106
+ const characterFields = characterFieldsOf(kind);
107
+ return { world, kind, kindSyncedNames, rulesFields, ruleNames: rulesFields.map((field) => field.name), defaultRules, characterFields };
108
+ }
109
+
110
+ /**
111
+ * Opens a world's simulation for whoever steps it: what the online core's worldKind calls open, and what a game
112
+ * played alone steps itself. It answers how to add, remove, read, write and step the world, with the simulation
113
+ * itself and the world's rules on it. Each step says whether this place is the word on the world now (isInCharge):
114
+ * only there are things that fell out of the world put back (beforePutBack). isInChargeAtFirst is the best guess
115
+ * before the first step.
116
+ */
117
+ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, isInChargeAtFirst, tracksTouches = false, readDataFile = null }) {
118
+ const { world, kind, ruleNames, defaultRules } = plan;
119
+ // The rules start as the word's own settings where this place is the word, and as declared (the pieces' defaults)
120
+ // where it follows, until the word says otherwise: decided at the first step, when it's known which.
121
+ let rules = null;
122
+ let isTakingRoomRules = false;
123
+ let isInCharge = isInChargeAtFirst;
124
+ const tuningOf = (rulesNow) => (kind.tuning ? kind.tuning(baseTuningOf(rulesNow), rulesNow) : baseTuningOf(rulesNow));
125
+ const opened = {
126
+ /** The game's own state, for hooks to read: set by whoever opened the world. */
127
+ roomState: () => null,
128
+ /** This game's own character, in a player's game: set by whoever opened the world; null where the world is only run. */
129
+ ownCharacterId: null,
130
+ isStateOnSteps: true,
131
+ };
132
+ const ownRules = () => Object.fromEntries(ruleNames.map((name) => [name, BASE_SYNCED_SETTING_NAMES.includes(name) ? settings.get(name) : kindSettings.get(name)]));
133
+ const simulation = createSimulation(physicsEngine(), world, { tickDurationSec, characterKind: kind, tuning: tuningOf({ ...defaultRules, ...ownRules() }), readDataFile, tracksTouches });
134
+ /** Where each character started, to put it back when it falls out of the world. */
135
+ const startOf = new Map();
136
+ /** The kind of thing each id is: "body", "character", "joint" or "rules". */
137
+ const kindOf = new Map();
138
+ const fallen = [];
139
+
140
+ function takeRules(next, isFromRoom) {
141
+ rules = { ...next };
142
+ simulation.setTuning(tuningOf(rules));
143
+ if (!isFromRoom) return;
144
+ // What the room steps by is what this side's settings show.
145
+ isTakingRoomRules = true;
146
+ try {
147
+ settings.set(Object.fromEntries(BASE_SYNCED_SETTING_NAMES.map((name) => [name, rules[name]])));
148
+ if (kindSettings && plan.kindSyncedNames.length) kindSettings.set(Object.fromEntries(plan.kindSyncedNames.map((name) => [name, rules[name]])));
149
+ } catch {
150
+ // Rules another version of the piece takes: stepped by, but not shown.
151
+ } finally {
152
+ isTakingRoomRules = false;
153
+ }
154
+ }
155
+ const onOwnChange = ({ name }) => {
156
+ if (!isTakingRoomRules && ruleNames.includes(name) && isInCharge) takeRules(ownRules(), false);
157
+ };
158
+ settings.onChange(onOwnChange);
159
+ kindSettings?.onChange(onOwnChange);
160
+ const decideRules = () => {
161
+ if (rules) return;
162
+ if (isInCharge) takeRules(ownRules(), false);
163
+ else takeRules(defaultRules, true);
164
+ };
165
+
166
+ function putBack(position, id, isCharacter) {
167
+ const answered = ask("beforePutBack", { ...position }, { id, isCharacter, roomState: opened.roomState() });
168
+ return answered && ["x", "y", "z"].every((axis) => Number.isFinite(answered[axis])) ? { x: answered.x, y: answered.y, z: answered.z } : position;
169
+ }
170
+
171
+ Object.assign(opened, {
172
+ simulation,
173
+ world,
174
+ plan,
175
+ /** The rules the world steps by now. */
176
+ currentRules() {
177
+ decideRules();
178
+ return { ...rules };
179
+ },
180
+ /** The word's own change of rules, for this room alone. */
181
+ setRules(next) {
182
+ decideRules();
183
+ takeRules({ ...rules, ...next }, false);
184
+ },
185
+ /** The next body number nothing has. */
186
+ freeBodyNumber() {
187
+ const freeIndex = simulation.bodies.findIndex((held) => held === null);
188
+ return freeIndex === -1 ? simulation.bodies.length : freeIndex;
189
+ },
190
+ add(entity, state) {
191
+ kindOf.set(entity.id, entity.entityKindName);
192
+ if (entity.entityKindName === "rules") {
193
+ // As declared, it says nothing yet. Anything else is the room's word: kept from before a restart, or the word's own.
194
+ if (!isSameRules(ruleNames, state, defaultRules)) takeRules(state, true);
195
+ return;
196
+ }
197
+ if (entity.entityKindName === "character") {
198
+ if (simulation.characterIndexById.has(entity.id)) return;
199
+ const feetM = { x: state.x, y: state.y - world.character.heightM / 2, z: state.z };
200
+ const characterIndex = simulation.addCharacter(entity.id, feetM);
201
+ startOf.set(entity.id, feetM);
202
+ simulation.writeCharacter(characterIndex, state);
203
+ retryJoints();
204
+ return;
205
+ }
206
+ if (entity.entityKindName === "triangle_groups") {
207
+ simulation.setOffTriangleGroups(state.offMaskNumber);
208
+ return;
209
+ }
210
+ if (entity.entityKindName === "joint") {
211
+ const declaration = world.joints.find((joint) => joint.id === entity.id) ?? (entity.entityData ? checkJoint({ ...entity.entityData, id: entity.id }, "joint") : null);
212
+ if (declaration) pendingJoints.set(entity.id, { declaration, isEnabled: state.isEnabled });
213
+ retryJoints();
214
+ return;
215
+ }
216
+ let bodyIndex = simulation.bodyIndexById.get(entity.id);
217
+ if (bodyIndex === undefined) {
218
+ // One added while playing: made as the world's kind it names, with the number the word gave it.
219
+ const bodyKind = world.bodyKinds[state.bodyKindNumber - 1];
220
+ if (!bodyKind || simulation.bodies[state.bodyNumber]) return;
221
+ bodyIndex = simulation.addBody(checkBody({ id: entity.id, bodyKindName: bodyKind.name }, "body", world.bodyKinds), state.bodyNumber);
222
+ }
223
+ simulation.writeBody(bodyIndex, state);
224
+ retryJoints();
225
+ },
226
+ remove(entityId) {
227
+ const entityKindName = kindOf.get(entityId);
228
+ kindOf.delete(entityId);
229
+ if (entityKindName === "character") {
230
+ const characterIndex = simulation.characterIndexById.get(entityId);
231
+ if (characterIndex !== undefined) simulation.removeCharacter(characterIndex);
232
+ startOf.delete(entityId);
233
+ } else if (entityKindName === "body") {
234
+ const bodyIndex = simulation.bodyIndexById.get(entityId);
235
+ if (bodyIndex !== undefined) simulation.removeBody(bodyIndex);
236
+ } else if (entityKindName === "joint") {
237
+ pendingJoints.delete(entityId);
238
+ simulation.removeJoint(entityId);
239
+ }
240
+ },
241
+ read(entityId) {
242
+ const entityKindName = kindOf.get(entityId);
243
+ if (entityKindName === "rules") {
244
+ decideRules();
245
+ return { ...rules };
246
+ }
247
+ if (entityKindName === "character") {
248
+ const characterIndex = simulation.characterIndexById.get(entityId);
249
+ return characterIndex === undefined ? null : simulation.readCharacter(characterIndex);
250
+ }
251
+ if (entityKindName === "triangle_groups") return { offMaskNumber: simulation.offTriangleGroupMaskNumber() };
252
+ if (entityKindName === "joint") {
253
+ const isEnabled = simulation.joints.has(entityId) ? simulation.isJointEnabled(entityId) : pendingJoints.has(entityId) ? pendingJoints.get(entityId).isEnabled : null;
254
+ if (isEnabled !== null) readJointEnabled.set(entityId, isEnabled);
255
+ return isEnabled === null ? null : { isEnabled };
256
+ }
257
+ const bodyIndex = simulation.bodyIndexById.get(entityId);
258
+ if (bodyIndex === undefined) return null;
259
+ return { ...simulation.readBody(bodyIndex), bodyNumber: bodyIndex, bodyKindNumber: simulation.bodies[bodyIndex].declaration.bodyKindNumber };
260
+ },
261
+ write(entityId, state, writeInfo) {
262
+ const entityKindName = kindOf.get(entityId);
263
+ if (entityKindName === "rules") {
264
+ if (!rules || !isSameRules(ruleNames, state, rules)) takeRules(state, true);
265
+ } else if (entityKindName === "character") {
266
+ const characterIndex = simulation.characterIndexById.get(entityId);
267
+ if (characterIndex !== undefined) simulation.writeCharacter(characterIndex, state, writeInfo.isResting);
268
+ } else if (entityKindName === "triangle_groups") {
269
+ simulation.setOffTriangleGroups(state.offMaskNumber);
270
+ } else if (entityKindName === "joint") {
271
+ if (simulation.joints.has(entityId)) simulation.setJointEnabled(entityId, state.isEnabled);
272
+ else if (pendingJoints.has(entityId)) pendingJoints.get(entityId).isEnabled = state.isEnabled;
273
+ } else {
274
+ const bodyIndex = simulation.bodyIndexById.get(entityId);
275
+ if (bodyIndex !== undefined) simulation.writeBody(bodyIndex, state, writeInfo.isResting);
276
+ }
277
+ },
278
+ /**
279
+ * Whose time a thing is drawn in: a body only other players hold, push or ride is drawn with the first of them,
280
+ * so it sits in their hands, against them or under them. One this game's own character holds, pushes or rides too
281
+ * stays with that character, run ahead.
282
+ */
283
+ drawnWith(entityId) {
284
+ if (kindOf.get(entityId) !== "body") return null;
285
+ const bodyIndex = simulation.bodyIndexById.get(entityId);
286
+ if (bodyIndex === undefined) return null;
287
+ const kindAnswer = kind.drawnWith?.(bodyIndex, opened.ownCharacterId, simulation.stepTools);
288
+ if (kindAnswer === null) return null;
289
+ let otherId = kindAnswer ?? null;
290
+ for (const character of simulation.characters) {
291
+ if (character?.rideBodyIndex !== bodyIndex) continue;
292
+ if (character.id === opened.ownCharacterId) return null;
293
+ otherId ??= character.id;
294
+ }
295
+ for (const characterIndex of simulation.touchingCharacterIndexes(bodyIndex)) {
296
+ const characterId = simulation.characters[characterIndex].id;
297
+ if (characterId === opened.ownCharacterId) return null;
298
+ otherId ??= characterId;
299
+ }
300
+ return otherId;
301
+ },
302
+ isResting(entityId) {
303
+ const entityKindName = kindOf.get(entityId);
304
+ // The rules are read every step: a change of them is the word's to say at once.
305
+ if (entityKindName === "rules") return false;
306
+ // Groups change only when the game switches one, which the core already knows.
307
+ if (entityKindName === "triangle_groups") return true;
308
+ // A joint rests until a step ties or lets it go (setJoint from a character kind's step).
309
+ if (entityKindName === "joint") return !simulation.joints.has(entityId) || readJointEnabled.get(entityId) === simulation.isJointEnabled(entityId);
310
+ if (entityKindName === "character") {
311
+ const characterIndex = simulation.characterIndexById.get(entityId);
312
+ return characterIndex !== undefined && simulation.isCharacterResting(characterIndex);
313
+ }
314
+ const bodyIndex = simulation.bodyIndexById.get(entityId);
315
+ return bodyIndex !== undefined && simulation.isBodyResting(bodyIndex);
316
+ },
317
+ step({ tickIndex, isReplay, inputOf, isInCharge: isInChargeNow, emit }) {
318
+ isInCharge = isInChargeNow;
319
+ decideRules();
320
+ simulation.step({ tickIndex, isReplay, isInCharge, inputOf, emit: emit ?? (() => {}), roomState: opened.roomState, ask, tell });
321
+ const hits = simulation.takeHits();
322
+ // A step run again already happened: no sound, no hook, twice.
323
+ if (!isReplay) {
324
+ for (const hit of hits) {
325
+ tell("bodyHit", { bodyId: simulation.bodies[hit.bodyIndex]?.declaration.id ?? null, otherBodyId: hit.otherBodyIndex >= 0 ? (simulation.bodies[hit.otherBodyIndex]?.declaration.id ?? null) : null, otherCharacterId: hit.otherCharacterIndex >= 0 ? (simulation.characters[hit.otherCharacterIndex]?.id ?? null) : null, speedMPerSec: hit.speedMPerSec });
326
+ }
327
+ }
328
+ if (!isInCharge) return;
329
+ // Where the world is run, anything that fell out of it goes back to where it started.
330
+ for (const character of simulation.characters) {
331
+ if (!character || character.isWaiting) continue;
332
+ const fields = simulation.readCharacter(character.index);
333
+ if (fields.y >= world.fallOutHeightM) continue;
334
+ const backM = putBack(startOf.get(character.id) ?? world.startPositionsM[0], character.id, true);
335
+ simulation.writeCharacter(character.index, { ...fields, x: backM.x, y: backM.y + world.character.heightM / 2, z: backM.z, velocityX: 0, velocityY: 0, velocityZ: 0, isGrounded: false, airTickCount: 0, rideBodyNumber: 0, seatIndex: 0, ...startFieldsOf(kind, simulation.stepTools) });
336
+ }
337
+ simulation.forEachAwakeBody((bodyIndex) => {
338
+ if (simulation.readBody(bodyIndex).y < world.fallOutHeightM) fallen.push(bodyIndex);
339
+ });
340
+ for (const bodyIndex of fallen.splice(0)) {
341
+ const declaration = simulation.bodies[bodyIndex].declaration;
342
+ const backM = putBack(declaration.positionM, declaration.id, false);
343
+ kind.onBodyRemoved?.(bodyIndex, simulation.stepTools);
344
+ simulation.writeBody(bodyIndex, { ...simulation.readBody(bodyIndex), x: backM.x, y: backM.y, z: backM.z, rotation: declaration.rotation, velocityX: 0, velocityY: 0, velocityZ: 0, spinX: 0, spinY: 0, spinZ: 0 });
345
+ }
346
+ },
347
+ close() {
348
+ simulation.dispose();
349
+ },
350
+ });
351
+ /** Joints whose ends aren't here yet (a character that hasn't arrived): made as soon as they are. */
352
+ const pendingJoints = new Map();
353
+ /** Whether each joint held when it was last read: one that changed since doesn't rest. */
354
+ const readJointEnabled = new Map();
355
+ function retryJoints() {
356
+ for (const [jointId, pending] of pendingJoints) {
357
+ if (simulation.addJoint(pending.declaration, pending.isEnabled)) pendingJoints.delete(jointId);
358
+ }
359
+ }
360
+ for (const body of world.bodies) if (body.motionKind !== "fixed") kindOf.set(body.id, "body");
361
+ return opened;
362
+ }
363
+
364
+ /** What the online core's worldKind is declared with for a world, but for open. */
365
+ function worldFields(plan) {
366
+ const { world } = plan;
367
+ return {
368
+ entityKinds: {
369
+ // A character first: a thing added with no kind named is one.
370
+ character: { stateFields: plan.characterFields, hasInput: true },
371
+ body: { stateFields: BODY_FIELDS },
372
+ joint: { stateFields: JOINT_FIELDS },
373
+ rules: { stateFields: plan.rulesFields },
374
+ ...(hasTriangleGroups(world) ? { triangle_groups: { stateFields: TRIANGLE_GROUP_FIELDS } } : {}),
375
+ },
376
+ inputFields: plan.kind.inputFields,
377
+ // The bodies that move, the joints, and the rules as the pieces have them: the same in every game, so nothing of
378
+ // them is sent until it changes.
379
+ entities: [
380
+ { id: RULES_ID, entityKindName: "rules", state: { ...plan.defaultRules } },
381
+ ...world.bodies.flatMap((body, bodyIndex) => (body.motionKind !== "fixed" ? [{ id: body.id, entityKindName: "body", state: declaredBodyFields(body, bodyIndex, body.bodyKindNumber, world) }] : [])),
382
+ ...world.joints.map((joint) => ({ id: joint.id, entityKindName: "joint", state: { isEnabled: true } })),
383
+ ...(hasTriangleGroups(world) ? [{ id: TRIANGLE_GROUPS_ID, entityKindName: "triangle_groups", state: { offMaskNumber: 0 } }] : []),
384
+ ],
385
+ };
386
+ }
387
+
388
+ /** A body as declared, as its fields. */
389
+ function declaredBodyFields(checked, bodyNumber, bodyKindNumber, world) {
390
+ return {
391
+ x: checked.positionM.x,
392
+ y: checked.positionM.y,
393
+ z: checked.positionM.z,
394
+ rotation: checked.rotation,
395
+ velocityX: 0,
396
+ velocityY: 0,
397
+ velocityZ: 0,
398
+ spinX: 0,
399
+ spinY: 0,
400
+ spinZ: 0,
401
+ bodyNumber,
402
+ bodyKindNumber,
403
+ layerNumber: world.collisionLayers.findIndex((layer) => layer.name === checked.collisionLayerName),
404
+ motionNumber: MOTION_KINDS.indexOf(checked.motionKind),
405
+ steerNumber: 0,
406
+ massKg: checked.massKg ?? 0,
407
+ };
408
+ }
409
+
410
+ /** Where the next character starts, as a character's fields: each takes the next of the world's start places, round again. */
411
+ function startStates(world) {
412
+ let startCount = 0;
413
+ return () => {
414
+ const feetM = world.startPositionsM[startCount % world.startPositionsM.length];
415
+ startCount += 1;
416
+ return { x: feetM.x, y: feetM.y + world.character.heightM / 2, z: feetM.z, layerNumber: world.collisionLayers.findIndex((layer) => layer.name === "character") };
417
+ };
418
+ }
419
+
420
+ /** A body added while playing, checked: one of the world's kinds of body, somewhere. */
421
+ function checkAddedBody(world, declaration) {
422
+ if (declaration === null || typeof declaration !== "object" || declaration.bodyKindName === undefined) {
423
+ refuse("bad_body", "A body added while playing names one of the world's bodyKinds.", "body.bodyKindName", `Declare what it's made of in the world's bodyKinds, and add it as { id, bodyKindName, positionM }${world.bodyKinds.length ? `: this world has ${world.bodyKinds.map((bodyKind) => bodyKind.name).join(", ")}` : ""}. Every player's game then knows how to make it.`);
424
+ }
425
+ // How it moves from the start: a building piece placed fixed on a plot, never moving first.
426
+ const { motionKind, ...rest } = declaration;
427
+ if (motionKind !== undefined && !MOTION_KINDS.includes(motionKind)) refuse("bad_body", `body.motionKind is ${JSON.stringify(motionKind)}.`, "body.motionKind", `Use: ${MOTION_KINDS.join(", ")}; or leave it out for a body that moves.`);
428
+ return { ...checkBody(rest, "body", world.bodyKinds), startMotionKind: motionKind ?? "moving" };
429
+ }
430
+
431
+ const layerNumberOf = (world, layerName, what) => {
432
+ const layerNumber = world.collisionLayers.findIndex((layer) => layer.name === layerName);
433
+ if (layerNumber < 0 || layerName === "riding") refuse("bad_argument", `${what} is ${JSON.stringify(layerName)}.`, what, `Use one of the world's collisionLayers: ${world.collisionLayers.filter((layer) => layer.name !== "riding").map((layer) => layer.name).join(", ")}.`);
434
+ return layerNumber;
435
+ };
436
+
437
+ /** What setBody was given, as the body's fields. */
438
+ function bodyChanges(world, changes) {
439
+ for (const key of Object.keys(changes ?? {})) if (!SET_BODY_KEYS.includes(key)) refuse("unknown_argument", `setBody has no "${key}".`, key, `It takes: ${SET_BODY_KEYS.join(", ")}.`);
440
+ const fields = {};
441
+ const { positionM, rotationDeg, velocityMPerSec, spinRadPerSec, motionKind, collisionLayerName } = changes ?? {};
442
+ if (positionM !== undefined) Object.assign(fields, { x: pointOrRefuse(positionM, "positionM", "Give three numbers: x, y and z.").x, y: positionM.y, z: positionM.z });
443
+ if (rotationDeg !== undefined) fields.rotation = rotationFromDeg(pointOrRefuse(rotationDeg, "rotationDeg", "Give the turn about each axis in degrees."));
444
+ if (velocityMPerSec !== undefined) Object.assign(fields, { velocityX: pointOrRefuse(velocityMPerSec, "velocityMPerSec", "Give three numbers: x, y and z.").x, velocityY: velocityMPerSec.y, velocityZ: velocityMPerSec.z });
445
+ if (spinRadPerSec !== undefined) Object.assign(fields, { spinX: pointOrRefuse(spinRadPerSec, "spinRadPerSec", "Give three numbers: x, y and z.").x, spinY: spinRadPerSec.y, spinZ: spinRadPerSec.z });
446
+ if (motionKind !== undefined) {
447
+ if (!MOTION_KINDS.includes(motionKind)) refuse("bad_argument", `motionKind is ${JSON.stringify(motionKind)}.`, "motionKind", `Use: ${MOTION_KINDS.join(", ")}.`);
448
+ fields.motionNumber = MOTION_KINDS.indexOf(motionKind);
449
+ }
450
+ if (collisionLayerName !== undefined) fields.layerNumber = layerNumberOf(world, collisionLayerName, "collisionLayerName");
451
+ if (changes?.massKg !== undefined) {
452
+ if (!Number.isFinite(changes.massKg) || changes.massKg < 0.01 || changes.massKg > 100_000) refuse("bad_argument", `massKg is ${JSON.stringify(changes.massKg)}.`, "massKg", "Give how heavy it is now in kilograms, from 0.01 to 100000.");
453
+ // On the wire's grain, so every side weighs it the same.
454
+ fields.massKg = Math.round(changes.massKg * 100) / 100;
455
+ }
456
+ return fields;
457
+ }
458
+
459
+ /** A body as a simulation has it now, or null. */
460
+ function bodyStateOf(simulation, bodyId) {
461
+ const bodyIndex = simulation?.bodyIndexById.get(bodyId);
462
+ if (bodyIndex === undefined) return null;
463
+ const fields = simulation.readBody(bodyIndex);
464
+ const body = simulation.bodies[bodyIndex];
465
+ return {
466
+ positionM: { x: fields.x, y: fields.y, z: fields.z },
467
+ rotation: fields.rotation,
468
+ velocityMPerSec: { x: fields.velocityX, y: fields.velocityY, z: fields.velocityZ },
469
+ spinRadPerSec: { x: fields.spinX, y: fields.spinY, z: fields.spinZ },
470
+ motionKind: MOTION_KINDS[body.motionIndex],
471
+ collisionLayerName: simulation.world.collisionLayers[body.layerIndex].name,
472
+ massKg: body.massKg ?? null,
473
+ isResting: simulation.isBodyResting(bodyIndex),
474
+ riderCharacterIds: simulation.characters.filter((character) => character?.rideBodyIndex === bodyIndex).map((character) => character.id),
475
+ };
476
+ }
477
+
478
+ const isFixedBody = (world, bodyId) => world.bodies.some((body) => body.id === bodyId && body.motionKind === "fixed");
479
+ const unknownBody = (bodyId) => refuse("unknown_body", `There's no body ${JSON.stringify(bodyId)} in this world.`, "bodyId", "Give the id of a body in bodyIds(): one the world declares, or one added with addBody.");
480
+ const unknownCharacter = (characterId) => refuse("unknown_character", `There's no character ${JSON.stringify(characterId)} here.`, "characterId", "Give the id of a character in characterIds(): a player's has the player's id.");
481
+
482
+ /** A character kind's own fields as a character starts with them: the ones on the wire, since each game sets its local ones (isShared: false) itself. */
483
+ function startFieldsOf(kind, tools) {
484
+ const fields = { ...kind.readOwn({ own: kind.startOwn(tools) }, tools) };
485
+ for (const field of kind.stateFields) if (field.isShared === false) delete fields[field.name];
486
+ return fields;
487
+ }
488
+
489
+ /** A character's fields as a drawing reads them. */
490
+ function characterView(world, simulation, fields, characterId) {
491
+ const rideIndex = (fields.rideBodyNumber ?? 0) - 1;
492
+ return {
493
+ characterId,
494
+ positionM: { x: fields.x, y: fields.y - world.character.heightM / 2, z: fields.z },
495
+ facingYawRad: fields.facingYawRad,
496
+ velocityMPerSec: { x: fields.velocityX, y: fields.velocityY, z: fields.velocityZ },
497
+ speedMPerSec: Math.hypot(fields.velocityX, fields.velocityZ),
498
+ riseSpeedMPerSec: fields.velocityY,
499
+ isOnGround: fields.isGrounded,
500
+ rideBodyId: rideIndex >= 0 ? (simulation?.bodies[rideIndex]?.declaration.id ?? null) : null,
501
+ seatIndex: rideIndex >= 0 ? fields.seatIndex : null,
502
+ collisionLayerName: world.collisionLayers[fields.layerNumber]?.name ?? "character",
503
+ };
504
+ }
505
+
506
+ /** Every field a character of a kind shares: the piece's own, then the kind's that go on the wire. */
507
+ export const characterFieldsOf = (kind) => [...CHARACTER_BASE_FIELDS, ...kind.stateFields.filter((field) => field.isShared !== false).map(({ isShared, ...field }) => field)];
508
+
509
+ /** A character's fields as a drawing reads them, with its kind's own: for characters over a level. */
510
+ export const characterViewOf = (world, kind, fields, characterId, simulation) => ({ ...characterView(world, simulation, fields, characterId), own: ownOf({ kind }, fields, simulation, characterId) });
511
+
512
+ /** The world's numbers from a piece's settings as they are, turned by a kind's own: for characters over a level, where every side declares the same settings. */
513
+ export const levelTuningOf = (kind, settings) => {
514
+ const rules = Object.fromEntries(BASE_SYNCED_SETTING_NAMES.map((name) => [name, settings.get(name)]));
515
+ return kind.tuning ? kind.tuning(baseTuningOf(rules), rules) : baseTuningOf(rules);
516
+ };
517
+
518
+ /** The queries a game asks of a simulation it reaches by simulationNow. */
519
+ export const queriesOver = (simulationNow) => queryCalls(simulationNow);
520
+
521
+ /** The kind's own fields from a character's fields. */
522
+ const ownOf = (plan, fields, simulation = null, characterId = null) => {
523
+ const localOwn = simulation ? simulation.characters[simulation.characterIndexById.get(characterId)]?.own : null;
524
+ return Object.fromEntries(plan.kind.stateFields.map((field) => [field.name, field.isShared === false ? (localOwn?.[field.name] ?? null) : fields[field.name]]));
525
+ };
526
+
527
+ /** A query's request, checked: the points and lengths a ray, a ball's sweep or an overlap takes. */
528
+ function checkQuery(given, keys, what) {
529
+ if (given === null || typeof given !== "object") refuse("bad_argument", `${what} takes an object.`, what, `Give { ${keys.join(", ")} }.`);
530
+ for (const key of Object.keys(given)) if (![...keys, "collisionLayerNames", "excludedId"].includes(key)) refuse("unknown_argument", `${what} has no "${key}".`, key, `It takes: ${keys.join(", ")}, collisionLayerNames, excludedId.`);
531
+ for (const key of keys) {
532
+ if (key.endsWith("M") && typeof given[key] === "object") pointOrRefuse(given[key], key, "Give three numbers: x, y and z, in metres.");
533
+ else if (!Number.isFinite(given[key]) || given[key] < 0) refuse("bad_argument", `${key} is ${JSON.stringify(given[key])}.`, key, "Give a length in metres from 0.");
534
+ }
535
+ return given;
536
+ }
537
+
538
+ /** The queries a game asks of a world: the same alone, in a player's game and on a game server. */
539
+ /** A query's isStoppedAtPenetration and rotation, checked: what a shape's cast and overlap take beside their points. */
540
+ function shapeQueryOf(request, keys, what) {
541
+ const { isStoppedAtPenetration, rotation, marginM, ...rest } = request ?? {};
542
+ if (isStoppedAtPenetration !== undefined && typeof isStoppedAtPenetration !== "boolean") refuse("bad_argument", "isStoppedAtPenetration isn't true or false.", "isStoppedAtPenetration", "Give false to pass out of what the shape starts touching (a camera pressed to a wall), or leave it out.");
543
+ if (rotation !== undefined && !(rotation && ["x", "y", "z", "w"].every((part) => Number.isFinite(rotation[part])))) refuse("bad_argument", "rotation isn't { x, y, z, w }.", "rotation", "Give the turn as the engine and three.js hold it (a quaternion), or leave it out for standing up.");
544
+ if (marginM !== undefined && !(Number.isFinite(marginM) && marginM >= 0 && marginM <= 1)) refuse("bad_argument", `marginM is ${JSON.stringify(marginM)}.`, "marginM", "Give how near counts as touching, 0 to 1 m, or leave it out.");
545
+ return { ...checkQuery(rest, keys, what), ...(isStoppedAtPenetration === undefined ? {} : { isStoppedAtPenetration }), ...(rotation === undefined ? {} : { rotation }), ...(marginM === undefined ? {} : { marginM }) };
546
+ }
547
+
548
+ function queryCalls(simulationNow) {
549
+ const checkInto = (into) => {
550
+ if (into !== undefined && into !== null && typeof into !== "object") refuse("bad_argument", "into isn't an object.", "into", "Give an object of your own to write the hit into (kept and reused), or leave it out for a new one.");
551
+ return into ?? null;
552
+ };
553
+ return {
554
+ /** The first thing a ray meets: { bodyId, characterId, pointM, normal, distanceM }, or null. With into, written there instead of a new object. */
555
+ castRay: (request, into) => simulationNow()?.castRay(checkQuery(request, ["fromM", "directionM", "maximumDistanceM"], "castRay"), checkInto(into)) ?? null,
556
+ /** The first thing a ball meets moving along a direction, or null. */
557
+ castBall: (request, into) => simulationNow()?.castBall(shapeQueryOf(request, ["fromM", "radiusM", "directionM", "maximumDistanceM"], "castBall"), checkInto(into)) ?? null,
558
+ /** The first thing a capsule (standing up, or turned by rotation) meets moving along a direction, or null. */
559
+ castCapsule: (request, into) => simulationNow()?.castCapsule(shapeQueryOf(request, ["fromM", "radiusM", "heightM", "directionM", "maximumDistanceM"], "castCapsule"), checkInto(into)) ?? null,
560
+ /** Where a capsule touches the world: [{ bodyId, characterId, pointM, normal, depthM }], to push out of walls by. */
561
+ overlapCapsule: (request) => simulationNow()?.overlapCapsule(shapeQueryOf(request, ["centerM", "radiusM", "heightM"], "overlapCapsule")) ?? [],
562
+ /** Everything a ball overlaps: [{ bodyId, characterId }]. */
563
+ overlapBall: (request) => simulationNow()?.overlapBall(checkQuery(request, ["centerM", "radiusM"], "overlapBall")) ?? [],
564
+ };
565
+ }
566
+
567
+ /**
568
+ * What a game calls on a world in play, alone or online, over the few calls both have: things is the world as the
569
+ * online core's World gives it (ids, has, entityKindName, state, drawn, add, remove, set, setInput, on, simulation),
570
+ * and the rest says who this game is in it.
571
+ */
572
+ function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharge, isReady, hasGameServer }) {
573
+ const { world, kind } = plan;
574
+ const listeners = Object.fromEntries(LISTENED_EVENT_NAMES.map((eventName) => [eventName, new Set()]));
575
+ /** Each thing's kind, kept so a removal can still say what was removed. */
576
+ const kindById = new Map(things.ids().map((id) => [id, things.entityKindName(id)]));
577
+ const telling = (eventName, id) => {
578
+ for (const listener of [...listeners[eventName]]) listener(id);
579
+ };
580
+ things.on("added", (id) => {
581
+ const entityKindName = things.entityKindName(id);
582
+ kindById.set(id, entityKindName);
583
+ if (entityKindName === "body") telling("bodyAdded", id);
584
+ else if (entityKindName === "character") telling("characterAdded", id);
585
+ });
586
+ things.on("removed", (id) => {
587
+ const entityKindName = kindById.get(id);
588
+ kindById.delete(id);
589
+ if (entityKindName === "body") telling("bodyRemoved", id);
590
+ else if (entityKindName === "character") telling("characterRemoved", id);
591
+ });
592
+ const simulationNow = () => things.simulation?.simulation ?? null;
593
+ const isBody = (bodyId) => things.entityKindName(bodyId) === "body";
594
+ const isCharacter = (characterId) => things.entityKindName(characterId) === "character";
595
+ /** The world's calls where this game runs it; a refusal with a game server, and null where another player's game does. */
596
+ const inCharge = (what) => {
597
+ if (isInCharge()) return things;
598
+ if (hasGameServer) refuse("not_in_charge", `With a game server, ${what} there.`, null, "Call it in the game server's code, on physics.onServer(state, room).");
599
+ return null;
600
+ };
601
+ /** Where a body is drawn: a moving one from the world in play, a fixed one where it's declared. */
602
+ const drawnOf = (bodyId) => {
603
+ const drawn = isBody(bodyId) ? things.drawn(bodyId) : null;
604
+ if (drawn) return drawn;
605
+ const declaration = world.bodies.find((body) => body.id === bodyId && body.motionKind === "fixed");
606
+ return declaration ? { x: declaration.positionM.x, y: declaration.positionM.y, z: declaration.positionM.z, rotation: declaration.rotation } : null;
607
+ };
608
+ const shared = sharedCalls({ plan, things, simulationNow, inChargeOf: inCharge });
609
+
610
+ const calls = {
611
+ settings,
612
+ hooks,
613
+ world,
614
+ /** The character kind's own settings (a piece built on physics, like @zaisma/physics-party's feel), or null. */
615
+ characterSettings: kind.settings ?? null,
616
+ /** The character kind's own hooks, or null. */
617
+ characterHooks: kind.hooks ?? null,
618
+ /** Whether this game runs the world: alone, or as the room's host on the relay. */
619
+ get isInCharge() {
620
+ return isInCharge();
621
+ },
622
+ /** Whether the world is here yet: at once alone or in charge, else once the room has said how it is. */
623
+ get isReady() {
624
+ return isReady();
625
+ },
626
+ ownCharacterId,
627
+ ...shared,
628
+ ...queryCalls(simulationNow),
629
+ /** A body's declaration, checked: its shapes and sizes, to build what's drawn from. */
630
+ bodyDeclaration(bodyId) {
631
+ const simulation = simulationNow();
632
+ if (simulation) return simulation.bodies[simulation.bodyIndexById.get(bodyId)]?.declaration ?? null;
633
+ return world.bodies.find((body) => body.id === bodyId) ?? null;
634
+ },
635
+ /** Where to draw a body this frame: { positionM, rotation, steerNumber }. null for a body that isn't here. */
636
+ drawnBody(bodyId) {
637
+ const drawn = drawnOf(bodyId);
638
+ return drawn ? { positionM: { x: drawn.x, y: drawn.y, z: drawn.z }, rotation: { ...drawn.rotation }, steerNumber: drawn.steerNumber ?? 0, wheels: simulationNow()?.wheelStates(bodyId) ?? [] } : null;
639
+ },
640
+ /** Puts a three.js object (anything with position.set and quaternion.set) where a body is drawn this frame. */
641
+ applyTo(object3d, bodyId) {
642
+ const drawn = drawnOf(bodyId);
643
+ if (!drawn) return false;
644
+ object3d.position.set(drawn.x, drawn.y, drawn.z);
645
+ object3d.quaternion.set(drawn.rotation.x, drawn.rotation.y, drawn.rotation.z, drawn.rotation.w);
646
+ return true;
647
+ },
648
+ /** This player's input from now on, or with { characterId } a bot's this game moves. Only the fields given change. */
649
+ setInput(given, setOptions = {}) {
650
+ if (setOptions === null || typeof setOptions !== "object" || Object.keys(setOptions).some((key) => key !== "characterId")) refuse("unknown_argument", "setInput's options are { characterId }.", "setOptions", "Leave them out for this player's own character.");
651
+ const characterId = setOptions.characterId ?? ownCharacterId;
652
+ return Boolean(characterId === ownCharacterId ? things.setInput(given) : things.setInput(given, characterId));
653
+ },
654
+ /** Where and how to draw a character this frame: its feet, facing, speed, footing, what it rides, and its kind's own fields. */
655
+ drawnCharacter(characterId) {
656
+ const drawn = isCharacter(characterId) ? things.drawn(characterId) : null;
657
+ if (!drawn) return null;
658
+ const view = { ...characterView(world, simulationNow(), drawn, characterId), own: ownOf(plan, drawn, simulationNow(), characterId) };
659
+ return kind.drawnCharacter ? kind.drawnCharacter(view, drawn, { things, simulation: simulationNow(), world }) : view;
660
+ },
661
+ /** Lays the ground near a place, though nothing moves there: under a camera looking past, before a query far off. */
662
+ keepGroundNear(pointM) {
663
+ pointOrRefuse(pointM, "pointM", "Give a place in metres.");
664
+ simulationNow()?.keepGroundNear(pointM);
665
+ },
666
+ /** Hears "bodyAdded", "bodyRemoved", "characterAdded" or "characterRemoved": listener(id). Answers a function that stops listening. */
667
+ on(eventName, listener) {
668
+ if (!LISTENED_EVENT_NAMES.includes(eventName)) refuse("unknown_event", `There's no event ${JSON.stringify(eventName)}.`, "eventName", `Listen for: ${LISTENED_EVENT_NAMES.join(", ")}.`);
669
+ if (typeof listener !== "function") refuse("bad_argument", "on takes a listener function.", "listener", "Give (id) => { ... }.");
670
+ listeners[eventName].add(listener);
671
+ return () => listeners[eventName].delete(listener);
672
+ },
673
+ };
674
+ return kind.calls ? kind.calls(calls, { things, simulationNow, inCharge, world, ownCharacterId }) : calls;
675
+ }
676
+
677
+ /**
678
+ * The calls that change the world, the same where it's run in a player's game (on the relay, or alone) and on a game
679
+ * server: bodies, characters, joints and seats. inChargeOf(what) answers the world's calls where this place may
680
+ * change it (refusing, or null, where it may not).
681
+ */
682
+ function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
683
+ const { world, kind } = plan;
684
+ const isBody = (bodyId) => things.entityKindName(bodyId) === "body";
685
+ const isCharacter = (characterId) => things.entityKindName(characterId) === "character";
686
+ const isJoint = (jointId) => things.entityKindName(jointId) === "joint";
687
+ // Every thing in play, declared ones included: an id freed by a removal may be used again, even in the same step.
688
+ const ids = () => new Set(things.ids());
689
+ return {
690
+ bodyIds: () => [...world.bodies.filter((body) => body.motionKind === "fixed").map((body) => body.id), ...things.ids("body")],
691
+ hasBody: (bodyId) => isBody(bodyId) || isFixedBody(world, bodyId),
692
+ /** A body as this world has it now. */
693
+ bodyState: (bodyId) => bodyStateOf(simulationNow(), bodyId),
694
+ /** Adds a body of one of the world's bodyKinds. */
695
+ addBody(declaration) {
696
+ const running = inChargeOf("bodies are added");
697
+ const checked = checkAddedBody(world, declaration);
698
+ if (!running || ids().has(checked.id)) return false;
699
+ if (things.ids("body").length >= MAXIMUM_BODY_COUNT) refuse("too_many_bodies", `A world holds at most ${MAXIMUM_BODY_COUNT} bodies.`, "body", "Remove bodies nobody needs.");
700
+ return Boolean(running.add(checked.id, { entityKindName: "body", state: { ...declaredBodyFields(checked, things.simulation.freeBodyNumber(), checked.bodyKindNumber, world), motionNumber: MOTION_KINDS.indexOf(checked.startMotionKind) } }));
701
+ },
702
+ removeBody: (bodyId) => Boolean(inChargeOf("bodies are removed") && isBody(bodyId) && things.remove(bodyId)),
703
+ /** Sets a body's place, rotation, speed or spin at once (a teleport), how it moves (motionKind), or its collision layer. */
704
+ setBody(bodyId, changes) {
705
+ const running = inChargeOf("bodies are set");
706
+ const fields = bodyChanges(world, changes);
707
+ if (!isBody(bodyId)) return world.bodies.some((body) => body.id === bodyId) ? false : unknownBody(bodyId);
708
+ const isMoved = ["x", "y", "z", "rotation"].some((name) => name in fields);
709
+ return Boolean(running && running.set(bodyId, fields, { isTeleport: isMoved }));
710
+ },
711
+ pushBody(bodyId, pushMPerSec) {
712
+ pointOrRefuse(pushMPerSec, "pushMPerSec", "Give the change of speed in metres a second along each axis.");
713
+ const running = inChargeOf("bodies are pushed");
714
+ const state = running && isBody(bodyId) ? things.state(bodyId) : null;
715
+ return Boolean(state && running.set(bodyId, { velocityX: state.velocityX + pushMPerSec.x, velocityY: state.velocityY + pushMPerSec.y, velocityZ: state.velocityZ + pushMPerSec.z }, { isTeleport: false }));
716
+ },
717
+ characterIds: () => things.ids("character"),
718
+ hasCharacter: isCharacter,
719
+ /** A character as this world has it now: where, how fast, facing where, standing or not, riding what, and its kind's own fields. */
720
+ characterState(characterId) {
721
+ if (!isCharacter(characterId)) return null;
722
+ const fields = things.state(characterId);
723
+ return { ...characterView(world, simulationNow(), fields, characterId), own: ownOf(plan, fields, simulationNow(), characterId) };
724
+ },
725
+ addCharacter(characterId, addOptions = {}) {
726
+ checkId(characterId, "bad_character_id", "characterId");
727
+ const running = inChargeOf("characters are added");
728
+ if (!running || things.has(characterId)) return false;
729
+ if (things.ids("character").length >= MAXIMUM_CHARACTER_COUNT) refuse("too_many_characters", `A world holds at most ${MAXIMUM_CHARACTER_COUNT} characters.`, "characterId", "Remove characters nobody needs.");
730
+ const feetM = addOptions?.positionM === undefined ? null : pointOrRefuse(addOptions.positionM, "positionM", "Give where its feet stand, in metres.");
731
+ return Boolean(running.add(characterId, { entityKindName: "character", ...(feetM ? { state: { x: feetM.x, y: feetM.y + world.character.heightM / 2, z: feetM.z } } : {}) }));
732
+ },
733
+ removeCharacter: (characterId) => Boolean(inChargeOf("characters are removed") && isCharacter(characterId) && things.remove(characterId)),
734
+ /** Sets a character at once: its feet's place (a teleport), its speed, facing, collision layer, or its kind's own fields. */
735
+ setCharacter(characterId, changes) {
736
+ const running = inChargeOf("characters are set");
737
+ for (const key of Object.keys(changes ?? {})) if (!SET_CHARACTER_KEYS.includes(key)) refuse("unknown_argument", `setCharacter has no "${key}".`, key, `It takes: ${SET_CHARACTER_KEYS.join(", ")}.`);
738
+ if (!isCharacter(characterId)) unknownCharacter(characterId);
739
+ const fields = {};
740
+ if (changes?.positionM !== undefined) {
741
+ const feetM = pointOrRefuse(changes.positionM, "positionM", "Give where its feet stand, in metres.");
742
+ Object.assign(fields, { x: feetM.x, y: feetM.y + world.character.heightM / 2, z: feetM.z, velocityX: 0, velocityY: 0, velocityZ: 0, isGrounded: false, airTickCount: 0, rideBodyNumber: 0, seatIndex: 0, ...startFieldsOf(kind, simulationNow()?.stepTools) });
743
+ }
744
+ if (changes?.velocityMPerSec !== undefined) Object.assign(fields, { velocityX: pointOrRefuse(changes.velocityMPerSec, "velocityMPerSec", "Give three numbers: x, y and z.").x, velocityY: changes.velocityMPerSec.y, velocityZ: changes.velocityMPerSec.z });
745
+ if (changes?.facingYawRad !== undefined) fields.facingYawRad = changes.facingYawRad;
746
+ if (changes?.collisionLayerName !== undefined) fields.layerNumber = layerNumberOf(world, changes.collisionLayerName, "collisionLayerName");
747
+ if (changes?.own !== undefined) {
748
+ if (changes.own === null || typeof changes.own !== "object") refuse("bad_argument", "own isn't an object of the character kind's fields.", "own", `Give some of: ${kind.stateFields.map((field) => field.name).join(", ") || "(this kind has none)"}.`);
749
+ for (const [name, ownValue] of Object.entries(changes.own)) {
750
+ if (!kind.stateFields.some((field) => field.name === name)) refuse("bad_argument", `The character kind has no field "${name}".`, `own.${name}`, `Its fields: ${kind.stateFields.map((field) => field.name).join(", ") || "none"}.`);
751
+ fields[name] = ownValue;
752
+ }
753
+ }
754
+ return Boolean(running && running.set(characterId, fields, { isTeleport: changes?.positionM !== undefined }));
755
+ },
756
+ /** Puts a character in a seat of a body (the first seat drives what has wheels), or with bodyId null lets it out where it is. */
757
+ seatCharacter(characterId, bodyId, seatIndex = 0) {
758
+ const running = inChargeOf("characters are seated");
759
+ if (!isCharacter(characterId)) unknownCharacter(characterId);
760
+ if (bodyId === null) return Boolean(running && running.set(characterId, { rideBodyNumber: 0, seatIndex: 0 }, { isTeleport: false }));
761
+ if (!isBody(bodyId)) unknownBody(bodyId);
762
+ const simulation = simulationNow();
763
+ const bodyIndex = simulation?.bodyIndexById.get(bodyId);
764
+ const seats = simulation?.bodies[bodyIndex]?.declaration.seats ?? [];
765
+ if (!Number.isInteger(seatIndex) || seatIndex < 0 || seatIndex >= seats.length) refuse("bad_argument", `seatIndex is ${JSON.stringify(seatIndex)}.`, "seatIndex", seats.length ? `Give a seat from 0 to ${seats.length - 1}: the body's kind declares ${seats.length}.` : "Give the body's kind seats first.");
766
+ if (simulation.characters.some((character) => character && character.id !== characterId && character.rideBodyIndex === bodyIndex && character.seatIndex === seatIndex)) return false;
767
+ // Into the seat at once, as a teleport: its player's game doesn't ease it there across (and through) the vehicle.
768
+ return Boolean(running && running.set(characterId, { rideBodyNumber: bodyIndex + 1, seatIndex }, { isTeleport: true }));
769
+ },
770
+ jointIds: () => [...things.ids("joint")],
771
+ /** Adds a joint while playing: two bodies (or a body and a character, or a body and the world) held together. */
772
+ addJoint(declaration) {
773
+ const running = inChargeOf("joints are added");
774
+ const checked = checkJoint(declaration, "joint", (id) => isBody(id) || isCharacter(id));
775
+ if (!running || ids().has(checked.id)) return false;
776
+ if (things.ids("joint").length >= MAXIMUM_JOINT_COUNT) refuse("too_many_joints", `A world holds at most ${MAXIMUM_JOINT_COUNT} joints.`, "joint", "Remove joints nobody needs.");
777
+ const { id, ...entityData } = declaration;
778
+ return Boolean(running.add(checked.id, { entityKindName: "joint", state: { isEnabled: true }, entityData }));
779
+ },
780
+ removeJoint: (jointId) => Boolean(inChargeOf("joints are removed") && isJoint(jointId) && things.remove(jointId)),
781
+ /** Lets a joint go, or holds again (a cart's handles let go and taken). */
782
+ setJoint(jointId, changes) {
783
+ const running = inChargeOf("joints are set");
784
+ for (const key of Object.keys(changes ?? {})) if (key !== "isEnabled") refuse("unknown_argument", `setJoint has no "${key}".`, key, "It takes: isEnabled.");
785
+ if (typeof changes?.isEnabled !== "boolean") refuse("bad_argument", "setJoint takes { isEnabled }.", "isEnabled", "Give true to hold, false to let go.");
786
+ if (!isJoint(jointId)) refuse("unknown_joint", `There's no joint ${JSON.stringify(jointId)} here.`, "jointId", "Give the id of a joint in jointIds().");
787
+ return Boolean(running && running.set(jointId, { isEnabled: changes.isEnabled }, { isTeleport: false }));
788
+ },
789
+ isJointEnabled: (jointId) => (isJoint(jointId) ? Boolean(things.state(jointId)?.isEnabled) : false),
790
+ /** Switches one of the world's triangle groups on or off for everyone (a door that opens, a bridge that falls), 1 to 31. */
791
+ setTriangleGroup(groupNumber, isEnabled) {
792
+ const running = inChargeOf("triangle groups are switched");
793
+ if (!Number.isInteger(groupNumber) || groupNumber < 1 || groupNumber > MAXIMUM_TRIANGLE_GROUP_NUMBER) refuse("bad_argument", `groupNumber is ${JSON.stringify(groupNumber)}.`, "groupNumber", `Give a group from 1 to ${MAXIMUM_TRIANGLE_GROUP_NUMBER}, as the mesh's triangleGroupNumbers number it.`);
794
+ if (typeof isEnabled !== "boolean") refuse("bad_argument", "setTriangleGroup takes the group and true or false.", "isEnabled", "Give true to have its triangles there, false to take them away.");
795
+ if (!hasTriangleGroups(world)) refuse("no_triangle_groups", "This world's meshes have no triangleGroupNumbers.", "groupNumber", "Give a mesh triangleGroupNumbers in the world's declaration, in the game and on its game server.");
796
+ const maskNumber = things.state(TRIANGLE_GROUPS_ID)?.offMaskNumber ?? 0;
797
+ const bitNumber = 1 << (groupNumber - 1);
798
+ return Boolean(running && running.set(TRIANGLE_GROUPS_ID, { offMaskNumber: isEnabled ? maskNumber & ~bitNumber : maskNumber | bitNumber }, { isTeleport: false }));
799
+ },
800
+ /** Whether a triangle group is there now. */
801
+ isTriangleGroupEnabled: (groupNumber) => !((things.state(TRIANGLE_GROUPS_ID)?.offMaskNumber ?? 0) & (1 << (groupNumber - 1))),
802
+ };
803
+ }
804
+
805
+ /** The character kind a world is given, checked: the piece's own walk unless the game gives its own. */
806
+ const kindOf = (characters) => (characters === undefined ? walkingCharacters() : defineCharacterKind(characters));
807
+
808
+ /**
809
+ * Answers physicsKind for one side's online core (its worldKind, from index.js in a game and server.js on a game
810
+ * server). physicsKind(world, { settings, hooks, characters }) is shared physics for a world: a kind of sync for
811
+ * createNet(room).use and defineNetServer's kinds.
812
+ */
813
+ export const physicsKindFrom = (worldKind) => (givenWorld, given = {}) => {
814
+ if (given === null || typeof given !== "object" || Object.keys(given).some((key) => !["settings", "hooks", "characters"].includes(key))) refuse("unknown_argument", "physicsKind takes a world, then { settings, hooks, characters }.", "given", "Give the world first, then an object with settings, hooks and characters (a character kind), each optional.");
815
+ const world = worldOf(givenWorld);
816
+ const kind = kindOf(given.characters);
817
+ const plan = worldPlan(world, kind);
818
+ const { settings, hooks, ask, tell } = openPiece(statement, { settings: given.settings, hooks: given.hooks });
819
+ const nextStart = startStates(world);
820
+ const physicsWorldKind = worldKind({
821
+ name: "physics",
822
+ ...worldFields(plan),
823
+ ...(world.playerCharacterMode === "on_join" ? { playerEntityKindName: "character" } : {}),
824
+ startState: (entityId, entityKindName) => (entityKindName === "character" ? nextStart() : {}),
825
+ // Every field that may be a little off says how far itself; the rest are exact.
826
+ toleranceStepCount: 0,
827
+ // In a player's game the world steps by that game's own settings objects. On a game server every room has rules of
828
+ // its own, starting as the kind's settings, so one room turning its gravity never turns another's.
829
+ open: ({ tickDurationSec, isServer, room }) =>
830
+ openWorld({
831
+ plan,
832
+ settings: isServer ? openSettings(statement, settings.values) : settings,
833
+ kindSettings: kind.settingsStatement ? (isServer ? openSettings(kind.settingsStatement, kind.settings.values) : kind.settings) : null,
834
+ ask,
835
+ tell,
836
+ tickDurationSec,
837
+ isInChargeAtFirst: isServer,
838
+ tracksTouches: !isServer,
839
+ readDataFile: room && typeof room.readDataFile === "function" ? (path) => room.readDataFile(path) : null,
840
+ }),
841
+ // What net.use answers: physics' own calls over the core's world.
842
+ calls(things, kindContext) {
843
+ const isInCharge = () => kindContext.authorityKind === "host" && kindContext.isAuthority() && !kindContext.isSpectator;
844
+ // The simulation is opened when the world first needs it, and again after a restart: each is told whose game it is.
845
+ kindContext.onTick(() => {
846
+ if (things.simulation) things.simulation.ownCharacterId = kindContext.myPlayerId;
847
+ });
848
+ return physicsCalls({
849
+ plan,
850
+ settings,
851
+ hooks,
852
+ things,
853
+ ownCharacterId: kindContext.myPlayerId,
854
+ isInCharge,
855
+ isReady: () => isInCharge() || (world.playerCharacterMode === "on_join" && !kindContext.isSpectator ? things.drawn(kindContext.myPlayerId) !== null : kindContext.tickIndex() !== null),
856
+ hasGameServer: kindContext.authorityKind === "server",
857
+ });
858
+ },
859
+ // What physics.onServer(state, room) answers on a game server.
860
+ serverCalls: (things, kindContext) => physicsServerCalls({ plan, settings, things, roomState: kindContext.roomState }),
861
+ });
862
+ return Object.assign(physicsWorldKind, { settings, hooks, world, characterKind: kind });
863
+ };
864
+
865
+ /** Physics' calls on a game server, over the core's world there. */
866
+ function physicsServerCalls({ plan, settings, things, roomState }) {
867
+ const opened = things.simulation;
868
+ opened.roomState = () => roomState;
869
+ const simulation = opened.simulation;
870
+ const { kind } = plan;
871
+ const calls = {
872
+ /** This room's settings: they start as the kind's, are kept with the room's state, and changing them changes this room alone. */
873
+ get settings() {
874
+ const roomSettings = openSettings(statement, { ...settings.values, ...Object.fromEntries(BASE_SYNCED_SETTING_NAMES.map((name) => [name, opened.currentRules()[name]])) });
875
+ roomSettings.onChange(({ name, newValue }) => {
876
+ if (BASE_SYNCED_SETTING_NAMES.includes(name)) opened.setRules({ [name]: newValue });
877
+ });
878
+ return roomSettings;
879
+ },
880
+ /** This room's character kind's settings (a piece built on physics), as the room's settings are: this room's alone. Null for a kind with none. */
881
+ get characterSettings() {
882
+ if (!kind.settingsStatement) return null;
883
+ const rules = opened.currentRules();
884
+ const roomSettings = openSettings(kind.settingsStatement, { ...kind.settings.values, ...Object.fromEntries(plan.kindSyncedNames.map((name) => [name, rules[name]])) });
885
+ roomSettings.onChange(({ name, newValue }) => {
886
+ if (plan.kindSyncedNames.includes(name)) opened.setRules({ [name]: newValue });
887
+ });
888
+ return roomSettings;
889
+ },
890
+ ...sharedCalls({ plan, things, simulationNow: () => simulation, inChargeOf: () => things }),
891
+ ...queryCalls(() => simulation),
892
+ /** A bot's input from now on: only the fields given change. Answers false for a player's character. */
893
+ setInput: (characterId, input) => things.entityKindName(characterId) === "character" && Boolean(things.setInput(characterId, input)),
894
+ /** What steps said happened since this was last asked (emit), as the online core keeps them. */
895
+ takeEmitted: () => things.takeEmitted(),
896
+ };
897
+ return kind.serverCalls ? kind.serverCalls(calls, { things, simulation, opened, roomState }) : calls;
898
+ }
899
+
900
+ /**
901
+ * A world played alone: the same calls over the same simulation, stepped here with no room. update(nowMs) runs the
902
+ * fixed steps that are due on the clock it's given.
903
+ */
904
+ export function alonePhysics(givenWorld, { settings: givenSettings, hooks: givenHooks, ticksPerSec, playerId, characters, defineShape }) {
905
+ const world = worldOf(givenWorld);
906
+ const kind = kindOf(characters);
907
+ const plan = worldPlan(world, kind);
908
+ const { settings, hooks, ask, tell } = openPiece(statement, { settings: givenSettings, hooks: givenHooks });
909
+ const tickDurationSec = 1 / ticksPerSec;
910
+ const opened = openWorld({ plan, settings, kindSettings: kind.settings ?? null, ask, tell, tickDurationSec, isInChargeAtFirst: true });
911
+ const fields = worldFields(plan);
912
+ const shapes = Object.fromEntries(Object.entries(fields.entityKinds).map(([name, declared]) => [name, defineShape(declared.stateFields, { what: name, isPressAllowed: false })]));
913
+ const inputShape = defineShape(kind.inputFields, { what: "inputFields", isPressAllowed: true });
914
+ /** Every thing in the world: id to { entityKindName, earlier, later }, its fields after the last two steps. */
915
+ const entities = new Map();
916
+ const inputs = new Map();
917
+ const listeners = { added: new Set(), removed: new Set(), emitted: new Set() };
918
+ const nextStart = startStates(world);
919
+ let lastTickIndex = null;
920
+ let lastTickAtMs = 0;
921
+ let nowMs = 0;
922
+ /** Puts a thing's fields on their steps, as online: the same numbers alone as in a room. */
923
+ const onSteps = (entityKindName, state) => shapes[entityKindName].onSteps(state);
924
+
925
+ const things = {
926
+ simulation: opened,
927
+ stateShapeOf: (entityKindName) => shapes[entityKindName],
928
+ ids: (entityKindName) => [...entities].filter(([, entity]) => entity.entityKindName !== "rules" && entity.entityKindName !== "triangle_groups" && (entityKindName === undefined || entity.entityKindName === entityKindName)).map(([id]) => id),
929
+ has: (id) => entities.has(id),
930
+ entityKindName: (id) => entities.get(id)?.entityKindName ?? null,
931
+ state: (id) => entities.get(id)?.later ?? null,
932
+ /** A thing's fields between its last two steps, by how far the frame is into the next. */
933
+ drawn(id) {
934
+ const entity = entities.get(id);
935
+ if (!entity) return null;
936
+ const fractionNumber = Math.min(Math.max((nowMs - lastTickAtMs) / (tickDurationSec * 1000), 0), 1);
937
+ return shapes[entity.entityKindName].blend(entity.earlier, entity.later, fractionNumber);
938
+ },
939
+ add(id, { entityKindName = "character", state = {}, entityData = null } = {}) {
940
+ if (entities.has(id)) return false;
941
+ const shape = shapes[entityKindName];
942
+ const whole = shape.merged(shape.merged(shape.defaults(), entityKindName === "character" ? nextStart() : {}), state);
943
+ opened.add({ id, entityKindName, controllerPlayerId: id === playerId ? playerId : null, entityData }, whole);
944
+ const read = onSteps(entityKindName, opened.read(id) ?? whole);
945
+ entities.set(id, { entityKindName, earlier: read, later: read });
946
+ if (entityKindName === "character") inputs.set(id, inputShape.defaults());
947
+ for (const listener of [...listeners.added]) listener(id);
948
+ return true;
949
+ },
950
+ remove(id) {
951
+ if (!entities.has(id)) return false;
952
+ opened.remove(id);
953
+ entities.delete(id);
954
+ inputs.delete(id);
955
+ for (const listener of [...listeners.removed]) listener(id);
956
+ return true;
957
+ },
958
+ set(id, changes, setOptions = {}) {
959
+ const entity = entities.get(id);
960
+ if (!entity) return false;
961
+ const shape = shapes[entity.entityKindName];
962
+ opened.write(id, shape.merged(entity.later, shape.held(changes, "changes")), { isResting: false, isTeleport: setOptions.isTeleport !== false });
963
+ const read = onSteps(entity.entityKindName, opened.read(id));
964
+ entity.earlier = read;
965
+ entity.later = read;
966
+ return true;
967
+ },
968
+ setInput(input, id = playerId) {
969
+ const held = inputs.get(id);
970
+ if (!held) return false;
971
+ const given = inputShape.held(input, "input");
972
+ for (const [name, givenValue] of Object.entries(given)) held[name] = inputShape.pressNames.includes(name) ? held[name] || givenValue : givenValue;
973
+ return true;
974
+ },
975
+ takeEmitted: () => [],
976
+ on(eventName, listener) {
977
+ listeners[eventName].add(listener);
978
+ return () => listeners[eventName].delete(listener);
979
+ },
980
+ };
981
+ for (const entity of fields.entities) things.add(entity.id, { entityKindName: entity.entityKindName, state: entity.state });
982
+ if (world.playerCharacterMode === "on_join") things.add(playerId, { entityKindName: "character" });
983
+
984
+ const calls = physicsCalls({ plan, settings, hooks, things, ownCharacterId: playerId, isInCharge: () => true, isReady: () => true, hasGameServer: false });
985
+ return Object.assign(calls, {
986
+ /** Frees the engine's memory this world holds: a menu played alone, before the game joins a room. Nothing may be called on it after. */
987
+ dispose() {
988
+ opened.close();
989
+ entities.clear();
990
+ },
991
+ /** Hears what a step said happened (emit), as it happens. Answers a function that stops it. */
992
+ onEmitted(listener) {
993
+ listeners.emitted.add(listener);
994
+ return () => listeners.emitted.delete(listener);
995
+ },
996
+ /**
997
+ * Call every frame: runs the fixed steps that are due. Give the game's own clock in milliseconds to pause the
998
+ * world (a clock that stops) or slow it (one that runs slow); left out, it's the page's.
999
+ */
1000
+ update(givenNowMs = typeof performance === "object" ? performance.now() : Date.now()) {
1001
+ if (typeof givenNowMs !== "number" || !Number.isFinite(givenNowMs)) refuse("bad_argument", "update takes the clock in milliseconds, or nothing.", "nowMs", "Leave it out, or give a number that only grows, like performance.now().");
1002
+ nowMs = givenNowMs;
1003
+ const currentTickIndex = Math.floor(nowMs / (tickDurationSec * 1000));
1004
+ if (lastTickIndex === null) lastTickIndex = currentTickIndex - 1;
1005
+ // After a long pause (a hidden tab) only the newest few steps run, never thousands at once.
1006
+ for (let tickIndex = Math.max(lastTickIndex + 1, currentTickIndex - 7); tickIndex <= currentTickIndex; tickIndex += 1) {
1007
+ const emit = (eventName, payload = null, emitOptions = {}) => {
1008
+ for (const listener of [...listeners.emitted]) listener({ kindName: "physics", entityId: emitOptions.entityId ?? null, eventName, payload, tickIndex, playerId: emitOptions.entityId === playerId ? playerId : null, viewTickNumber: null, isReplay: false });
1009
+ };
1010
+ opened.step({ tickIndex, tickDurationSec, isReplay: false, isInCharge: true, inputOf: (id) => inputs.get(id) ?? null, emit });
1011
+ for (const held of inputs.values()) for (const name of inputShape.pressNames) held[name] = false;
1012
+ for (const [id, entity] of entities) {
1013
+ if (entity.entityKindName === "rules") continue;
1014
+ const isResting = opened.isResting(id);
1015
+ // A thing at rest is as it was: read once where it stopped, then nothing to read and nothing to blend.
1016
+ if (isResting && entity.isSettled) continue;
1017
+ const read = opened.read(id);
1018
+ if (!read) continue;
1019
+ const onStepsRead = onSteps(entity.entityKindName, read);
1020
+ // As online, every place steps on the wire's numbers.
1021
+ opened.write(id, onStepsRead, { isResting, isTeleport: false });
1022
+ entity.earlier = entity.isSettled ? onStepsRead : entity.later;
1023
+ entity.later = onStepsRead;
1024
+ entity.isSettled = isResting;
1025
+ if (isResting) entity.earlier = entity.later;
1026
+ }
1027
+ // The step's own time, not the frame's: a frame just before a step is due and the one after it then blend evenly.
1028
+ lastTickAtMs = tickIndex * tickDurationSec * 1000;
1029
+ }
1030
+ lastTickIndex = Math.max(lastTickIndex, currentTickIndex);
1031
+ },
1032
+ });
1033
+ }
1034
+
1035
+ export { turned };