@zaisma/physics 2.4.0 → 2.5.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/sync.js CHANGED
@@ -9,7 +9,7 @@
9
9
  // calls (physicsCalls), the same alone and online.
10
10
  import statement from "./piece.json.js";
11
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";
12
+ import { checkBody, checkId, checkJoint, refuse, rotationFromDeg, triangleGroupBitNumberOf, triangleGroupMaskIndexOf, worldOf, MAXIMUM_BODY_COUNT, MAXIMUM_CHARACTER_COUNT, MAXIMUM_JOINT_COUNT, MAXIMUM_TRIANGLE_GROUP_MASK_NUMBER, MAXIMUM_TRIANGLE_GROUP_NUMBER, MOTION_KINDS, WORLD_REACH_M } from "./declare.js";
13
13
  import { physicsEngine } from "./engine.js";
14
14
  import { defineCharacterKind, walkingCharacters } from "./characters.js";
15
15
  import { createSimulation, turned } from "./simulation.js";
@@ -18,7 +18,10 @@ import { createSimulation, turned } from "./simulation.js";
18
18
  const RULES_ID = "physics:rules";
19
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
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 }];
21
+ /** Which triangle groups are off: three whole numbers with a bit for each group (triangleGroupMaskIndexOf, triangleGroupBitNumberOf). */
22
+ const TRIANGLE_GROUP_MASK_NAMES = ["offMaskNumber", "offSecondMaskNumber", "offThirdMaskNumber"];
23
+ const TRIANGLE_GROUP_FIELDS = TRIANGLE_GROUP_MASK_NAMES.map((name) => ({ name, valueKind: "integer", minimumNumber: 0, maximumNumber: MAXIMUM_TRIANGLE_GROUP_MASK_NUMBER }));
24
+ const NO_TRIANGLE_GROUPS_OFF = Object.freeze(Object.fromEntries(TRIANGLE_GROUP_MASK_NAMES.map((name) => [name, 0])));
22
25
  const hasTriangleGroups = (world) => world.bodies.some((body) => body.shapes.some((shape) => shape.triangleGroupNumbers));
23
26
  /** The piece's settings every side steps by, in the order they're sent. */
24
27
  const BASE_SYNCED_SETTING_NAMES = ["gravityMPerSecPerSec", "bouncePct", "gripPct", "walkSpeedMPerSec", "jumpHeightM", "characterMassKg"];
@@ -28,6 +31,7 @@ const SET_CHARACTER_KEYS = ["positionM", "velocityMPerSec", "facingYawRad", "col
28
31
  // 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
32
  // engine drift a hair apart after going back, and nobody sees three centimetres. Whole numbers and yes-or-no fields
30
33
  // are never off at all.
34
+ // A place is on millimetres: a timetable's places are too (declare.js), so what a body carries keeps up with it exactly.
31
35
  const place = (name) => ({ name, valueKind: "number", minimumNumber: -WORLD_REACH_M, maximumNumber: WORLD_REACH_M, stepSizeNumber: 0.001, toleranceNumber: 0.03, snapAboveNumber: 3 });
32
36
  const speed = (name) => ({ name, valueKind: "number", minimumNumber: -250, maximumNumber: 250, stepSizeNumber: 0.02, toleranceNumber: 0.6 });
33
37
  const BODY_FIELDS = [
@@ -66,6 +70,14 @@ const CHARACTER_BASE_FIELDS = [
66
70
  { name: "layerNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: 15, defaultValue: 2 },
67
71
  ];
68
72
  const JOINT_FIELDS = [{ name: "isEnabled", valueKind: "boolean", defaultValue: true }];
73
+ // The same grain as the engine takes it, so a step leaves every awake body on the wire's steps (and reading it back
74
+ // from the wire changes nothing): each number field's range, step and count of steps, counted as the core's shape
75
+ // counts them, and how many steps each part of the rotation has.
76
+ const grainOf = (fieldName) => {
77
+ const field = BODY_FIELDS.find((each) => each.name === fieldName);
78
+ return { minimumNumber: field.minimumNumber, maximumNumber: field.maximumNumber, stepSizeNumber: field.stepSizeNumber, maximumStepCount: Math.ceil((field.maximumNumber - field.minimumNumber) / field.stepSizeNumber - 1e-9) };
79
+ };
80
+ const BODY_GRAIN = { place: grainOf("x"), speed: grainOf("velocityX"), spin: grainOf("spinX"), rotationMaximumStepCount: 2 ** BODY_FIELDS.find((each) => each.name === "rotation").componentBitCount - 1 };
69
81
 
70
82
  /** A rules field for a setting, as its statement states it. */
71
83
  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 });
@@ -88,7 +100,7 @@ function baseTuningOf(rules) {
88
100
  }
89
101
 
90
102
  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);
