@zaisma/physics 2.6.0 → 2.8.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,10 +9,11 @@
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_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";
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_MOTOR_TARGET_NUMBER, 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";
16
+ import { defineBodyBehaviors } from "./bodies.js";
16
17
 
17
18
  /** The one thing in every world that holds its rules: the settings every side must step by. */
18
19
  const RULES_ID = "physics:rules";
@@ -22,11 +23,25 @@ const TRIANGLE_GROUPS_ID = "physics:triangle_groups";
22
23
  const TRIANGLE_GROUP_MASK_NAMES = ["offMaskNumber", "offSecondMaskNumber", "offThirdMaskNumber"];
23
24
  const TRIANGLE_GROUP_FIELDS = TRIANGLE_GROUP_MASK_NAMES.map((name) => ({ name, valueKind: "integer", minimumNumber: 0, maximumNumber: MAXIMUM_TRIANGLE_GROUP_MASK_NUMBER }));
24
25
  const NO_TRIANGLE_GROUPS_OFF = Object.freeze(Object.fromEntries(TRIANGLE_GROUP_MASK_NAMES.map((name) => [name, 0])));
26
+ /** Which zones are switched off, as one thing of whole numbers with a bit a zone: only in a world that has zones. */
27
+ const ZONE_SWITCHES_ID = "physics:zone_switches";
28
+ const ZONE_MASK_BIT_COUNT = 24;
29
+ const zoneMaskNameOf = (maskIndex) => `off${maskIndex}MaskNumber`;
30
+ const zoneMaskFieldsOf = (world) => Array.from({ length: Math.ceil(world.zones.length / ZONE_MASK_BIT_COUNT) }, (unused, maskIndex) => ({ name: zoneMaskNameOf(maskIndex), valueKind: "integer", minimumNumber: 0, maximumNumber: 2 ** ZONE_MASK_BIT_COUNT - 1 }));
31
+ /** The switches' fields from whether each zone is on. */
32
+ const zoneSwitchesOf = (world, isEnabledOf) => {
33
+ const state = Object.fromEntries(zoneMaskFieldsOf(world).map((field) => [field.name, 0]));
34
+ for (const [zoneIndex, zone] of world.zones.entries()) if (!isEnabledOf(zone)) state[zoneMaskNameOf(Math.floor(zoneIndex / ZONE_MASK_BIT_COUNT))] |= 1 << (zoneIndex % ZONE_MASK_BIT_COUNT);
35
+ return state;
36
+ };
37
+ const isZoneOffIn = (state, zoneIndex) => Boolean((state?.[zoneMaskNameOf(Math.floor(zoneIndex / ZONE_MASK_BIT_COUNT))] ?? 0) & (1 << (zoneIndex % ZONE_MASK_BIT_COUNT)));
25
38
  const hasTriangleGroups = (world) => world.bodies.some((body) => body.shapes.some((shape) => shape.triangleGroupNumbers));
26
39
  /** The piece's settings every side steps by, in the order they're sent. */
27
40
  const BASE_SYNCED_SETTING_NAMES = ["gravityMPerSecPerSec", "bouncePct", "gripPct", "walkSpeedMPerSec", "jumpHeightM", "characterMassKg"];
28
41
  const LISTENED_EVENT_NAMES = ["bodyAdded", "bodyRemoved", "characterAdded", "characterRemoved"];
29
- const SET_BODY_KEYS = ["positionM", "rotationDeg", "velocityMPerSec", "spinRadPerSec", "motionKind", "collisionLayerName", "massKg"];
42
+ const SET_BODY_KEYS = ["positionM", "rotationDeg", "velocityMPerSec", "spinRadPerSec", "motionKind", "collisionLayerName", "massKg", "own"];
43
+ /** Whether a kind of thing on the wire is a body: the piece's own, or one of a body kind with fields of its own (bodies.js). */
44
+ const isBodyEntityKind = (entityKindName) => entityKindName === "body" || (typeof entityKindName === "string" && entityKindName.startsWith("body_kind_"));
30
45
  const SET_CHARACTER_KEYS = ["positionM", "velocityMPerSec", "facingYawRad", "collisionLayerName", "characterSizeName", "own"];
31
46
  const ADD_CHARACTER_KEYS = ["positionM", "characterSizeName"];
32
47
  // 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
