@zaisma/physics 2.5.0 → 2.6.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, 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";
12
+ import { checkBody, checkId, checkJoint, refuse, rotationFromDeg, triangleGroupBitNumberOf, triangleGroupMaskIndexOf, worldOf, MAXIMUM_BODY_COUNT, MAXIMUM_CHARACTER_COUNT, MAXIMUM_CHARACTER_SIZE_COUNT, MAXIMUM_FIXED_BODY_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";
@@ -27,7 +27,8 @@ const hasTriangleGroups = (world) => world.bodies.some((body) => body.shapes.som
27
27
  const BASE_SYNCED_SETTING_NAMES = ["gravityMPerSecPerSec", "bouncePct", "gripPct", "walkSpeedMPerSec", "jumpHeightM", "characterMassKg"];
28
28
  const LISTENED_EVENT_NAMES = ["bodyAdded", "bodyRemoved", "characterAdded", "characterRemoved"];
29
29
  const SET_BODY_KEYS = ["positionM", "rotationDeg", "velocityMPerSec", "spinRadPerSec", "motionKind", "collisionLayerName", "massKg"];
30
- const SET_CHARACTER_KEYS = ["positionM", "velocityMPerSec", "facingYawRad", "collisionLayerName", "own"];
30
+ const SET_CHARACTER_KEYS = ["positionM", "velocityMPerSec", "facingYawRad", "collisionLayerName", "characterSizeName", "own"];
31
+ const ADD_CHARACTER_KEYS = ["positionM", "characterSizeName"];
31
32
  // 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
32
33
  // engine drift a hair apart after going back, and nobody sees three centimetres. Whole numbers and yes-or-no fields
33
34
  // are never off at all.
@@ -44,7 +45,7 @@ const BODY_FIELDS = [
44
45
  speed("velocityZ"),
45
46
  ...["spinX", "spinY", "spinZ"].map((name) => ({ name, valueKind: "number", minimumNumber: -120, maximumNumber: 120, stepSizeNumber: 0.05, toleranceNumber: 1.5 })),
46
47
  // 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).
47
- { name: "bodyNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: MAXIMUM_BODY_COUNT },
48
+ { name: "bodyNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: MAXIMUM_BODY_COUNT + MAXIMUM_FIXED_BODY_COUNT },
48
49
  { name: "bodyKindNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: 255 },
49
50
  // Which of the world's collision layers it's on, and how it moves now (moving, kinematic or fixed): a parked cart made fixed.
50
51
  { name: "layerNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: 15, defaultValue: 1 },
@@ -65,9 +66,11 @@ const CHARACTER_BASE_FIELDS = [
65
66
  { name: "isGrounded", valueKind: "boolean" },
66
67
  { name: "airTickCount", valueKind: "integer", minimumNumber: 0, maximumNumber: 250 },
67
68
  // The body it rides in (its number and one more, 0 for none), and which of its seats.
68
- { name: "rideBodyNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: MAXIMUM_BODY_COUNT + 1 },
69
+ { name: "rideBodyNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: MAXIMUM_BODY_COUNT + MAXIMUM_FIXED_BODY_COUNT + 1 },
69
70
  { name: "seatIndex", valueKind: "integer", minimumNumber: 0, maximumNumber: 7 },
70
71
  { name: "layerNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: 15, defaultValue: 2 },
72
+ // Which size it is: 0 for the world's own character's, then the world's characterSizes in order.
73
+ { name: "sizeNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: MAXIMUM_CHARACTER_SIZE_COUNT },
71
74
  ];
72
75
  const JOINT_FIELDS = [{ name: "isEnabled", valueKind: "boolean", defaultValue: true }];
73
76
  // The same grain as the engine takes it, so a step leaves every awake body on the wire's steps (and reading it back
@@ -196,8 +199,7 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
196
199
  },
197
200
  /** The next body number nothing has. */
198
201
  freeBodyNumber() {
199
- const freeIndex = simulation.bodies.findIndex((held) => held === null);
200
- return freeIndex === -1 ? simulation.bodies.length : freeIndex;
202
+ return simulation.freeBodyIndex();
201
203
  },
202
204
  add(entity, state) {
203
205
  kindOf.set(entity.id, entity.entityKindName);
@@ -446,6 +448,12 @@ function checkAddedBody(world, declaration) {
446
448
  return { ...checkBody(rest, "body", world.bodyKinds), startMotionKind: motionKind ?? "moving" };
447
449
  }
448
450
 
451
+ /** A size's number on the wire: 0 for the world's own character's (null), then the world's characterSizes in order. */
452
+ const sizeNumberOf = (world, characterSizeName) => {
453
+ const sizeNumber = characterSizeName === null ? 0 : world.characterSizes.findIndex((size) => size.name === characterSizeName) + 1;
454
+ if (sizeNumber === 0 && characterSizeName !== null) refuse("bad_argument", `characterSizeName is ${JSON.stringify(characterSizeName)}.`, "characterSizeName", `Use one of the world's characterSizes (${world.characterSizes.map((size) => size.name).join(", ") || "it names none"}), or null for the world's own character.`);
455
+ return sizeNumber;
456
+ };
449
457
  const layerNumberOf = (world, layerName, what) => {
450
458
  const layerNumber = world.collisionLayers.findIndex((layer) => layer.name === layerName);
451
459
  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(", ")}.`);
@@ -493,7 +501,7 @@ function bodyStateOf(simulation, bodyId) {
493
501
  };
494
502
  }
495
503
 
496
- const isFixedBody = (world, bodyId) => world.bodies.some((body) => body.id === bodyId && body.motionKind === "fixed");
504
+ const isFixedBody = (world, bodyId) => world.bodyById.get(bodyId)?.motionKind === "fixed";
497
505
  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.");
498
506
  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.");
499
507
 
@@ -518,6 +526,7 @@ function characterView(world, simulation, fields, characterId) {
518
526
  rideBodyId: rideIndex >= 0 ? (simulation?.bodies[rideIndex]?.declaration.id ?? null) : null,
519
527
  seatIndex: rideIndex >= 0 ? fields.seatIndex : null,
520
528
  collisionLayerName: world.collisionLayers[fields.layerNumber]?.name ?? "character",
529
+ characterSizeName: world.characterSizes[(fields.sizeNumber ?? 0) - 1]?.name ?? null,
521
530
  };
522
531
  }
523
532
 
@@ -649,7 +658,7 @@ function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharg
649
658
  const simulation = drawn ? simulationNow() : null;
650
659
  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 } };
651
660
  if (drawn) return drawn;
652
- const declaration = world.bodies.find((body) => body.id === bodyId && body.motionKind === "fixed");
661
+ const declaration = isFixedBody(world, bodyId) ? world.bodyById.get(bodyId) : null;
653
662
  return declaration ? { x: declaration.positionM.x, y: declaration.positionM.y, z: declaration.positionM.z, rotation: declaration.rotation } : null;
654
663
  };
655
664
  const shared = sharedCalls({ plan, things, simulationNow, inChargeOf: inCharge });
@@ -677,7 +686,7 @@ function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharg
677
686
  bodyDeclaration(bodyId) {
678
687
  const simulation = simulationNow();
679
688
  if (simulation) return simulation.bodies[simulation.bodyIndexById.get(bodyId)]?.declaration ?? null;
680
- return world.bodies.find((body) => body.id === bodyId) ?? null;
689
+ return world.bodyById.get(bodyId) ?? null;
681
690
  },
682
691
  /** Where to draw a body this frame: { positionM, rotation, steerNumber }. null for a body that isn't here. */
683
692
  drawnBody(bodyId) {
@@ -734,7 +743,7 @@ function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
734
743
  // Every thing in play, declared ones included: an id freed by a removal may be used again, even in the same step.
735
744
  const ids = () => new Set(things.ids());
736
745
  return {
737
- bodyIds: () => [...world.bodies.filter((body) => body.motionKind === "fixed").map((body) => body.id), ...things.ids("body")],
746
+ bodyIds: () => [...world.fixedBodyIds, ...things.ids("body")],
738
747
  hasBody: (bodyId) => isBody(bodyId) || isFixedBody(world, bodyId),
739
748
  /** A body as this world has it now. */
740
749
  bodyState: (bodyId) => bodyStateOf(simulationNow(), bodyId),
@@ -751,9 +760,9 @@ function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
751
760
  setBody(bodyId, changes) {
752
761
  const running = inChargeOf("bodies are set");
753
762
  const fields = bodyChanges(world, changes);
754
- if (!isBody(bodyId)) return world.bodies.some((body) => body.id === bodyId) ? false : unknownBody(bodyId);
763
+ if (!isBody(bodyId)) return world.bodyById.has(bodyId) ? false : unknownBody(bodyId);
755
764
  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.");
765
+ if (world.bodyById.get(bodyId)?.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.");
757
766
  return Boolean(running && running.set(bodyId, fields, { isTeleport: isMoved }));
758
767
  },
759
768
  pushBody(bodyId, pushMPerSec) {
@@ -775,8 +784,11 @@ function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
775
784
  const running = inChargeOf("characters are added");
776
785
  if (!running || things.has(characterId)) return false;
777
786
  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.");
787
+ for (const key of Object.keys(addOptions ?? {})) if (!ADD_CHARACTER_KEYS.includes(key)) refuse("unknown_argument", `addCharacter has no "${key}".`, key, `It takes: ${ADD_CHARACTER_KEYS.join(", ")}.`);
778
788
  const feetM = addOptions?.positionM === undefined ? null : pointOrRefuse(addOptions.positionM, "positionM", "Give where its feet stand, in metres.");
779
- return Boolean(running.add(characterId, { entityKindName: "character", ...(feetM ? { state: { x: feetM.x, y: feetM.y + world.character.heightM / 2, z: feetM.z } } : {}) }));
789
+ const sizeNumber = addOptions?.characterSizeName === undefined ? 0 : sizeNumberOf(world, addOptions.characterSizeName);
790
+ const state = { ...(feetM ? { x: feetM.x, y: feetM.y + world.character.heightM / 2, z: feetM.z } : {}), ...(sizeNumber ? { sizeNumber } : {}) };
791
+ return Boolean(running.add(characterId, { entityKindName: "character", ...(Object.keys(state).length ? { state } : {}) }));
780
792
  },
781
793
  removeCharacter: (characterId) => Boolean(inChargeOf("characters are removed") && isCharacter(characterId) && things.remove(characterId)),
782
794
  /** Sets a character at once: its feet's place (a teleport), its speed, facing, collision layer, or its kind's own fields. */
@@ -792,6 +804,7 @@ function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
792
804
  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 });
793
805
  if (changes?.facingYawRad !== undefined) fields.facingYawRad = changes.facingYawRad;
794
806
  if (changes?.collisionLayerName !== undefined) fields.layerNumber = layerNumberOf(world, changes.collisionLayerName, "collisionLayerName");
807
+ if (changes?.characterSizeName !== undefined) fields.sizeNumber = sizeNumberOf(world, changes.characterSizeName);
795
808
  if (changes?.own !== undefined) {
796
809
  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)"}.`);
797
810
  for (const [name, ownValue] of Object.entries(changes.own)) {