103
+ if (!given || !Number.isFinite(given.x) || !Number.isFinite(given.y) || !Number.isFinite(given.z)) refuse("bad_argument", `${what} isn't { x, y, z }.`, what, fix);
92
104
  return given;
93
105
  }
94
106
 
@@ -130,7 +142,7 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
130
142
  isStateOnSteps: true,
131
143
  };
132
144
  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 });
145
+ const simulation = createSimulation(physicsEngine(), world, { tickDurationSec, characterKind: kind, tuning: tuningOf({ ...defaultRules, ...ownRules() }), readDataFile, tracksTouches, bodyGrain: BODY_GRAIN });
134
146
  /** Where each character started, to put it back when it falls out of the world. */
135
147
  const startOf = new Map();
136
148
  /** The kind of thing each id is: "body", "character", "joint" or "rules". */
@@ -204,7 +216,7 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
204
216
  return;
205
217
  }
206
218
  if (entity.entityKindName === "triangle_groups") {
207
- simulation.setOffTriangleGroups(state.offMaskNumber);
219
+ simulation.setOffTriangleGroups(state.offMaskNumber, state.offSecondMaskNumber ?? 0, state.offThirdMaskNumber ?? 0);
208
220
  return;
209
221
  }
210
222
  if (entity.entityKindName === "joint") {
@@ -246,9 +258,10 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
246
258
  }
247
259
  if (entityKindName === "character") {
248
260
  const characterIndex = simulation.characterIndexById.get(entityId);
249
- return characterIndex === undefined ? null : simulation.readCharacter(characterIndex);
261
+ // The character's own object, filled again: the core reads it at once and keeps nothing.
262
+ return characterIndex === undefined ? null : simulation.readSteppedCharacter(characterIndex);
250
263
  }
251
- if (entityKindName === "triangle_groups") return { offMaskNumber: simulation.offTriangleGroupMaskNumber() };
264
+ if (entityKindName === "triangle_groups") return { offMaskNumber: simulation.offTriangleGroupMaskNumber(0), offSecondMaskNumber: simulation.offTriangleGroupMaskNumber(1), offThirdMaskNumber: simulation.offTriangleGroupMaskNumber(2) };
252
265
  if (entityKindName === "joint") {
253
266
  const isEnabled = simulation.joints.has(entityId) ? simulation.isJointEnabled(entityId) : pendingJoints.has(entityId) ? pendingJoints.get(entityId).isEnabled : null;
254
267
  if (isEnabled !== null) readJointEnabled.set(entityId, isEnabled);
@@ -256,7 +269,13 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
256
269
  }
257
270
  const bodyIndex = simulation.bodyIndexById.get(entityId);
258
271
  if (bodyIndex === undefined) return null;
259
- return { ...simulation.readBody(bodyIndex), bodyNumber: bodyIndex, bodyKindNumber: simulation.bodies[bodyIndex].declaration.bodyKindNumber };
272
+ // The body's own object, filled again: the core reads it at once and keeps nothing.
273
+ return simulation.readSteppedBody(bodyIndex);
274
+ },
275
+ /** Whether the last step left a body on the wire's steps itself, so what read answers needs no rounding and no writing back. */
276
+ isOnSteps(entityId) {
277
+ const bodyIndex = kindOf.get(entityId) === "body" ? simulation.bodyIndexById.get(entityId) : undefined;
278
+ return bodyIndex !== undefined && simulation.isBodyOnSteps(bodyIndex);
260
279
  },