@@ -72,7 +87,14 @@ const CHARACTER_BASE_FIELDS = [
72
87
  // Which size it is: 0 for the world's own character's, then the world's characterSizes in order.
73
88
  { name: "sizeNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: MAXIMUM_CHARACTER_SIZE_COUNT },
74
89
  ];
75
- const JOINT_FIELDS = [{ name: "isEnabled", valueKind: "boolean", defaultValue: true }];
90
+ // Whether it holds, whether it let go by breaking, and what its motor holds or goes to (0 for a joint without one).
91
+ const JOINT_FIELDS = [
92
+ { name: "isEnabled", valueKind: "boolean", defaultValue: true },
93
+ { name: "isBroken", valueKind: "boolean" },
94
+ { name: "motorTargetNumber", valueKind: "number", minimumNumber: -MAXIMUM_MOTOR_TARGET_NUMBER, maximumNumber: MAXIMUM_MOTOR_TARGET_NUMBER, stepSizeNumber: 0.001 },
95
+ ];
96
+ /** A joint's fields as it starts: holding, whole, its motor at its declared target. */
97
+ const startJointFields = (declaration) => ({ isEnabled: true, isBroken: false, motorTargetNumber: declaration.motor?.targetNumber ?? 0 });
76
98
  // The same grain as the engine takes it, so a step leaves every awake body on the wire's steps (and reading it back
77
99
  // from the wire changes nothing): each number field's range, step and count of steps, counted as the core's shape
78
100
  // counts them, and how many steps each part of the rotation has.
@@ -111,7 +133,7 @@ function pointOrRefuse(given, what, fix) {
111
133
  * Everything one world needs that's the same wherever it's opened: the world, its character kind, the fields each
112
134
  * thing shares, and which settings every side steps by.
113
135
  */
114
- function worldPlan(world, kind) {
136
+ function worldPlan(world, kind, bodyBehaviors = null) {
115
137
  const kindSyncedNames = kind.syncedSettingNames ?? [];
116
138
  const baseStated = new Map(openSettings(statement).list().map((stated) => [stated.name, stated]));
117
139
  const kindStated = kind.settingsStatement ? new Map(openSettings(kind.settingsStatement).list().map((stated) => [stated.name, stated])) : new Map();
@@ -119,7 +141,23 @@ function worldPlan(world, kind) {
119
141
  const defaultRules = Object.fromEntries(rulesFields.map((field) => [field.name, field.defaultValue]));
120
142
  // A field the kind keeps locally (isShared: false) is worked out by each step and never goes on the wire.
121
143
  const characterFields = characterFieldsOf(kind);
122
- return { world, kind, kindSyncedNames, rulesFields, ruleNames: rulesFields.map((field) => field.name), defaultRules, characterFields };
144
+ // The body kinds with fields of their own are each a kind of thing of their own on the wire.
145
+ const ownFieldBehaviors = (bodyBehaviors ?? []).filter((behavior) => behavior?.stateFields.length);
146
+ return {
147
+ world,
148
+ kind,
149
+ kindSyncedNames,
150
+ rulesFields,
151
+ ruleNames: rulesFields.map((field) => field.name),
152
+ defaultRules,
153
+ characterFields,
154
+ bodyBehaviors,
155
+ ownFieldBehaviors,
156
+ bodyEntityKindNames: ["body", ...ownFieldBehaviors.map((behavior) => behavior.entityKindName)],
157
+ /** Which kind of thing a body of one of the world's body kinds is on the wire, and its kind's own fields as they start. */
158
+ bodyEntityKindNameOf: (bodyKindNumber) => bodyBehaviors?.[bodyKindNumber]?.entityKindName ?? "body",
159
+ startOwnOf: (bodyKindNumber) => bodyBehaviors?.[bodyKindNumber]?.startOwn() ?? {},
160
+ };
123
161
  }
124
162
 
125
163
  /**
@@ -145,7 +183,7 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
145
183
  isStateOnSteps: true,
146
184
  };
147
185
  const ownRules = () => Object.fromEntries(ruleNames.map((name) => [name, BASE_SYNCED_SETTING_NAMES.includes(name) ? settings.get(name) : kindSettings.get(name)]));
148
- const simulation = createSimulation(physicsEngine(), world, { tickDurationSec, characterKind: kind, tuning: tuningOf({ ...defaultRules, ...ownRules() }), readDataFile, tracksTouches, bodyGrain: BODY_GRAIN });
186
+ const simulation = createSimulation(physicsEngine(), world, { tickDurationSec, characterKind: kind, tuning: tuningOf({ ...defaultRules, ...ownRules() }), readDataFile, tracksTouches, bodyGrain: BODY_GRAIN, bodyBehaviors: plan.bodyBehaviors });
149
187
  /** Where each character started, to put it back when it falls out of the world. */
150
188
  const startOf = new Map();
151
189
  /** The kind of thing each id is: "body", "character", "joint" or "rules". */
@@ -221,9 +259,13 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
221
259
  simulation.setOffTriangleGroups(state.offMaskNumber, state.offSecondMaskNumber ?? 0, state.offThirdMaskNumber ?? 0);
222
260
  return;
223
261
  }
262
+ if (entity.entityKindName === "zone_switches") {
263
+ switchZones(state);
264
+ return;
265
+ }
224
266
  if (entity.entityKindName === "joint") {
225
267
  const declaration = world.joints.find((joint) => joint.id === entity.id) ?? (entity.entityData ? checkJoint({ ...entity.entityData, id: entity.id }, "joint") : null);
226
- if (declaration) pendingJoints.set(entity.id, { declaration, isEnabled: state.isEnabled });
268
+ if (declaration) pendingJoints.set(entity.id, { declaration, fields: { isEnabled: state.isEnabled, isBroken: Boolean(state.isBroken), motorTargetNumber: state.motorTargetNumber ?? declaration.motor?.targetNumber ?? 0 } });
227
269
  retryJoints();
228
270
  return;
229
271
  }
@@ -244,11 +286,12 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
244
286
  const characterIndex = simulation.characterIndexById.get(entityId);
245
287
  if (characterIndex !== undefined) simulation.removeCharacter(characterIndex);
246
288
  startOf.delete(entityId);
247
- } else if (entityKindName === "body") {
289
+ } else if (isBodyEntityKind(entityKindName)) {
248
290
  const bodyIndex = simulation.bodyIndexById.get(entityId);
249
291
  if (bodyIndex !== undefined) simulation.removeBody(bodyIndex);
250
292
  } else if (entityKindName === "joint") {
251
293
  pendingJoints.delete(entityId);
294
+ readJointFields.delete(entityId);
252
295
  simulation.removeJoint(entityId);
253
296
  }
254
297
  },
@@ -264,10 +307,18 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
264
307
  return characterIndex === undefined ? null : simulation.readSteppedCharacter(characterIndex);
265
308
  }
266
309
  if (entityKindName === "triangle_groups") return { offMaskNumber: simulation.offTriangleGroupMaskNumber(0), offSecondMaskNumber: simulation.offTriangleGroupMaskNumber(1), offThirdMaskNumber: simulation.offTriangleGroupMaskNumber(2) };
310
+ if (entityKindName === "zone_switches") return zoneSwitchesOf(world, (zone) => simulation.isZoneEnabled(zone.id));
267
311
  if (entityKindName === "joint") {
268
- const isEnabled = simulation.joints.has(entityId) ? simulation.isJointEnabled(entityId) : pendingJoints.has(entityId) ? pendingJoints.get(entityId).isEnabled : null;
269
- if (isEnabled !== null) readJointEnabled.set(entityId, isEnabled);
270
- return isEnabled === null ? null : { isEnabled };
312
+ // The joint's own object, filled again: the core reads it at once and keeps nothing.
313
+ let fields = readJointFields.get(entityId);
314
+ if (!fields) readJointFields.set(entityId, (fields = { isEnabled: true, isBroken: false, motorTargetNumber: 0 }));
315
+ if (simulation.readJoint(entityId, fields)) return fields;
316
+ const pending = pendingJoints.get(entityId);
317
+ if (!pending) {
318
+ readJointFields.delete(entityId);
319
+ return null;
320
+ }
321
+ return Object.assign(fields, pending.fields);
271
322
  }
272
323
  const bodyIndex = simulation.bodyIndexById.get(entityId);
273
324
  if (bodyIndex === undefined) return null;
@@ -279,6 +330,11 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
279
330
  const bodyIndex = kindOf.get(entityId) === "body" ? simulation.bodyIndexById.get(entityId) : undefined;
280
331
  return bodyIndex !== undefined && simulation.isBodyOnSteps(bodyIndex);
281
332
  },