261
280
  write(entityId, state, writeInfo) {
262
281
  const entityKindName = kindOf.get(entityId);
@@ -266,7 +285,7 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
266
285
  const characterIndex = simulation.characterIndexById.get(entityId);
267
286
  if (characterIndex !== undefined) simulation.writeCharacter(characterIndex, state, writeInfo.isResting);
268
287
  } else if (entityKindName === "triangle_groups") {
269
- simulation.setOffTriangleGroups(state.offMaskNumber);
288
+ simulation.setOffTriangleGroups(state.offMaskNumber, state.offSecondMaskNumber ?? 0, state.offThirdMaskNumber ?? 0);
270
289
  } else if (entityKindName === "joint") {
271
290
  if (simulation.joints.has(entityId)) simulation.setJointEnabled(entityId, state.isEnabled);
272
291
  else if (pendingJoints.has(entityId)) pendingJoints.get(entityId).isEnabled = state.isEnabled;
@@ -314,10 +333,10 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
314
333
  const bodyIndex = simulation.bodyIndexById.get(entityId);
315
334
  return bodyIndex !== undefined && simulation.isBodyResting(bodyIndex);
316
335
  },
317
- step({ tickIndex, isReplay, inputOf, isInCharge: isInChargeNow, emit }) {
336
+ step({ tickIndex, timetableTickIndex = tickIndex, isReplay, inputOf, isInCharge: isInChargeNow, emit }) {
318
337
  isInCharge = isInChargeNow;
319
338
  decideRules();
320
- simulation.step({ tickIndex, isReplay, isInCharge, inputOf, emit: emit ?? (() => {}), roomState: opened.roomState, ask, tell });
339
+ simulation.step({ tickIndex, timetableTickIndex, isReplay, isInCharge, inputOf, emit: emit ?? (() => {}), roomState: opened.roomState, ask, tell });
321
340
  const hits = simulation.takeHits();
322
341
  // A step run again already happened: no sound, no hook, twice.
323
342
  if (!isReplay) {
@@ -334,9 +353,7 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
334
353
  const backM = putBack(startOf.get(character.id) ?? world.startPositionsM[0], character.id, true);
335
354
  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
355
  }
337
- simulation.forEachAwakeBody((bodyIndex) => {
338
- if (simulation.readBody(bodyIndex).y < world.fallOutHeightM) fallen.push(bodyIndex);
339
- });
356
+ simulation.addAwakeBodiesBelow(world.fallOutHeightM, fallen);
340
357
  for (const bodyIndex of fallen.splice(0)) {
341
358
  const declaration = simulation.bodies[bodyIndex].declaration;
342
359
  const backM = putBack(declaration.positionM, declaration.id, false);
@@ -380,7 +397,7 @@ function worldFields(plan) {
380
397
  { id: RULES_ID, entityKindName: "rules", state: { ...plan.defaultRules } },
381
398
  ...world.bodies.flatMap((body, bodyIndex) => (body.motionKind !== "fixed" ? [{ id: body.id, entityKindName: "body", state: declaredBodyFields(body, bodyIndex, body.bodyKindNumber, world) }] : [])),
382
399
  ...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 } }] : []),
400
+ ...(hasTriangleGroups(world) ? [{ id: TRIANGLE_GROUPS_ID, entityKindName: "triangle_groups", state: { ...NO_TRIANGLE_GROUPS_OFF } }] : []),
384
401
  ],
385
402
  };
386
403
  }
@@ -422,6 +439,7 @@ function checkAddedBody(world, declaration) {
422
439
  if (declaration === null || typeof declaration !== "object" || declaration.bodyKindName === undefined) {
423
440
  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
441
  }
442
+ if (declaration.timetable !== undefined) refuse("bad_body", "A body added while playing has a timetable.", "body.timetable", "Declare a body on a timetable in the world's bodies, in the game and on its game server: every side works out where it is from the step alone.");
425
443
  // How it moves from the start: a building piece placed fixed on a plot, never moving first.
426
444
  const { motionKind, ...rest } = declaration;
427
445
  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.`);
@@ -524,27 +542,46 @@ const ownOf = (plan, fields, simulation = null, characterId = null) => {
524
542
  return Object.fromEntries(plan.kind.stateFields.map((field) => [field.name, field.isShared === false ? (localOwn?.[field.name] ?? null) : fields[field.name]]));
525
543
  };
526
544
 
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) {
545
+ /** What each query takes, beside collisionLayerNames and excludedId (and, for a shape, isStoppedAtPenetration, rotation and marginM). */
546
+ const QUERY_KEYS = {
547
+ castRay: ["fromM", "directionM", "maximumDistanceM"],
548
+ castBall: ["fromM", "radiusM", "directionM", "maximumDistanceM"],
549
+ castCapsule: ["fromM", "radiusM", "heightM", "directionM", "maximumDistanceM"],
550
+ overlapCapsule: ["centerM", "radiusM", "heightM"],
551
+ overlapBall: ["centerM", "radiusM"],
552
+ };
553
+ const SHAPE_QUERY_KEYS = ["isStoppedAtPenetration", "rotation", "marginM"];
554
+ const OVERLAP_QUERY_KEYS = [...SHAPE_QUERY_KEYS, "isEachTriangle", "isOneSided"];
555
+
556
+ /**
557
+ * A query's request, checked: the points and lengths a ray, a ball's sweep or an overlap takes. The request itself
558
+ * goes on to the search, and checking it makes nothing: a game asks thousands a second.
559
+ */
560
+ function checkQuery(given, what, isShape = false) {
561
+ const keys = QUERY_KEYS[what];
529
562
  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.");
563
+ for (const key in given) if (!keys.includes(key) && key !== "collisionLayerNames" && key !== "excludedId" && !(isShape && (what === "overlapCapsule" ? OVERLAP_QUERY_KEYS : SHAPE_QUERY_KEYS).includes(key))) refuse("unknown_argument", `${what} has no "${key}".`, key, `It takes: ${keys.join(", ")}, collisionLayerNames, excludedId.`);
564
+ for (let keyIndex = 0; keyIndex < keys.length; keyIndex += 1) {
565
+ const key = keys[keyIndex];
566
+ const givenValue = given[key];
567
+ if (typeof givenValue === "object" && key.endsWith("M")) pointOrRefuse(givenValue, key, "Give three numbers: x, y and z, in metres.");
568
+ else if (!Number.isFinite(givenValue) || givenValue < 0) refuse("bad_argument", `${key} is ${JSON.stringify(givenValue)}.`, key, "Give a length in metres from 0.");
534
569
  }
535
570
  return given;
536
571
  }
537
572
 
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 ?? {};
573
+ /** A shape's query, checked: its points and lengths, and the isStoppedAtPenetration, rotation and marginM a shape's cast and overlap take beside them. */
574
+ function shapeQueryOf(request, what) {
575
+ const { isStoppedAtPenetration, rotation, marginM } = checkQuery(request, what, true);
542
576
  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.");
577
+ if (rotation !== undefined && !(rotation && Number.isFinite(rotation.x) && Number.isFinite(rotation.y) && Number.isFinite(rotation.z) && Number.isFinite(rotation.w))) 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
578
  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 }) };
579
+ if (request.isEachTriangle !== undefined && typeof request.isEachTriangle !== "boolean") refuse("bad_argument", "isEachTriangle isn't true or false.", "isEachTriangle", "Give true for every triangle of a mesh the capsule touches, or leave it out for the deepest one of each mesh.");
580
+ if (request.isOneSided !== undefined && typeof request.isOneSided !== "boolean") refuse("bad_argument", "isOneSided isn't true or false.", "isOneSided", "Give true to leave out triangles that face away from the capsule, or leave it out.");
581
+ return request;
546
582
  }
547
583
 
584
+ /** The queries a game asks of a world: the same alone, in a player's game and on a game server. */
548
585
  function queryCalls(simulationNow) {
549
586
  const checkInto = (into) => {
550
587
  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.");
@@ -552,15 +589,21 @@ function queryCalls(simulationNow) {
552
589
  };
553
590
  return {
554
591
  /** 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,
592
+ castRay: (request, into) => simulationNow()?.castRay(checkQuery(request, "castRay"), checkInto(into)) ?? null,
556
593
  /** 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,
594
+ castBall: (request, into) => simulationNow()?.castBall(shapeQueryOf(request, "castBall"), checkInto(into)) ?? null,
558
595
  /** 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,
596
+ castCapsule: (request, into) => simulationNow()?.castCapsule(shapeQueryOf(request, "castCapsule"), checkInto(into)) ?? null,
560
597
  /** 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")) ?? [],
598
+ overlapCapsule(request, into) {
599
+ if (into !== undefined && into !== null && !Array.isArray(into)) refuse("bad_argument", "into isn't a list.", "into", "Give a list of your own to write the contacts into (kept and given again), or leave it out for a new one.");
600
+ const simulation = simulationNow();
601
+ if (simulation) return simulation.overlapCapsule(shapeQueryOf(request, "overlapCapsule"), into ?? null);
602
+ if (into) into.length = 0;
603
+ return into ?? [];
604
+ },
562
605
  /** Everything a ball overlaps: [{ bodyId, characterId }]. */
563
- overlapBall: (request) => simulationNow()?.overlapBall(checkQuery(request, ["centerM", "radiusM"], "overlapBall")) ?? [],
606
+ overlapBall: (request) => simulationNow()?.overlapBall(checkQuery(request, "overlapBall")) ?? [],
564
607
  };
565
608
  }
566
609
 
@@ -569,7 +612,7 @@ function queryCalls(simulationNow) {
569
612
  * online core's World gives it (ids, has, entityKindName, state, drawn, add, remove, set, setInput, on, simulation),
570
613
  * and the rest says who this game is in it.
571
614
  */
572
- function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharge, isReady, hasGameServer }) {
615
+ function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharge, isReady, hasGameServer, tickNumber }) {
573
616
  const { world, kind } = plan;
574
617
  const listeners = Object.fromEntries(LISTENED_EVENT_NAMES.map((eventName) => [eventName, new Set()]));
575
618
  /** Each thing's kind, kept so a removal can still say what was removed. */
@@ -599,8 +642,12 @@ function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharg
599
642
  return null;
600
643
  };
601
644
  /** Where a body is drawn: a moving one from the world in play, a fixed one where it's declared. */
645
+ const timetabledPlace = { x: 0, y: 0, z: 0, rotationX: 0, rotationY: 0, rotationZ: 0, rotationW: 1 };
602
646
  const drawnOf = (bodyId) => {
603
647
  const drawn = isBody(bodyId) ? things.drawn(bodyId) : null;
648
+ // A body on a timetable is drawn where this frame's moment has it, between two steps.
649
+ const simulation = drawn ? simulationNow() : null;
650
+ if (simulation?.timetablePlace(simulation.bodyIndexById.get(bodyId), tickNumber(), timetabledPlace)) return { ...drawn, x: timetabledPlace.x, y: timetabledPlace.y, z: timetabledPlace.z, rotation: { x: timetabledPlace.rotationX, y: timetabledPlace.rotationY, z: timetabledPlace.rotationZ, w: timetabledPlace.rotationW } };
604
651
  if (drawn) return drawn;
605
652
  const declaration = world.bodies.find((body) => body.id === bodyId && body.motionKind === "fixed");
606
653
  return declaration ? { x: declaration.positionM.x, y: declaration.positionM.y, z: declaration.positionM.z, rotation: declaration.rotation } : null;
@@ -706,6 +753,7 @@ function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
706
753
  const fields = bodyChanges(world, changes);
707
754
  if (!isBody(bodyId)) return world.bodies.some((body) => body.id === bodyId) ? false : unknownBody(bodyId);
708
755
  const isMoved = ["x", "y", "z", "rotation"].some((name) => name in fields);
756
+ if (world.bodies.some((body) => body.id === bodyId && body.timetable) && Object.keys(fields).some((name) => name !== "layerNumber")) refuse("bad_argument", `setBody was given more than a collision layer for "${bodyId}", which is on a timetable.`, "changes", "Its timetable says where it is at every step: give collisionLayerName alone, or declare it without a timetable to move it yourself.");
709
757
  return Boolean(running && running.set(bodyId, fields, { isTeleport: isMoved }));
710
758
  },
711
759
  pushBody(bodyId, pushMPerSec) {
@@ -787,18 +835,19 @@ function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
787
835
  return Boolean(running && running.set(jointId, { isEnabled: changes.isEnabled }, { isTeleport: false }));
788
836
  },
789
837
  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. */
838
+ /** Switches one of the world's triangle groups on or off for everyone (a door that opens, a bridge that falls), 1 to 63. */
791
839
  setTriangleGroup(groupNumber, isEnabled) {
792
840
  const running = inChargeOf("triangle groups are switched");
793
841
  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
842
  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
843
  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 }));
844
+ const maskName = TRIANGLE_GROUP_MASK_NAMES[triangleGroupMaskIndexOf(groupNumber)];
845
+ const maskNumber = things.state(TRIANGLE_GROUPS_ID)?.[maskName] ?? 0;
846
+ const bitNumber = triangleGroupBitNumberOf(groupNumber);
847
+ return Boolean(running && running.set(TRIANGLE_GROUPS_ID, { [maskName]: isEnabled ? maskNumber & ~bitNumber : maskNumber | bitNumber }, { isTeleport: false }));
799
848
  },
800
849
  /** Whether a triangle group is there now. */
801
- isTriangleGroupEnabled: (groupNumber) => !((things.state(TRIANGLE_GROUPS_ID)?.offMaskNumber ?? 0) & (1 << (groupNumber - 1))),
850
+ isTriangleGroupEnabled: (groupNumber) => !((things.state(TRIANGLE_GROUPS_ID)?.[TRIANGLE_GROUP_MASK_NAMES[triangleGroupMaskIndexOf(groupNumber)]] ?? 0) & triangleGroupBitNumberOf(groupNumber)),
802
851
  };
803
852
  }
804
853
 
@@ -854,6 +903,7 @@ export const physicsKindFrom = (worldKind) => (givenWorld, given = {}) => {
854
903
  isInCharge,
855
904
  isReady: () => isInCharge() || (world.playerCharacterMode === "on_join" && !kindContext.isSpectator ? things.drawn(kindContext.myPlayerId) !== null : kindContext.tickIndex() !== null),
856
905
  hasGameServer: kindContext.authorityKind === "server",
906
+ tickNumber: () => (kindContext.tickIndex() ?? 0) + kindContext.fractionNumber(),
857
907
  });
858
908
  },
859
909
  // What physics.onServer(state, room) answers on a game server.
@@ -897,6 +947,27 @@ function physicsServerCalls({ plan, settings, things, roomState }) {
897
947
  return kind.serverCalls ? kind.serverCalls(calls, { things, simulation, opened, roomState }) : calls;
898
948
  }
899
949
 
950
+ /** A body's place, rotation, speed and spin from what a step left, with the fields a step doesn't move from where they were last put on steps. */
951
+ function copyMotion(into, read, rest) {
952
+ into.x = read.x;
953
+ into.y = read.y;
954
+ into.z = read.z;
955
+ into.rotation.x = read.rotation.x;
956
+ into.rotation.y = read.rotation.y;
957
+ into.rotation.z = read.rotation.z;
958
+ into.rotation.w = read.rotation.w;
959
+ into.velocityX = read.velocityX;
960
+ into.velocityY = read.velocityY;
961
+ into.velocityZ = read.velocityZ;
962
+ into.spinX = read.spinX;
963
+ into.spinY = read.spinY;
964
+ into.spinZ = read.spinZ;
965
+ into.layerNumber = rest.layerNumber;
966
+ into.motionNumber = rest.motionNumber;
967
+ into.steerNumber = rest.steerNumber;
968
+ into.massKg = rest.massKg;
969
+ }
970
+
900
971
  /**
901
972
  * A world played alone: the same calls over the same simulation, stepped here with no room. update(nowMs) runs the
902
973
  * fixed steps that are due on the clock it's given.
@@ -919,6 +990,8 @@ export function alonePhysics(givenWorld, { settings: givenSettings, hooks: given
919
990
  let lastTickIndex = null;
920
991
  let lastTickAtMs = 0;
921
992
  let nowMs = 0;
993
+ /** Steps run so far: the clock of the world's timetables, which starts with the world and never skips. */
994
+ let ranTickCount = 0;
922
995
  /** Puts a thing's fields on their steps, as online: the same numbers alone as in a room. */
923
996
  const onSteps = (entityKindName, state) => shapes[entityKindName].onSteps(state);
924
997
 
@@ -981,7 +1054,47 @@ export function alonePhysics(givenWorld, { settings: givenSettings, hooks: given
981
1054
  for (const entity of fields.entities) things.add(entity.id, { entityKindName: entity.entityKindName, state: entity.state });
982
1055
  if (world.playerCharacterMode === "on_join") things.add(playerId, { entityKindName: "character" });
983
1056
 
984
- const calls = physicsCalls({ plan, settings, hooks, things, ownCharacterId: playerId, isInCharge: () => true, isReady: () => true, hasGameServer: false });
1057
+ const steppedWriteInfo = { isResting: false, isTeleport: false };
1058
+ /** After a step: a thing's fields as the step left them, on the wire's steps as online, beside the step before for drawing between the two. */
1059
+ function takeStepped(entity, id) {
1060
+ if (entity.entityKindName === "rules") return;
1061
+ const isResting = opened.isResting(id);
1062
+ // A thing at rest is as it was: read once where it stopped, then nothing to read and nothing to blend.
1063
+ if (isResting && entity.isSettled) return;
1064
+ const read = opened.read(id);
1065
+ if (!read) return;
1066
+ let onStepsRead;
1067
+ if (entity.entityKindName === "body" && entity.onStepsRest && opened.isOnSteps(id) && read.layerNumber === entity.readLayerNumber && read.motionNumber === entity.readMotionNumber && read.steerNumber === entity.readSteerNumber && read.massKg === entity.readMassKg) {
1068
+ // The step left it on the wire's steps already: nothing to round and nothing to write back, so a
1069
+ // thousand bodies falling leave nothing for the garbage collector. Its fields go into one of two
1070
+ // objects of its own, turn about (nothing outside keeps them).
1071
+ if (!entity.ownFirst) {
1072
+ entity.ownFirst = { ...entity.onStepsRest, rotation: { x: 0, y: 0, z: 0, w: 1 } };
1073
+ entity.ownSecond = { ...entity.onStepsRest, rotation: { x: 0, y: 0, z: 0, w: 1 } };
1074
+ }
1075
+ onStepsRead = entity.later === entity.ownFirst ? entity.ownSecond : entity.ownFirst;
1076
+ copyMotion(onStepsRead, read, entity.onStepsRest);
1077
+ } else {
1078
+ onStepsRead = onSteps(entity.entityKindName, read);
1079
+ // As online, every place steps on the wire's numbers.
1080
+ steppedWriteInfo.isResting = isResting;
1081
+ opened.write(id, onStepsRead, steppedWriteInfo);
1082
+ if (entity.entityKindName === "body") {
1083
+ entity.readLayerNumber = read.layerNumber;
1084
+ entity.readMotionNumber = read.motionNumber;
1085
+ entity.readSteerNumber = read.steerNumber;
1086
+ entity.readMassKg = read.massKg;
1087
+ entity.onStepsRest = onStepsRead;
1088
+ }
1089
+ }
1090
+ entity.earlier = entity.isSettled ? onStepsRead : entity.later;
1091
+ entity.later = onStepsRead;
1092
+ entity.isSettled = isResting;
1093
+ if (isResting) entity.earlier = entity.later;
1094
+ }
1095
+ // The moment a frame draws: the last step run, and how far the clock is into the next.
1096
+ const tickNumber = () => Math.max(ranTickCount - 1, 0) + Math.min(Math.max((nowMs - lastTickAtMs) / (tickDurationSec * 1000), 0), 1);
1097
+ const calls = physicsCalls({ plan, settings, hooks, things, ownCharacterId: playerId, isInCharge: () => true, isReady: () => true, hasGameServer: false, tickNumber });
985
1098
  return Object.assign(calls, {
986
1099
  /** 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
1100
  dispose() {
@@ -1007,23 +1120,10 @@ export function alonePhysics(givenWorld, { settings: givenSettings, hooks: given
1007
1120
  const emit = (eventName, payload = null, emitOptions = {}) => {
1008
1121
  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
1122
  };
1010
- opened.step({ tickIndex, tickDurationSec, isReplay: false, isInCharge: true, inputOf: (id) => inputs.get(id) ?? null, emit });
1123
+ opened.step({ tickIndex, timetableTickIndex: ranTickCount, tickDurationSec, isReplay: false, isInCharge: true, inputOf: (id) => inputs.get(id) ?? null, emit });
1124
+ ranTickCount += 1;
1011
1125
  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
- }
1126
+ entities.forEach(takeStepped);
1027
1127
  // 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
1128
  lastTickAtMs = tickIndex * tickDurationSec * 1000;
1029
1129
  }