333
+ /** isOnSteps for a body's motion alone: its kind's own fields may still want rounding. */
334
+ isMotionOnSteps(entityId) {
335
+ const bodyIndex = isBodyEntityKind(kindOf.get(entityId)) ? simulation.bodyIndexById.get(entityId) : undefined;
336
+ return bodyIndex !== undefined && simulation.isBodyMotionOnSteps(bodyIndex);
337
+ },
282
338
  write(entityId, state, writeInfo) {
283
339
  const entityKindName = kindOf.get(entityId);
284
340
  if (entityKindName === "rules") {
@@ -288,9 +344,11 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
288
344
  if (characterIndex !== undefined) simulation.writeCharacter(characterIndex, state, writeInfo.isResting);
289
345
  } else if (entityKindName === "triangle_groups") {
290
346
  simulation.setOffTriangleGroups(state.offMaskNumber, state.offSecondMaskNumber ?? 0, state.offThirdMaskNumber ?? 0);
347
+ } else if (entityKindName === "zone_switches") {
348
+ switchZones(state);
291
349
  } else if (entityKindName === "joint") {
292
- if (simulation.joints.has(entityId)) simulation.setJointEnabled(entityId, state.isEnabled);
293
- else if (pendingJoints.has(entityId)) pendingJoints.get(entityId).isEnabled = state.isEnabled;
350
+ if (simulation.joints.has(entityId)) simulation.writeJoint(entityId, state);
351
+ else if (pendingJoints.has(entityId)) Object.assign(pendingJoints.get(entityId).fields, { isEnabled: state.isEnabled, isBroken: Boolean(state.isBroken), motorTargetNumber: state.motorTargetNumber ?? 0 });
294
352
  } else {
295
353
  const bodyIndex = simulation.bodyIndexById.get(entityId);
296
354
  if (bodyIndex !== undefined) simulation.writeBody(bodyIndex, state, writeInfo.isResting);
@@ -302,7 +360,7 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
302
360
  * stays with that character, run ahead.
303
361
  */
304
362
  drawnWith(entityId) {
305
- if (kindOf.get(entityId) !== "body") return null;
363
+ if (!isBodyEntityKind(kindOf.get(entityId))) return null;
306
364
  const bodyIndex = simulation.bodyIndexById.get(entityId);
307
365
  if (bodyIndex === undefined) return null;
308
366
  const kindAnswer = kind.drawnWith?.(bodyIndex, opened.ownCharacterId, simulation.stepTools);
@@ -325,9 +383,13 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
325
383
  // The rules are read every step: a change of them is the word's to say at once.
326
384
  if (entityKindName === "rules") return false;
327
385
  // Groups change only when the game switches one, which the core already knows.
328
- if (entityKindName === "triangle_groups") return true;
329
- // A joint rests until a step ties or lets it go (setJoint from a character kind's step).
330
- if (entityKindName === "joint") return !simulation.joints.has(entityId) || readJointEnabled.get(entityId) === simulation.isJointEnabled(entityId);
386
+ if (entityKindName === "triangle_groups" || entityKindName === "zone_switches") return true;
387
+ // A joint rests until a step ties it, lets it go, breaks it or gives its motor another target.
388
+ if (entityKindName === "joint") {
389
+ const read = readJointFields.get(entityId);
390
+ const now = simulation.readJoint(entityId, jointNow);
391
+ return !now || (read !== undefined && read.isEnabled === now.isEnabled && read.isBroken === now.isBroken && read.motorTargetNumber === now.motorTargetNumber);
392
+ }
331
393
  if (entityKindName === "character") {
332
394
  const characterIndex = simulation.characterIndexById.get(entityId);
333
395
  return characterIndex !== undefined && simulation.isCharacterResting(characterIndex);
@@ -341,9 +403,12 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
341
403
  simulation.step({ tickIndex, timetableTickIndex, isReplay, isInCharge, inputOf, emit: emit ?? (() => {}), roomState: opened.roomState, ask, tell });
342
404
  const hits = simulation.takeHits();
343
405
  // A step run again already happened: no sound, no hook, twice.
406
+ if (!isReplay && simulation.jointBreakChangeCount() !== seenJointBreakChangeCount) tellBrokenJoints();
407
+ if (!isReplay && world.zones.length) for (const change of simulation.takeZoneChanges()) tell(change.isEntered ? "zoneEntered" : "zoneLeft", { zoneId: change.zoneId, bodyId: change.bodyId, characterId: change.characterId });
344
408
  if (!isReplay) {
345
409
  for (const hit of hits) {
346
- 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 });
410
+ simulation.describeHit(hit);
411
+ 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, positionM: hit.positionM, surfaceName: hit.surfaceName, otherSurfaceName: hit.otherSurfaceName, massKg: hit.massKg });
347
412
  }
348
413
  }
349
414
  if (!isInCharge) return;
@@ -367,16 +432,35 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
367
432
  simulation.dispose();
368
433
  },
369
434
  });
435
+ /** Switches every zone as the switches' fields say. */
436
+ function switchZones(state) {
437
+ for (const [zoneIndex, zone] of world.zones.entries()) simulation.setZoneEnabled(zone.id, !isZoneOffIn(state, zoneIndex));
438
+ }
370
439
  /** Joints whose ends aren't here yet (a character that hasn't arrived): made as soon as they are. */
371
440
  const pendingJoints = new Map();
372
- /** Whether each joint held when it was last read: one that changed since doesn't rest. */
373
- const readJointEnabled = new Map();
441
+ /** Each joint's fields as they were last read: one that changed since doesn't rest. */
442
+ const readJointFields = new Map();
443
+ const jointNow = { isEnabled: true, isBroken: false, motorTargetNumber: 0 };
374
444
  function retryJoints() {
375
445
  for (const [jointId, pending] of pendingJoints) {
376
- if (simulation.addJoint(pending.declaration, pending.isEnabled)) pendingJoints.delete(jointId);
446
+ if (!simulation.addJoint(pending.declaration, pending.fields.isEnabled)) continue;
447
+ simulation.writeJoint(jointId, pending.fields);
448
+ pendingJoints.delete(jointId);
377
449
  }
378
450
  }
379
- for (const body of world.bodies) if (body.motionKind !== "fixed") kindOf.set(body.id, "body");
451
+ /** The joints told to have broken: a step run again tells nothing twice, and one mended and broken again is told again. */
452
+ const toldBrokenJointIds = new Set();
453
+ let seenJointBreakChangeCount = 0;
454
+ function tellBrokenJoints() {
455
+ seenJointBreakChangeCount = simulation.jointBreakChangeCount();
456
+ for (const jointId of toldBrokenJointIds) if (!simulation.joints.get(jointId)?.isBroken) toldBrokenJointIds.delete(jointId);
457
+ for (const [jointId, joint] of simulation.joints) {
458
+ if (!joint.isBroken || toldBrokenJointIds.has(jointId)) continue;
459
+ toldBrokenJointIds.add(jointId);
460
+ tell("jointBroke", { jointId, bodyId: joint.declaration.bodyId, otherBodyId: joint.declaration.otherBodyId });
461
+ }
462
+ }
463
+ for (const body of world.bodies) if (body.motionKind !== "fixed") kindOf.set(body.id, plan.bodyEntityKindNameOf(body.bodyKindNumber));
380
464
  return opened;
381
465
  }
382
466
 
@@ -388,18 +472,21 @@ function worldFields(plan) {
388
472
  // A character first: a thing added with no kind named is one.
389
473
  character: { stateFields: plan.characterFields, hasInput: true },
390
474
  body: { stateFields: BODY_FIELDS },
475
+ ...Object.fromEntries(plan.ownFieldBehaviors.map((behavior) => [behavior.entityKindName, { stateFields: [...BODY_FIELDS, ...behavior.stateFields] }])),
391
476
  joint: { stateFields: JOINT_FIELDS },
392
477
  rules: { stateFields: plan.rulesFields },
393
478
  ...(hasTriangleGroups(world) ? { triangle_groups: { stateFields: TRIANGLE_GROUP_FIELDS } } : {}),
479
+ ...(world.zones.length ? { zone_switches: { stateFields: zoneMaskFieldsOf(world) } } : {}),
394
480
  },
395
481
  inputFields: plan.kind.inputFields,
396
482
  // The bodies that move, the joints, and the rules as the pieces have them: the same in every game, so nothing of
397
483
  // them is sent until it changes.
398
484
  entities: [
399
485
  { id: RULES_ID, entityKindName: "rules", state: { ...plan.defaultRules } },
400
- ...world.bodies.flatMap((body, bodyIndex) => (body.motionKind !== "fixed" ? [{ id: body.id, entityKindName: "body", state: declaredBodyFields(body, bodyIndex, body.bodyKindNumber, world) }] : [])),
401
- ...world.joints.map((joint) => ({ id: joint.id, entityKindName: "joint", state: { isEnabled: true } })),
486
+ ...world.bodies.flatMap((body, bodyIndex) => (body.motionKind !== "fixed" ? [{ id: body.id, entityKindName: plan.bodyEntityKindNameOf(body.bodyKindNumber), state: { ...declaredBodyFields(body, bodyIndex, body.bodyKindNumber, world), ...plan.startOwnOf(body.bodyKindNumber) } }] : [])),
487
+ ...world.joints.map((joint) => ({ id: joint.id, entityKindName: "joint", state: startJointFields(joint) })),
402
488
  ...(hasTriangleGroups(world) ? [{ id: TRIANGLE_GROUPS_ID, entityKindName: "triangle_groups", state: { ...NO_TRIANGLE_GROUPS_OFF } }] : []),
489
+ ...(world.zones.length ? [{ id: ZONE_SWITCHES_ID, entityKindName: "zone_switches", state: zoneSwitchesOf(world, (zone) => zone.isEnabled) }] : []),
403
490
  ],
404
491
  };
405
492
  }
@@ -450,8 +537,8 @@ function checkAddedBody(world, declaration) {
450
537
 
451
538
  /** A size's number on the wire: 0 for the world's own character's (null), then the world's characterSizes in order. */
452
539
  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.`);
540
+ const sizeNumber = characterSizeName === null ? 0 : world.characterSizes.findIndex((characterSize) => characterSize.name === characterSizeName) + 1;
541
+ if (sizeNumber === 0 && characterSizeName !== null) refuse("bad_argument", `characterSizeName is ${JSON.stringify(characterSizeName)}.`, "characterSizeName", `Use one of the world's characterSizes (${world.characterSizes.map((characterSize) => characterSize.name).join(", ") || "it names none"}), or null for the world's own character.`);
455
542
  return sizeNumber;
456
543
  };
457
544
  const layerNumberOf = (world, layerName, what) => {
@@ -461,7 +548,7 @@ const layerNumberOf = (world, layerName, what) => {
461
548
  };
462
549
 
463
550
  /** What setBody was given, as the body's fields. */
464
- function bodyChanges(world, changes) {
551
+ function bodyChanges(world, changes, behavior = null) {
465
552
  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(", ")}.`);
466
553
  const fields = {};
467
554
  const { positionM, rotationDeg, velocityMPerSec, spinRadPerSec, motionKind, collisionLayerName } = changes ?? {};
@@ -479,6 +566,14 @@ function bodyChanges(world, changes) {
479
566
  // On the wire's grain, so every side weighs it the same.
480
567
  fields.massKg = Math.round(changes.massKg * 100) / 100;
481
568
  }
569
+ if (changes?.own !== undefined) {
570
+ const names = behavior?.fieldNames ?? [];
571
+ if (changes.own === null || typeof changes.own !== "object") refuse("bad_argument", "own isn't an object of the body kind's fields.", "own", `Give some of: ${names.join(", ") || "(this body's kind has none)"}.`);
572
+ for (const [name, ownValue] of Object.entries(changes.own)) {
573
+ if (!names.includes(name)) refuse("bad_argument", `The body's kind has no field "${name}".`, `own.${name}`, `Its fields: ${names.join(", ") || "none"}.`);
574
+ fields[name] = ownValue;
575
+ }
576
+ }
482
577
  return fields;
483
578
  }
484
579
 
@@ -497,6 +592,8 @@ function bodyStateOf(simulation, bodyId) {
497
592
  collisionLayerName: simulation.world.collisionLayers[body.layerIndex].name,
498
593
  massKg: body.massKg ?? null,
499
594
  isResting: simulation.isBodyResting(bodyIndex),
595
+ bodyKindName: body.bodyKindName,
596
+ own: body.own ? { ...body.own } : null,
500
597
  riderCharacterIds: simulation.characters.filter((character) => character?.rideBodyIndex === bodyIndex).map((character) => character.id),
501
598
  };
502
599
  }
@@ -554,26 +651,48 @@ const ownOf = (plan, fields, simulation = null, characterId = null) => {
554
651
  /** What each query takes, beside collisionLayerNames and excludedId (and, for a shape, isStoppedAtPenetration, rotation and marginM). */
555
652
  const QUERY_KEYS = {
556
653
  castRay: ["fromM", "directionM", "maximumDistanceM"],
654
+ castRayAll: ["fromM", "directionM", "maximumDistanceM"],
557
655
  castBall: ["fromM", "radiusM", "directionM", "maximumDistanceM"],
558
656
  castCapsule: ["fromM", "radiusM", "heightM", "directionM", "maximumDistanceM"],
657
+ castBox: ["fromM", "sizeM", "directionM", "maximumDistanceM"],
559
658
  overlapCapsule: ["centerM", "radiusM", "heightM"],
560
659
  overlapBall: ["centerM", "radiusM"],
660
+ overlapBox: ["centerM", "sizeM"],
561
661
  };
562
662
  const SHAPE_QUERY_KEYS = ["isStoppedAtPenetration", "rotation", "marginM"];
563
663
  const OVERLAP_QUERY_KEYS = [...SHAPE_QUERY_KEYS, "isEachTriangle", "isOneSided"];
664
+ /** What each query may take beside what it needs, collisionLayerNames and excludedId. */
665
+ const QUERY_OPTION_KEYS = {
666
+ castRay: [],
667
+ castRayAll: ["maximumHitCount"],
668
+ castBall: SHAPE_QUERY_KEYS,
669
+ castCapsule: SHAPE_QUERY_KEYS,
670
+ castBox: ["isStoppedAtPenetration", "rotation"],
671
+ overlapCapsule: OVERLAP_QUERY_KEYS,
672
+ overlapBall: [],
673
+ overlapBox: ["rotation"],
674
+ };
675
+ /** The most hits castRayAll answers, and the most rays castRays takes in one call. */
676
+ const MAXIMUM_RAY_HIT_COUNT = 256;
677
+ const MAXIMUM_RAY_COUNT = 65536;
678
+ const ZONES_AT_KEYS = ["centerM", "radiusM", "heightM", "rotation"];
679
+ const RAYS_KEYS = ["rays", "rayCount", "maximumDistanceM", "collisionLayerNames", "excludedId"];
564
680
 
565
681
  /**
566
682
  * A query's request, checked: the points and lengths a ray, a ball's sweep or an overlap takes. The request itself
567
683
  * goes on to the search, and checking it makes nothing: a game asks thousands a second.
568
684
  */
569
- function checkQuery(given, what, isShape = false) {
685
+ function checkQuery(given, what) {
570
686
  const keys = QUERY_KEYS[what];
687
+ const optionKeys = QUERY_OPTION_KEYS[what];
571
688
  if (given === null || typeof given !== "object") refuse("bad_argument", `${what} takes an object.`, what, `Give { ${keys.join(", ")} }.`);
572
- 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.`);
689
+ for (const key in given) if (!keys.includes(key) && key !== "collisionLayerNames" && key !== "excludedId" && !optionKeys.includes(key)) refuse("unknown_argument", `${what} has no "${key}".`, key, `It takes: ${[...keys, ...optionKeys].join(", ")}, collisionLayerNames, excludedId.`);
573
690
  for (let keyIndex = 0; keyIndex < keys.length; keyIndex += 1) {
574
691
  const key = keys[keyIndex];
575
692
  const givenValue = given[key];
576
- if (typeof givenValue === "object" && key.endsWith("M")) pointOrRefuse(givenValue, key, "Give three numbers: x, y and z, in metres.");
693
+ if (key === "sizeM") {
694
+ if (!givenValue || !(givenValue.x > 0) || !(givenValue.y > 0) || !(givenValue.z > 0) || !Number.isFinite(givenValue.x + givenValue.y + givenValue.z)) refuse("bad_argument", `sizeM is ${JSON.stringify(givenValue)}.`, "sizeM", "Give how wide (x), tall (y) and deep (z) the box is, each above 0, in metres.");
695
+ } else if (typeof givenValue === "object" && key.endsWith("M")) pointOrRefuse(givenValue, key, "Give three numbers: x, y and z, in metres.");
577
696
  else if (!Number.isFinite(givenValue) || givenValue < 0) refuse("bad_argument", `${key} is ${JSON.stringify(givenValue)}.`, key, "Give a length in metres from 0.");
578
697
  }
579
698
  return given;
@@ -581,7 +700,7 @@ function checkQuery(given, what, isShape = false) {
581
700
 
582
701
  /** A shape's query, checked: its points and lengths, and the isStoppedAtPenetration, rotation and marginM a shape's cast and overlap take beside them. */
583
702
  function shapeQueryOf(request, what) {
584
- const { isStoppedAtPenetration, rotation, marginM } = checkQuery(request, what, true);
703
+ const { isStoppedAtPenetration, rotation, marginM } = checkQuery(request, what);
585
704
  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.");
586
705
  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.");
587
706
  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.");
@@ -613,6 +732,46 @@ function queryCalls(simulationNow) {
613
732
  },
614
733
  /** Everything a ball overlaps: [{ bodyId, characterId }]. */
615
734
  overlapBall: (request) => simulationNow()?.overlapBall(checkQuery(request, "overlapBall")) ?? [],
735
+ /** The ids of the zones a place touches now: a point (centerM alone), a ball (with radiusM) or a capsule (with radiusM and heightM). */
736
+ zonesAt(request) {
737
+ if (request === null || typeof request !== "object") refuse("bad_argument", "zonesAt takes an object.", "zonesAt", "Give { centerM }, with radiusM for a ball and heightM too for a capsule.");
738
+ for (const key in request) if (!ZONES_AT_KEYS.includes(key)) refuse("unknown_argument", `zonesAt has no "${key}".`, key, `It takes: ${ZONES_AT_KEYS.join(", ")}.`);
739
+ pointOrRefuse(request.centerM, "centerM", "Give three numbers: x, y and z, in metres.");
740
+ for (const key of ["radiusM", "heightM"]) if (request[key] !== undefined && !(Number.isFinite(request[key]) && request[key] >= 0)) refuse("bad_argument", `${key} is ${JSON.stringify(request[key])}.`, key, "Give a length in metres from 0, or leave it out.");
741
+ if (request.heightM !== undefined && request.radiusM === undefined) refuse("bad_argument", "zonesAt was given heightM with no radiusM.", "radiusM", "A capsule takes both its radiusM and its heightM (its whole height, round ends included).");
742
+ if (request.rotation !== undefined && !(request.rotation && Number.isFinite(request.rotation.x + request.rotation.y + request.rotation.z + request.rotation.w))) refuse("bad_argument", "rotation isn't { x, y, z, w }.", "rotation", "Give the capsule's turn as a quaternion, or leave it out for standing up.");
743
+ return simulationNow()?.zonesAt(request) ?? [];
744
+ },
745
+ /** Everything a box (turned by rotation) overlaps: [{ bodyId, characterId }]. */
746
+ overlapBox: (request) => simulationNow()?.overlapBox(shapeQueryOf(request, "overlapBox")) ?? [],
747
+ /** The first thing a box (turned by rotation) meets moving along a direction, or null. */
748
+ castBox: (request, into) => simulationNow()?.castBox(shapeQueryOf(request, "castBox"), checkInto(into)) ?? null,
749
+ /** Everything a ray passes through, nearest first, one hit a shape: a list of hits as castRay's, up to maximumHitCount (default 16). */
750
+ castRayAll(request, into) {
751
+ 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 hits into (kept and given again), or leave it out for a new one.");
752
+ const { maximumHitCount } = checkQuery(request, "castRayAll");
753
+ if (maximumHitCount !== undefined && !(Number.isInteger(maximumHitCount) && maximumHitCount >= 1 && maximumHitCount <= MAXIMUM_RAY_HIT_COUNT)) refuse("bad_argument", `maximumHitCount is ${JSON.stringify(maximumHitCount)}.`, "maximumHitCount", `Give how many hits to answer at most, 1 to ${MAXIMUM_RAY_HIT_COUNT}, or leave it out for 16.`);
754
+ const simulation = simulationNow();
755
+ if (simulation) return simulation.castRayAll(request, into ?? null);
756
+ if (into) into.length = 0;
757
+ return into ?? [];
758
+ },
759
+ /** Many rays in one call: { rays (six numbers a ray: its start, then its direction), maximumDistanceM }. Answers { rayCount, hitCount, distancesM, normals, hitAt(rayIndex, into) }; with into, written there. */
760
+ castRays(request, into) {
761
+ if (request === null || typeof request !== "object") refuse("bad_argument", "castRays takes an object.", "castRays", "Give { rays, maximumDistanceM }.");
762
+ for (const key in request) if (!RAYS_KEYS.includes(key)) refuse("unknown_argument", `castRays has no "${key}".`, key, `It takes: ${RAYS_KEYS.join(", ")}.`);
763
+ const { rays, rayCount = rays instanceof Float32Array ? Math.floor(rays.length / 6) : 0, maximumDistanceM } = request;
764
+ if (!(rays instanceof Float32Array)) refuse("bad_argument", "rays isn't a Float32Array.", "rays", "Give a Float32Array with six numbers a ray: where it starts (x, y, z), then its direction (x, y, z).");
765
+ if (!Number.isInteger(rayCount) || rayCount < 0 || rayCount > MAXIMUM_RAY_COUNT || rayCount * 6 > rays.length) refuse("bad_argument", `rayCount is ${JSON.stringify(rayCount)}.`, "rayCount", `Give how many of rays' rays to cast, up to ${MAXIMUM_RAY_COUNT} and what rays holds, or leave it out for all of them.`);
766
+ if (!Number.isFinite(maximumDistanceM) || maximumDistanceM < 0) refuse("bad_argument", `maximumDistanceM is ${JSON.stringify(maximumDistanceM)}.`, "maximumDistanceM", "Give how far every ray goes at most, in metres from 0.");
767
+ if (into !== undefined && into !== null && (typeof into !== "object" || Array.isArray(into))) refuse("bad_argument", "into isn't an answer of castRays.", "into", "Give what an earlier castRays answered (kept and given again), or leave it out for a new one.");
768
+ const simulation = simulationNow();
769
+ if (simulation) return simulation.castRays(request, into ?? null);
770
+ const answer = into ?? { rayCount: 0, hitCount: 0, distancesM: new Float32Array(0), normals: new Float32Array(0), hitAt: () => null };
771
+ answer.rayCount = 0;
772
+ answer.hitCount = 0;
773
+ return answer;
774
+ },
616
775
  };
617
776
  }
618
777
 
@@ -621,6 +780,10 @@ function queryCalls(simulationNow) {
621
780
  * online core's World gives it (ids, has, entityKindName, state, drawn, add, remove, set, setInput, on, simulation),
622
781
  * and the rest says who this game is in it.
623
782
  */
783
+ function unknownZone(world, zoneId) {
784
+ refuse("unknown_zone", `There's no zone ${JSON.stringify(zoneId)} in this world.`, "zoneId", world.zones.length ? `Give one of the world's zones: ${world.zones.slice(0, 20).map((zone) => zone.id).join(", ")}.` : "Give the world zones in its declaration first, in the game and on its game server.");
785
+ }
786
+
624
787
  function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharge, isReady, hasGameServer, tickNumber }) {
625
788
  const { world, kind } = plan;
626
789
  const listeners = Object.fromEntries(LISTENED_EVENT_NAMES.map((eventName) => [eventName, new Set()]));
@@ -632,17 +795,17 @@ function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharg
632
795
  things.on("added", (id) => {
633
796
  const entityKindName = things.entityKindName(id);
634
797
  kindById.set(id, entityKindName);
635
- if (entityKindName === "body") telling("bodyAdded", id);
798
+ if (isBodyEntityKind(entityKindName)) telling("bodyAdded", id);
636
799
  else if (entityKindName === "character") telling("characterAdded", id);
637
800
  });
638
801
  things.on("removed", (id) => {
639
802
  const entityKindName = kindById.get(id);
640
803
  kindById.delete(id);
641
- if (entityKindName === "body") telling("bodyRemoved", id);
804
+ if (isBodyEntityKind(entityKindName)) telling("bodyRemoved", id);
642
805
  else if (entityKindName === "character") telling("characterRemoved", id);
643
806
  });
644
807
  const simulationNow = () => things.simulation?.simulation ?? null;
645
- const isBody = (bodyId) => things.entityKindName(bodyId) === "body";
808
+ const isBody = (bodyId) => isBodyEntityKind(things.entityKindName(bodyId));
646
809
  const isCharacter = (characterId) => things.entityKindName(characterId) === "character";
647
810
  /** The world's calls where this game runs it; a refusal with a game server, and null where another player's game does. */
648
811
  const inCharge = (what) => {
@@ -661,6 +824,11 @@ function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharg
661
824
  const declaration = isFixedBody(world, bodyId) ? world.bodyById.get(bodyId) : null;
662
825
  return declaration ? { x: declaration.positionM.x, y: declaration.positionM.y, z: declaration.positionM.z, rotation: declaration.rotation } : null;
663
826
  };
827
+ /** A body's kind's own fields as drawn this frame, or null for a kind with none. */
828
+ const ownOfBody = (bodyId, drawn) => {
829
+ const behavior = plan.bodyBehaviors?.[world.bodyById.get(bodyId)?.bodyKindNumber ?? simulationNow()?.bodies[simulationNow().bodyIndexById.get(bodyId)]?.declaration.bodyKindNumber];
830
+ return behavior ? Object.fromEntries(behavior.fieldNames.map((name) => [name, drawn[name] ?? null])) : null;
831
+ };
664
832
  const shared = sharedCalls({ plan, things, simulationNow, inChargeOf: inCharge });
665
833
 
666
834
  const calls = {
@@ -691,7 +859,19 @@ function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharg
691
859
  /** Where to draw a body this frame: { positionM, rotation, steerNumber }. null for a body that isn't here. */
692
860
  drawnBody(bodyId) {
693
861
  const drawn = drawnOf(bodyId);
694
- return drawn ? { positionM: { x: drawn.x, y: drawn.y, z: drawn.z }, rotation: { ...drawn.rotation }, steerNumber: drawn.steerNumber ?? 0, wheels: simulationNow()?.wheelStates(bodyId) ?? [] } : null;
862
+ return drawn ? { positionM: { x: drawn.x, y: drawn.y, z: drawn.z }, rotation: { ...drawn.rotation }, steerNumber: drawn.steerNumber ?? 0, wheels: simulationNow()?.wheelStates(bodyId) ?? [], own: ownOfBody(bodyId, drawn) } : null;
863
+ },
864
+ /**
865
+ * What a moving body slides or rolls along right now, as this game's world has it: { otherBodyId,
866
+ * otherCharacterId, positionM, surfaceName, otherSurfaceName, slideSpeedMPerSec, rollSpeedMPerSec }, or null
867
+ * when it rests, touches nothing or isn't a moving body. For the sound and the dust of a thing dragged or rolling.
868
+ */
869
+ bodyTouch(bodyId) {
870
+ const simulation = simulationNow();
871
+ const bodyIndex = simulation?.bodyIndexById.get(bodyId);
872
+ const touch = bodyIndex === undefined ? null : simulation.bodyTouch(bodyIndex);
873
+ if (!touch) return null;
874
+ return { otherBodyId: touch.otherBodyIndex >= 0 ? (simulation.bodies[touch.otherBodyIndex]?.declaration.id ?? null) : null, otherCharacterId: touch.otherCharacterIndex >= 0 ? (simulation.characters[touch.otherCharacterIndex]?.id ?? null) : null, positionM: touch.positionM, surfaceName: touch.surfaceName, otherSurfaceName: touch.otherSurfaceName, slideSpeedMPerSec: touch.slideSpeedMPerSec, rollSpeedMPerSec: touch.rollSpeedMPerSec };
695
875
  },
696
876
  /** Puts a three.js object (anything with position.set and quaternion.set) where a body is drawn this frame. */
697
877
  applyTo(object3d, bodyId) {
@@ -737,13 +917,14 @@ function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharg
737
917
  */
738
918
  function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
739
919
  const { world, kind } = plan;
740
- const isBody = (bodyId) => things.entityKindName(bodyId) === "body";
920
+ const isBody = (bodyId) => isBodyEntityKind(things.entityKindName(bodyId));
741
921
  const isCharacter = (characterId) => things.entityKindName(characterId) === "character";
742
922
  const isJoint = (jointId) => things.entityKindName(jointId) === "joint";
743
923
  // Every thing in play, declared ones included: an id freed by a removal may be used again, even in the same step.
744
924
  const ids = () => new Set(things.ids());
925
+ const movingBodyIds = () => (plan.bodyEntityKindNames.length === 1 ? things.ids("body") : plan.bodyEntityKindNames.flatMap((entityKindName) => things.ids(entityKindName)));
745
926
  return {
746
- bodyIds: () => [...world.fixedBodyIds, ...things.ids("body")],
927
+ bodyIds: () => [...world.fixedBodyIds, ...movingBodyIds()],
747
928
  hasBody: (bodyId) => isBody(bodyId) || isFixedBody(world, bodyId),
748
929
  /** A body as this world has it now. */
749
930
  bodyState: (bodyId) => bodyStateOf(simulationNow(), bodyId),
@@ -752,17 +933,18 @@ function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
752
933
  const running = inChargeOf("bodies are added");
753
934
  const checked = checkAddedBody(world, declaration);
754
935
  if (!running || ids().has(checked.id)) return false;
755
- 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.");
756
- return Boolean(running.add(checked.id, { entityKindName: "body", state: { ...declaredBodyFields(checked, things.simulation.freeBodyNumber(), checked.bodyKindNumber, world), motionNumber: MOTION_KINDS.indexOf(checked.startMotionKind) } }));
936
+ if (movingBodyIds().length >= MAXIMUM_BODY_COUNT) refuse("too_many_bodies", `A world holds at most ${MAXIMUM_BODY_COUNT} bodies.`, "body", "Remove bodies nobody needs.");
937
+ return Boolean(running.add(checked.id, { entityKindName: plan.bodyEntityKindNameOf(checked.bodyKindNumber), state: { ...declaredBodyFields(checked, things.simulation.freeBodyNumber(), checked.bodyKindNumber, world), ...plan.startOwnOf(checked.bodyKindNumber), motionNumber: MOTION_KINDS.indexOf(checked.startMotionKind) } }));
757
938
  },
758
939
  removeBody: (bodyId) => Boolean(inChargeOf("bodies are removed") && isBody(bodyId) && things.remove(bodyId)),
759
940
  /** Sets a body's place, rotation, speed or spin at once (a teleport), how it moves (motionKind), or its collision layer. */
760
941
  setBody(bodyId, changes) {
761
942
  const running = inChargeOf("bodies are set");
762
- const fields = bodyChanges(world, changes);
943
+ const behavior = plan.bodyBehaviors?.[simulationNow()?.bodies[simulationNow().bodyIndexById.get(bodyId)]?.declaration.bodyKindNumber] ?? null;
944
+ const fields = bodyChanges(world, changes, behavior);
763
945
  if (!isBody(bodyId)) return world.bodyById.has(bodyId) ? false : unknownBody(bodyId);
764
946
  const isMoved = ["x", "y", "z", "rotation"].some((name) => name in fields);
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.");
947
+ if (world.bodyById.get(bodyId)?.timetable && Object.keys(fields).some((name) => name !== "layerNumber" && !behavior?.fieldNames.includes(name))) 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.");
766
948
  return Boolean(running && running.set(bodyId, fields, { isTeleport: isMoved }));
767
949
  },
768
950
  pushBody(bodyId, pushMPerSec) {
@@ -836,18 +1018,30 @@ function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
836
1018
  if (!running || ids().has(checked.id)) return false;
837
1019
  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.");
838
1020
  const { id, ...entityData } = declaration;
839
- return Boolean(running.add(checked.id, { entityKindName: "joint", state: { isEnabled: true }, entityData }));
1021
+ return Boolean(running.add(checked.id, { entityKindName: "joint", state: startJointFields(checked), entityData }));
840
1022
  },
841
1023
  removeJoint: (jointId) => Boolean(inChargeOf("joints are removed") && isJoint(jointId) && things.remove(jointId)),
842
- /** Lets a joint go, or holds again (a cart's handles let go and taken). */
1024
+ /** Lets a joint go or holds again (a cart's handles let go and taken; a broken one mended), or gives its motor another target (a door told to close, a winch to turn). */
843
1025
  setJoint(jointId, changes) {
844
1026
  const running = inChargeOf("joints are set");
845
- for (const key of Object.keys(changes ?? {})) if (key !== "isEnabled") refuse("unknown_argument", `setJoint has no "${key}".`, key, "It takes: isEnabled.");
846
- if (typeof changes?.isEnabled !== "boolean") refuse("bad_argument", "setJoint takes { isEnabled }.", "isEnabled", "Give true to hold, false to let go.");
1027
+ for (const key of Object.keys(changes ?? {})) if (key !== "isEnabled" && key !== "motorTargetNumber") refuse("unknown_argument", `setJoint has no "${key}".`, key, "It takes: isEnabled, motorTargetNumber.");
1028
+ const { isEnabled, motorTargetNumber } = changes ?? {};
1029
+ if (isEnabled === undefined && motorTargetNumber === undefined) refuse("bad_argument", "setJoint takes { isEnabled, motorTargetNumber }, either or both.", "changes", "Give isEnabled true to hold or false to let go, or motorTargetNumber for its motor.");
1030
+ if (isEnabled !== undefined && typeof isEnabled !== "boolean") refuse("bad_argument", `isEnabled is ${JSON.stringify(isEnabled)}.`, "isEnabled", "Give true to hold, false to let go.");
847
1031
  if (!isJoint(jointId)) refuse("unknown_joint", `There's no joint ${JSON.stringify(jointId)} here.`, "jointId", "Give the id of a joint in jointIds().");
848
- return Boolean(running && running.set(jointId, { isEnabled: changes.isEnabled }, { isTeleport: false }));
1032
+ if (motorTargetNumber !== undefined) {
1033
+ if (!Number.isFinite(motorTargetNumber) || Math.abs(motorTargetNumber) > MAXIMUM_MOTOR_TARGET_NUMBER) refuse("bad_argument", `motorTargetNumber is ${JSON.stringify(motorTargetNumber)}.`, "motorTargetNumber", `Give a number from -${MAXIMUM_MOTOR_TARGET_NUMBER} to ${MAXIMUM_MOTOR_TARGET_NUMBER}: radians (a second) about a hinge, metres (a second) along a slider.`);
1034
+ if (simulationNow() && !simulationNow().joints.get(jointId)?.declaration.motor) refuse("bad_argument", `The joint ${JSON.stringify(jointId)} has no motor.`, "motorTargetNumber", 'Declare the joint with motor: { motorKind: "speed" } or { motorKind: "position" } (a hinge or a slider), in the game and on its game server.');
1035
+ }
1036
+ // Held again, it's whole again.
1037
+ return Boolean(running && running.set(jointId, { ...(isEnabled === undefined ? {} : { isEnabled, ...(isEnabled ? { isBroken: false } : {}) }), ...(motorTargetNumber === undefined ? {} : { motorTargetNumber }) }, { isTeleport: false }));
849
1038
  },
850
1039
  isJointEnabled: (jointId) => (isJoint(jointId) ? Boolean(things.state(jointId)?.isEnabled) : false),
1040
+ /** A joint as the world has it now: { isEnabled, isBroken, motorTargetNumber }, or null. */
1041
+ jointState(jointId) {
1042
+ const fields = isJoint(jointId) ? things.state(jointId) : null;
1043
+ return fields ? { isEnabled: Boolean(fields.isEnabled), isBroken: Boolean(fields.isBroken), motorTargetNumber: fields.motorTargetNumber ?? 0 } : null;
1044
+ },
851
1045
  /** Switches one of the world's triangle groups on or off for everyone (a door that opens, a bridge that falls), 1 to 63. */
852
1046
  setTriangleGroup(groupNumber, isEnabled) {
853
1047
  const running = inChargeOf("triangle groups are switched");
@@ -859,6 +1053,28 @@ function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
859
1053
  const bitNumber = triangleGroupBitNumberOf(groupNumber);
860
1054
  return Boolean(running && running.set(TRIANGLE_GROUPS_ID, { [maskName]: isEnabled ? maskNumber & ~bitNumber : maskNumber | bitNumber }, { isTeleport: false }));
861
1055
  },
1056
+ zoneIds: () => world.zones.map((zone) => zone.id),
1057
+ /** Who's in a zone, as of the last step: [{ bodyId, characterId }]. */
1058
+ zoneOccupants(zoneId) {
1059
+ if (!world.zones.some((zone) => zone.id === zoneId)) unknownZone(world, zoneId);
1060
+ return simulationNow()?.zoneOccupants(zoneId) ?? [];
1061
+ },
1062
+ /** Switches a zone on or off for everyone (a fan that starts, a capture point that opens): off, nobody is in it and it does nothing. */
1063
+ setZone(zoneId, changes) {
1064
+ const running = inChargeOf("zones are switched");
1065
+ for (const key of Object.keys(changes ?? {})) if (key !== "isEnabled") refuse("unknown_argument", `setZone has no "${key}".`, key, "It takes: isEnabled.");
1066
+ if (typeof changes?.isEnabled !== "boolean") refuse("bad_argument", "setZone takes { isEnabled }.", "isEnabled", "Give true to switch the zone on, false to switch it off.");
1067
+ const zoneIndex = world.zones.findIndex((zone) => zone.id === zoneId);
1068
+ if (zoneIndex < 0) unknownZone(world, zoneId);
1069
+ const maskName = zoneMaskNameOf(Math.floor(zoneIndex / ZONE_MASK_BIT_COUNT));
1070
+ const maskNumber = things.state(ZONE_SWITCHES_ID)?.[maskName] ?? 0;
1071
+ const bitNumber = 1 << (zoneIndex % ZONE_MASK_BIT_COUNT);
1072
+ return Boolean(running && running.set(ZONE_SWITCHES_ID, { [maskName]: changes.isEnabled ? maskNumber & ~bitNumber : maskNumber | bitNumber }, { isTeleport: false }));
1073
+ },
1074
+ isZoneEnabled(zoneId) {
1075
+ const zoneIndex = world.zones.findIndex((zone) => zone.id === zoneId);
1076
+ return zoneIndex >= 0 && !isZoneOffIn(things.state(ZONE_SWITCHES_ID), zoneIndex);
1077
+ },
862
1078
  /** Whether a triangle group is there now. */
863
1079
  isTriangleGroupEnabled: (groupNumber) => !((things.state(TRIANGLE_GROUPS_ID)?.[TRIANGLE_GROUP_MASK_NAMES[triangleGroupMaskIndexOf(groupNumber)]] ?? 0) & triangleGroupBitNumberOf(groupNumber)),
864
1080
  };
@@ -873,10 +1089,10 @@ const kindOf = (characters) => (characters === undefined ? walkingCharacters() :
873
1089
  * createNet(room).use and defineNetServer's kinds.
874
1090
  */
875
1091
  export const physicsKindFrom = (worldKind) => (givenWorld, given = {}) => {
876
- 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.");
1092
+ if (given === null || typeof given !== "object" || Object.keys(given).some((key) => !["settings", "hooks", "characters", "bodies"].includes(key))) refuse("unknown_argument", "physicsKind takes a world, then { settings, hooks, characters, bodies }.", "given", "Give the world first, then an object with settings, hooks, characters (a character kind) and bodies (rules for the world's body kinds), each optional.");
877
1093
  const world = worldOf(givenWorld);
878
1094
  const kind = kindOf(given.characters);
879
- const plan = worldPlan(world, kind);
1095
+ const plan = worldPlan(world, kind, defineBodyBehaviors(given.bodies, world));
880
1096
  const { settings, hooks, ask, tell } = openPiece(statement, { settings: given.settings, hooks: given.hooks });
881
1097
  const nextStart = startStates(world);
882
1098
  const physicsWorldKind = worldKind({
@@ -985,10 +1201,10 @@ function copyMotion(into, read, rest) {
985
1201
  * A world played alone: the same calls over the same simulation, stepped here with no room. update(nowMs) runs the
986
1202
  * fixed steps that are due on the clock it's given.
987
1203
  */
988
- export function alonePhysics(givenWorld, { settings: givenSettings, hooks: givenHooks, ticksPerSec, playerId, characters, defineShape }) {
1204
+ export function alonePhysics(givenWorld, { settings: givenSettings, hooks: givenHooks, ticksPerSec, playerId, characters, bodies, defineShape }) {
989
1205
  const world = worldOf(givenWorld);
990
1206
  const kind = kindOf(characters);
991
- const plan = worldPlan(world, kind);
1207
+ const plan = worldPlan(world, kind, defineBodyBehaviors(bodies, world));
992
1208
  const { settings, hooks, ask, tell } = openPiece(statement, { settings: givenSettings, hooks: givenHooks });
993
1209
  const tickDurationSec = 1 / ticksPerSec;
994
1210
  const opened = openWorld({ plan, settings, kindSettings: kind.settings ?? null, ask, tell, tickDurationSec, isInChargeAtFirst: true });
@@ -1007,6 +1223,8 @@ export function alonePhysics(givenWorld, { settings: givenSettings, hooks: given
1007
1223
  let ranTickCount = 0;
1008
1224
  /** Puts a thing's fields on their steps, as online: the same numbers alone as in a room. */
1009
1225
  const onSteps = (entityKindName, state) => shapes[entityKindName].onSteps(state);
1226
+ /** Each body kind's own fields as a shape of their own, to put them on their steps without the whole body's. */
1227
+ const ownShapes = Object.fromEntries(plan.ownFieldBehaviors.map((behavior) => [behavior.entityKindName, { shape: defineShape(behavior.stateFields, { what: behavior.entityKindName, isPressAllowed: false }), fieldNames: behavior.fieldNames }]));
1010
1228
 
1011
1229
  const things = {
1012
1230
  simulation: opened,
@@ -1077,7 +1295,8 @@ export function alonePhysics(givenWorld, { settings: givenSettings, hooks: given
1077
1295
  const read = opened.read(id);
1078
1296
  if (!read) return;
1079
1297
  let onStepsRead;
1080
- 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) {
1298
+ const ownShape = ownShapes[entity.entityKindName];
1299
+ if ((entity.entityKindName === "body" || ownShape) && entity.onStepsRest && opened.isMotionOnSteps(id) && read.layerNumber === entity.readLayerNumber && read.motionNumber === entity.readMotionNumber && read.steerNumber === entity.readSteerNumber && read.massKg === entity.readMassKg) {
1081
1300
  // The step left it on the wire's steps already: nothing to round and nothing to write back, so a
1082
1301
  // thousand bodies falling leave nothing for the garbage collector. Its fields go into one of two
1083
1302
  // objects of its own, turn about (nothing outside keeps them).
@@ -1087,12 +1306,34 @@ export function alonePhysics(givenWorld, { settings: givenSettings, hooks: given
1087
1306
  }
1088
1307
  onStepsRead = entity.later === entity.ownFirst ? entity.ownSecond : entity.ownFirst;
1089
1308
  copyMotion(onStepsRead, read, entity.onStepsRest);
1309
+ if (ownShape) {
1310
+ // Its kind's own fields go on their steps by their own shape, and back into the body only where that moved one.
1311
+ entity.ownSlots ??= new Int32Array(ownShape.shape.slotCount);
1312
+ ownShape.shape.fromSlots(ownShape.shape.toSlots(read, entity.ownSlots), 0, onStepsRead);
1313
+ for (const name of ownShape.fieldNames) {
1314
+ if (onStepsRead[name] === read[name]) continue;
1315
+ steppedWriteInfo.isResting = isResting;
1316
+ opened.write(id, onStepsRead, steppedWriteInfo);
1317
+ break;
1318
+ }
1319
+ }
1090
1320
  } else {
1091
- onStepsRead = onSteps(entity.entityKindName, read);
1321
+ if (isBodyEntityKind(entity.entityKindName)) {
1322
+ // A body the step left off the wire's steps (one with fields of its own, a vehicle turning) is put on them
1323
+ // through slots of its own, into one of two objects of its own, turn about: nothing for the garbage collector.
1324
+ const shape = shapes[entity.entityKindName];
1325
+ entity.slots ??= new Int32Array(shape.slotCount);
1326
+ shape.toSlots(read, entity.slots);
1327
+ if (!entity.roundFirst) {
1328
+ entity.roundFirst = shape.fromSlots(entity.slots);
1329
+ entity.roundSecond = shape.fromSlots(entity.slots);
1330
+ }
1331
+ onStepsRead = shape.fromSlots(entity.slots, 0, entity.later === entity.roundFirst ? entity.roundSecond : entity.roundFirst);
1332
+ } else onStepsRead = onSteps(entity.entityKindName, read);
1092
1333
  // As online, every place steps on the wire's numbers.
1093
1334
  steppedWriteInfo.isResting = isResting;
1094
1335
  opened.write(id, onStepsRead, steppedWriteInfo);
1095
- if (entity.entityKindName === "body") {
1336
+ if (isBodyEntityKind(entity.entityKindName)) {
1096
1337
  entity.readLayerNumber = read.layerNumber;
1097
1338
  entity.readMotionNumber = read.motionNumber;
1098
1339
  entity.readSteerNumber = read.steerNumber;