@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/README.md +19 -5
- package/batch.js +6 -1
- package/bodies.js +72 -0
- package/characters.js +19 -5
- package/declare.js +110 -8
- package/index.d.ts +220 -39
- package/index.js +2 -2
- package/package.json +2 -1
- package/piece.json +19 -2
- package/piece.json.js +19 -2
- package/rapier/CHANGES.md +2 -0
- package/rapier/rapier.js +298 -6
- package/rapier/rapier.wasm +0 -0
- package/simulation.js +587 -57
- package/sync.js +294 -53
package/simulation.js
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
// whatever was written in since.
|
|
16
16
|
import { MOTION_KINDS, RIDING_LAYER_NAME, refuse, timetablePlaceInto, triangleGroupBitNumberOf, triangleGroupMaskIndexOf } from "./declare.js";
|
|
17
17
|
import { dataOf } from "./data.js";
|
|
18
|
-
import { ANSWER_FLOAT_COUNT, ANSWER_NUMBER_COUNT, BODY_FLOAT_COUNT, BODY_TAG_NUMBER, CHARACTER_TAG_NUMBER, CONTACT_FLOAT_COUNT, CONTACT_NUMBER_COUNT, EACH_TRIANGLE_FLAG_NUMBER, EXCLUDES_BODY_FLAG_NUMBER, NO_TRIANGLE_INDEX, ONE_SIDED_FLAG_NUMBER, SKIPS_CHARACTERS_FLAG_NUMBER, SMALL_TAG_NUMBER, TAG_KIND_MASK_NUMBER, WRITE_MOVING_NUMBER, WRITE_PLACE_ONLY_NUMBER, WRITE_RESTING_NUMBER, createBatch, heldMeshParts, isBigMesh } from "./batch.js";
|
|
18
|
+
import { ANSWER_FLOAT_COUNT, ANSWER_NUMBER_COUNT, RAYS_PER_CALL_COUNT, RAY_HIT_FLOAT_COUNT, BODY_FLOAT_COUNT, BODY_TAG_NUMBER, CHARACTER_TAG_NUMBER, CONTACT_FLOAT_COUNT, CONTACT_NUMBER_COUNT, EACH_TRIANGLE_FLAG_NUMBER, EXCLUDES_BODY_FLAG_NUMBER, NO_TRIANGLE_INDEX, ONE_SIDED_FLAG_NUMBER, SKIPS_CHARACTERS_FLAG_NUMBER, SMALL_TAG_NUMBER, TAG_KIND_MASK_NUMBER, WRITE_MOVING_NUMBER, WRITE_PLACE_ONLY_NUMBER, WRITE_RESTING_NUMBER, createBatch, heldMeshParts, isBigMesh } from "./batch.js";
|
|
19
19
|
|
|
20
20
|
/** A hit slower than this isn't told. */
|
|
21
21
|
const MINIMUM_TOLD_HIT_SPEED_M_PER_SEC = 1.2;
|
|
@@ -31,6 +31,8 @@ const GROUND_KEPT_AGAIN_STEP_COUNT = 30;
|
|
|
31
31
|
const CHARACTER_SKIN_M = 0.02;
|
|
32
32
|
/** How far under a character a body on a timetable still carries it, in metres: its controller's gap and a little more. */
|
|
33
33
|
const RIDE_REACH_M = CHARACTER_SKIN_M + 0.04;
|
|
34
|
+
/** A point asked of the zones is a ball this small. */
|
|
35
|
+
const POINT_RADIUS_M = 0.001;
|
|
34
36
|
const NO_TURN = Object.freeze({ x: 0, y: 0, z: 0, w: 1 });
|
|
35
37
|
|
|
36
38
|
/** An angle in radians, wrapped into -PI up to PI. */
|
|
@@ -79,12 +81,14 @@ const SUSPENSION_FORCE_HEADROOM_NUMBER = 2.5;
|
|
|
79
81
|
* maximumNumber, stepSizeNumber, maximumStepCount }, rotationMaximumStepCount }): with it, the engine leaves every
|
|
80
82
|
* awake body on those steps as a step ends, so every side steps on from the numbers the wire carries.
|
|
81
83
|
*/
|
|
82
|
-
export function createSimulation(engine, world, { tickDurationSec, characterKind, tuning, readDataFile = null, tracksTouches = false, isEachCharacterAlone = false, bodyGrain = null }) {
|
|
84
|
+
export function createSimulation(engine, world, { tickDurationSec, characterKind, tuning, readDataFile = null, tracksTouches = false, isEachCharacterAlone = false, bodyGrain = null, bodyBehaviors = null }) {
|
|
83
85
|
let currentTuning = tuning;
|
|
84
86
|
let stepCount = 0;
|
|
85
87
|
const substepDurationSec = tickDurationSec / world.substepCount;
|
|
86
88
|
const rapierWorld = new engine.World({ x: 0, y: -currentTuning.gravityMPerSecPerSec, z: 0 });
|
|
87
89
|
rapierWorld.timestep = substepDurationSec;
|
|
90
|
+
/** One of the engine solver's own small steps inside a substep: what a joint's impulse is read over. */
|
|
91
|
+
const solverStepDurationSec = substepDurationSec / rapierWorld.integrationParameters.numSolverIterations;
|
|
88
92
|
// The engine's batch calls: a step, a read, a write and a query each cross into the engine once, with plain numbers.
|
|
89
93
|
const batch = createBatch(engine, rapierWorld);
|
|
90
94
|
const { raw } = batch;
|
|
@@ -105,6 +109,12 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
105
109
|
let movableBodyCount = 0;
|
|
106
110
|
/** The bodies that aren't fixed for good, by index: what a step goes through, however many pieces the level is made of. */
|
|
107
111
|
const unfixedBodies = [];
|
|
112
|
+
/** The bodies whose kind has rules of its own (bodies.js), in the order of their indexes. */
|
|
113
|
+
const behavingBodies = [];
|
|
114
|
+
/** The bodies a step's forces push, until that step's end. */
|
|
115
|
+
const forcedBodies = new Set();
|
|
116
|
+
/** Whether the step is before its first engine substep: a force added now pushes through all of them. */
|
|
117
|
+
let isBeforeSubsteps = false;
|
|
108
118
|
let lowestFreeBodyIndex = 0;
|
|
109
119
|
const bodies = [];
|
|
110
120
|
const bodyIndexById = new Map();
|
|
@@ -354,8 +364,14 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
354
364
|
.setAngularDamping(declaration.angularDampingNumber ?? currentTuning.angularDampingNumber);
|
|
355
365
|
const rigidBody = rapierWorld.createRigidBody(description);
|
|
356
366
|
const layerIndex = layerIndexByName.get(declaration.collisionLayerName);
|
|
357
|
-
const
|
|
367
|
+
const behavior = bodyBehaviors?.[declaration.bodyKindNumber] ?? null;
|
|
368
|
+
const body = { index, id: declaration.id, bodyKindName: behavior?.bodyKindName ?? world.bodyKinds[declaration.bodyKindNumber - 1]?.name ?? null, declaration, rigidBody, colliders: [], motionIndex, declaredMotionIndex: motionIndex, layerIndex, vehicle: null, settledIndex: 0, settledStepCount: -1, groundKeptStepCount: -Infinity, steppedFields: null, behavior, own: behavior ? behavior.startOwn() : null, isOwnChanged: false, driverCharacterId: null, motion: null };
|
|
358
369
|
bodies[index] = body;
|
|
370
|
+
if (behavior) {
|
|
371
|
+
let placeIndex = behavingBodies.length;
|
|
372
|
+
while (placeIndex > 0 && behavingBodies[placeIndex - 1].index > index) placeIndex -= 1;
|
|
373
|
+
behavingBodies.splice(placeIndex, 0, body);
|
|
374
|
+
}
|
|
359
375
|
if (motionIndex !== 2) {
|
|
360
376
|
// Kept in the order of their indexes, so every side goes through them alike.
|
|
361
377
|
let placeIndex = unfixedBodies.length;
|
|
@@ -454,6 +470,9 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
454
470
|
}
|
|
455
471
|
lowestFreeBodyIndex = Math.min(lowestFreeBodyIndex, index);
|
|
456
472
|
if (body.timetable) timetableBodies.splice(timetableBodies.indexOf(body), 1);
|
|
473
|
+
if (body.behavior) behavingBodies.splice(behavingBodies.indexOf(body), 1);
|
|
474
|
+
forcedBodies.delete(body);
|
|
475
|
+
leaveZones(bodyTagOf(index), body.declaration.id, null);
|
|
457
476
|
rapierWorld.removeRigidBody(body.rigidBody);
|
|
458
477
|
bodyIndexById.delete(body.declaration.id);
|
|
459
478
|
bodies[index] = null;
|
|
@@ -543,6 +562,75 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
543
562
|
}
|
|
544
563
|
}
|
|
545
564
|
|
|
565
|
+
// ---- Body kinds with rules of their own, and the forces a step pushes with ----
|
|
566
|
+
|
|
567
|
+
const bodyOwnBefore = [];
|
|
568
|
+
/** Steps every body whose kind has rules, before the engine moves the world: each by its driver's input. */
|
|
569
|
+
function stepBodies(worldStepContext) {
|
|
570
|
+
const { inputOf } = worldStepContext;
|
|
571
|
+
for (const body of behavingBodies) body.driverCharacterId = null;
|
|
572
|
+
for (const character of characters) {
|
|
573
|
+
if (!character || character.rideBodyIndex < 0 || character.seatIndex !== 0) continue;
|
|
574
|
+
const ridden = bodies[character.rideBodyIndex];
|
|
575
|
+
if (ridden?.behavior) ridden.driverCharacterId = character.id;
|
|
576
|
+
}
|
|
577
|
+
for (const body of behavingBodies) {
|
|
578
|
+
const { behavior, own } = body;
|
|
579
|
+
body.isOwnChanged = false;
|
|
580
|
+
// At rest with nobody at its controls, nothing about it changes: it isn't stepped, and costs nothing.
|
|
581
|
+
if (body.driverCharacterId === null && !behavior.isSteppedAtRest && (body.motionIndex === 2 || (body.motionIndex === 0 && body.rigidBody.isSleeping()))) continue;
|
|
582
|
+
const { fieldNames } = behavior;
|
|
583
|
+
for (let nameIndex = 0; nameIndex < fieldNames.length; nameIndex += 1) bodyOwnBefore[nameIndex] = own[fieldNames[nameIndex]];
|
|
584
|
+
behavior.step(body, body.driverCharacterId === null ? null : (inputOf(body.driverCharacterId) ?? characterKind.idleInput), worldStepContext);
|
|
585
|
+
// A step that changed the kind's own fields leaves its body awake on the wire, so they're sent.
|
|
586
|
+
for (let nameIndex = 0; nameIndex < fieldNames.length; nameIndex += 1) if (own[fieldNames[nameIndex]] !== bodyOwnBefore[nameIndex]) body.isOwnChanged = true;
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
const bodyGiven = (given) => (typeof given === "string" ? bodies[bodyIndexById.get(given)] : given);
|
|
591
|
+
/**
|
|
592
|
+
* Pushes a moving body for one step. Before the step's first engine substep (a body kind's step, a character
|
|
593
|
+
* kind that steps before the world) it's a force the engine works with through every substep, against gravity
|
|
594
|
+
* and what the body leans on; later in a step it's the same push given at once.
|
|
595
|
+
*/
|
|
596
|
+
function forceBody(given, pushed, atM, isTurning) {
|
|
597
|
+
const body = bodyGiven(given);
|
|
598
|
+
if (!body || bodies[body.index] !== body || body.motionIndex !== 0) return false;
|
|
599
|
+
const isAt = !isTurning && atM !== null && atM !== undefined;
|
|
600
|
+
const sizeNumber = isBeforeSubsteps ? 1 : tickDurationSec;
|
|
601
|
+
engine.RawBatch.forceBody(batch.bodies, body.rigidBody.handle, pushed.x * sizeNumber, pushed.y * sizeNumber, pushed.z * sizeNumber, isAt ? atM.x : 0, isAt ? atM.y : 0, isAt ? atM.z : 0, (isAt ? 1 : 0) | (isBeforeSubsteps ? 0 : 2) | (isTurning ? 4 : 0));
|
|
602
|
+
if (isBeforeSubsteps) forcedBodies.add(body);
|
|
603
|
+
body.settledStepCount = -1;
|
|
604
|
+
return true;
|
|
605
|
+
}
|
|
606
|
+
/** The step's engine substeps are done: what pushed through them stops. */
|
|
607
|
+
function endForces() {
|
|
608
|
+
for (const body of forcedBodies) engine.RawBatch.resetBodyForces(batch.bodies, body.rigidBody.handle);
|
|
609
|
+
forcedBodies.clear();
|
|
610
|
+
}
|
|
611
|
+
/** A body's place, rotation, speed and spin now, in the body's own object, filled again at each call. */
|
|
612
|
+
function bodyMotion(given) {
|
|
613
|
+
const body = bodyGiven(given);
|
|
614
|
+
if (!body || bodies[body.index] !== body) return null;
|
|
615
|
+
const motion = (body.motion ??= { positionM: { x: 0, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 }, velocityMPerSec: { x: 0, y: 0, z: 0 }, spinRadPerSec: { x: 0, y: 0, z: 0 } });
|
|
616
|
+
raw.readBody(batch.bodies, body.rigidBody.handle);
|
|
617
|
+
const floats = batch.floats();
|
|
618
|
+
motion.positionM.x = floats[0];
|
|
619
|
+
motion.positionM.y = floats[1];
|
|
620
|
+
motion.positionM.z = floats[2];
|
|
621
|
+
motion.rotation.x = floats[3];
|
|
622
|
+
motion.rotation.y = floats[4];
|
|
623
|
+
motion.rotation.z = floats[5];
|
|
624
|
+
motion.rotation.w = floats[6];
|
|
625
|
+
motion.velocityMPerSec.x = floats[7];
|
|
626
|
+
motion.velocityMPerSec.y = floats[8];
|
|
627
|
+
motion.velocityMPerSec.z = floats[9];
|
|
628
|
+
motion.spinRadPerSec.x = floats[10];
|
|
629
|
+
motion.spinRadPerSec.y = floats[11];
|
|
630
|
+
motion.spinRadPerSec.z = floats[12];
|
|
631
|
+
return motion;
|
|
632
|
+
}
|
|
633
|
+
|
|
546
634
|
// ---- Joints ----
|
|
547
635
|
|
|
548
636
|
/** The engine body a joint end names: a body's, or a character's, by id. */
|
|
@@ -560,7 +648,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
560
648
|
const second = declaration.otherBodyId === null ? null : endOf(declaration.otherBodyId);
|
|
561
649
|
if (!first || (declaration.otherBodyId !== null && !second)) return false;
|
|
562
650
|
worldAnchor ??= rapierWorld.createRigidBody(engine.RigidBodyDesc.fixed());
|
|
563
|
-
const joint = { declaration, rapierJoint: null, isEnabled: false, bodyIndexes: [first.bodyIndex, second?.bodyIndex ?? -1], characterIndexes: [first.characterIndex, second?.characterIndex ?? -1], first, second };
|
|
651
|
+
const joint = { declaration, rapierJoint: null, isEnabled: false, isBroken: false, motorTargetNumber: declaration.motor?.targetNumber ?? 0, bodyIndexes: [first.bodyIndex, second?.bodyIndex ?? -1], characterIndexes: [first.characterIndex, second?.characterIndex ?? -1], first, second };
|
|
564
652
|
joints.set(declaration.id, joint);
|
|
565
653
|
setJointEnabled(joint, isEnabled);
|
|
566
654
|
return true;
|
|
@@ -572,8 +660,11 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
572
660
|
if (!isEnabled) {
|
|
573
661
|
if (joint.rapierJoint) rapierWorld.removeImpulseJoint(joint.rapierJoint, true);
|
|
574
662
|
joint.rapierJoint = null;
|
|
663
|
+
breakableJoints.delete(joint);
|
|
575
664
|
return;
|
|
576
665
|
}
|
|
666
|
+
// Held again, it's whole again.
|
|
667
|
+
setJointBroken(joint, false);
|
|
577
668
|
const { declaration } = joint;
|
|
578
669
|
const { anchorM, otherAnchorM, axis } = declaration;
|
|
579
670
|
const otherRigidBody = joint.second?.rigidBody ?? worldAnchor;
|
|
@@ -586,12 +677,47 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
586
677
|
else jointData = engine.JointData.rope(declaration.restLengthM, anchorM, otherAnchorM);
|
|
587
678
|
joint.rapierJoint = rapierWorld.createImpulseJoint(jointData, joint.first.rigidBody, otherRigidBody, true);
|
|
588
679
|
if ((declaration.jointKind === "hinge" || declaration.jointKind === "slider") && declaration.minimumNumber !== null && declaration.maximumNumber !== null) joint.rapierJoint.setLimits(declaration.minimumNumber, declaration.maximumNumber);
|
|
680
|
+
if (declaration.motor) runMotor(joint);
|
|
681
|
+
if (declaration.breakForceNewtons !== null) breakableJoints.add(joint);
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/** Sets a joint's motor to its target: the speed it holds, or the place it goes to. */
|
|
685
|
+
function runMotor(joint) {
|
|
686
|
+
const { motor, jointKind } = joint.declaration;
|
|
687
|
+
if (motor.motorKind === "speed") joint.rapierJoint.configureMotorVelocity(joint.motorTargetNumber, motor.dampingNumber);
|
|
688
|
+
else joint.rapierJoint.configureMotorPosition(joint.motorTargetNumber, motor.stiffnessNumber, motor.dampingNumber);
|
|
689
|
+
if (motor.maximumForceNumber !== null) engine.RawBatch.setMotorMaximumForce(batch.impulseJoints, joint.rapierJoint.handle, jointKind === "hinge", motor.maximumForceNumber);
|
|
690
|
+
}
|
|
691
|
+
function setJointMotor(joint, motorTargetNumber) {
|
|
692
|
+
if (!joint.declaration.motor || joint.motorTargetNumber === motorTargetNumber) return;
|
|
693
|
+
joint.motorTargetNumber = motorTargetNumber;
|
|
694
|
+
if (joint.rapierJoint) runMotor(joint);
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
/** The joints that break when they pull or push too hard, while they hold. */
|
|
698
|
+
const breakableJoints = new Set();
|
|
699
|
+
/** How many times a joint has broken or been made whole: whoever tells of breaks looks again when it moves. */
|
|
700
|
+
let jointBreakChangeCount = 0;
|
|
701
|
+
function setJointBroken(joint, isBroken) {
|
|
702
|
+
if (joint.isBroken === isBroken) return;
|
|
703
|
+
joint.isBroken = isBroken;
|
|
704
|
+
jointBreakChangeCount += 1;
|
|
705
|
+
}
|
|
706
|
+
/** After a step's engine substeps: a joint held harder than it bears lets go, broken. */
|
|
707
|
+
function breakJoints() {
|
|
708
|
+
for (const joint of breakableJoints) {
|
|
709
|
+
// The engine keeps what the joint gave over one of its solver's small steps: that, as a force.
|
|
710
|
+
if (engine.RawBatch.jointImpulse(batch.impulseJoints, joint.rapierJoint.handle) <= joint.declaration.breakForceNewtons * solverStepDurationSec) continue;
|
|
711
|
+
setJointEnabled(joint, false);
|
|
712
|
+
setJointBroken(joint, true);
|
|
713
|
+
}
|
|
589
714
|
}
|
|
590
715
|
|
|
591
716
|
function removeJoint(jointId) {
|
|
592
717
|
const joint = joints.get(jointId);
|
|
593
718
|
if (!joint) return false;
|
|
594
719
|
setJointEnabled(joint, false);
|
|
720
|
+
setJointBroken(joint, false);
|
|
595
721
|
joints.delete(jointId);
|
|
596
722
|
return true;
|
|
597
723
|
}
|
|
@@ -604,31 +730,31 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
604
730
|
* feet are and half the world's own height more, whatever its size, so a place on the wire means the same for all;
|
|
605
731
|
* its capsule is raised or lowered on it to stand on the same feet.
|
|
606
732
|
*/
|
|
607
|
-
const characterSizes = [{ name: null, ...world.character }, ...world.characterSizes].map((
|
|
733
|
+
const characterSizes = [{ name: null, ...world.character }, ...world.characterSizes].map((characterSize) => {
|
|
608
734
|
const controller = isKinematicKind ? rapierWorld.createCharacterController(CHARACTER_SKIN_M) : null;
|
|
609
735
|
if (controller) {
|
|
610
736
|
controller.setUp({ x: 0, y: 1, z: 0 });
|
|
611
737
|
controller.setSlideEnabled(true);
|
|
612
|
-
if (
|
|
613
|
-
controller.setMaxSlopeClimbAngle((
|
|
614
|
-
controller.setMinSlopeSlideAngle?.(((
|
|
615
|
-
controller.enableSnapToGround(
|
|
738
|
+
if (characterSize.stepHeightM > 0) controller.enableAutostep(characterSize.stepHeightM, characterSize.radiusM * 0.5, false);
|
|
739
|
+
controller.setMaxSlopeClimbAngle((characterSize.maximumSlopeDeg * Math.PI) / 180);
|
|
740
|
+
controller.setMinSlopeSlideAngle?.(((characterSize.maximumSlopeDeg + 5) * Math.PI) / 180);
|
|
741
|
+
controller.enableSnapToGround(characterSize.stepHeightM > 0 ? characterSize.stepHeightM : 0.1);
|
|
616
742
|
controller.setApplyImpulsesToDynamicBodies(characterKind.canPushBodies !== false);
|
|
617
743
|
controller.setCharacterMass(currentTuning.characterMassKg ?? 70);
|
|
618
744
|
}
|
|
619
745
|
return {
|
|
620
|
-
...
|
|
621
|
-
halfSegmentM:
|
|
746
|
+
...characterSize,
|
|
747
|
+
halfSegmentM: characterSize.heightM / 2 - characterSize.radiusM,
|
|
622
748
|
/** How far above the body's place the capsule's middle is. */
|
|
623
|
-
riseM: (
|
|
749
|
+
riseM: (characterSize.heightM - world.character.heightM) / 2,
|
|
624
750
|
controller,
|
|
625
751
|
/** How far up a surface under the character faces, at least, for it to stand there: the steepest slope it climbs. */
|
|
626
|
-
minimumStandNormalNumber: Math.cos((
|
|
752
|
+
minimumStandNormalNumber: Math.cos((characterSize.maximumSlopeDeg * Math.PI) / 180),
|
|
627
753
|
};
|
|
628
754
|
});
|
|
629
755
|
const characterHalfSegmentM = characterSizes[0].halfSegmentM;
|
|
630
|
-
const tallestCharacterHeightM = Math.max(...characterSizes.map((
|
|
631
|
-
const characterSizeIndexByName = new Map(characterSizes.map((
|
|
756
|
+
const tallestCharacterHeightM = Math.max(...characterSizes.map((characterSize) => characterSize.heightM));
|
|
757
|
+
const characterSizeIndexByName = new Map(characterSizes.map((characterSize, sizeIndex) => [characterSize.name, sizeIndex]));
|
|
632
758
|
|
|
633
759
|
/**
|
|
634
760
|
* Adds a character with its feet at a place, at an index: the next free one, or the one given. Answers the index.
|
|
@@ -661,7 +787,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
661
787
|
isWaiting,
|
|
662
788
|
rigidBody,
|
|
663
789
|
collider,
|
|
664
|
-
|
|
790
|
+
characterSize: characterSizes[0],
|
|
665
791
|
sizeIndex: 0,
|
|
666
792
|
/** Which of the world's characterSizes it is now, or null for the world's own character's. */
|
|
667
793
|
characterSizeName: null,
|
|
@@ -689,6 +815,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
689
815
|
characterKind.onCharacterRemoved?.(character, stepTools);
|
|
690
816
|
for (const [jointId, joint] of joints) if (joint.characterIndexes.includes(index)) removeJoint(jointId);
|
|
691
817
|
disownCollider(character.collider);
|
|
818
|
+
leaveZones(characterTagOf(index), null, character.id);
|
|
692
819
|
rapierWorld.removeRigidBody(character.rigidBody);
|
|
693
820
|
characterIndexById.delete(character.id);
|
|
694
821
|
characters[index] = null;
|
|
@@ -726,7 +853,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
726
853
|
const tagNumber = numbers[contactIndex * CONTACT_NUMBER_COUNT];
|
|
727
854
|
const body = (tagNumber & TAG_KIND_MASK_NUMBER) === BODY_TAG_NUMBER ? bodies[tagNumber >>> 8] : null;
|
|
728
855
|
if (!body || body.motionIndex !== 2) return false;
|
|
729
|
-
if (floats[contactIndex * CONTACT_FLOAT_COUNT + 4] >= character.
|
|
856
|
+
if (floats[contactIndex * CONTACT_FLOAT_COUNT + 4] >= character.characterSize.minimumStandNormalNumber) isStanding = true;
|
|
730
857
|
}
|
|
731
858
|
rest.isResting = isStanding;
|
|
732
859
|
return isStanding;
|
|
@@ -740,23 +867,23 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
740
867
|
*/
|
|
741
868
|
function setCharacterSize(character, sizeIndex, isFitChecked = false) {
|
|
742
869
|
if (character.sizeIndex === sizeIndex) return true;
|
|
743
|
-
const
|
|
744
|
-
if (!
|
|
870
|
+
const characterSize = characterSizes[sizeIndex];
|
|
871
|
+
if (!characterSize) return false;
|
|
745
872
|
if (isFitChecked && !character.isWaiting) {
|
|
746
873
|
raw.readBody(batch.bodies, character.rigidBody.handle);
|
|
747
874
|
let floats = batch.floats();
|
|
748
|
-
const contactCount = raw.capsuleContacts(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, floats[0], floats[1] + CHARACTER_SKIN_M +
|
|
875
|
+
const contactCount = raw.capsuleContacts(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, floats[0], floats[1] + CHARACTER_SKIN_M + characterSize.riseM, floats[2], 0, 0, 0, 1, characterSize.radiusM, characterSize.halfSegmentM, 0, groupsOf(character.layerIndex), character.rigidBody.handle, (isEachCharacterAlone ? SKIPS_CHARACTERS_FLAG_NUMBER : 0) | EXCLUDES_BODY_FLAG_NUMBER | EACH_TRIANGLE_FLAG_NUMBER);
|
|
749
876
|
floats = batch.floats();
|
|
750
877
|
for (let contactIndex = 0; contactIndex < contactCount; contactIndex += 1) {
|
|
751
878
|
const firstIndex = contactIndex * CONTACT_FLOAT_COUNT;
|
|
752
|
-
if (floats[firstIndex + 6] > SIZE_FIT_DEPTH_M && floats[firstIndex + 4] <
|
|
879
|
+
if (floats[firstIndex + 6] > SIZE_FIT_DEPTH_M && floats[firstIndex + 4] < characterSize.minimumStandNormalNumber) return false;
|
|
753
880
|
}
|
|
754
881
|
}
|
|
755
|
-
character.
|
|
882
|
+
character.characterSize = characterSize;
|
|
756
883
|
character.sizeIndex = sizeIndex;
|
|
757
|
-
character.characterSizeName =
|
|
758
|
-
character.collider.setShape(new engine.Capsule(
|
|
759
|
-
character.collider.setTranslationWrtParent({ x: 0, y: colliderRiseM +
|
|
884
|
+
character.characterSizeName = characterSize.name;
|
|
885
|
+
character.collider.setShape(new engine.Capsule(characterSize.halfSegmentM, characterSize.radiusM));
|
|
886
|
+
character.collider.setTranslationWrtParent({ x: 0, y: colliderRiseM + characterSize.riseM, z: 0 });
|
|
760
887
|
isPropagationOwed = true;
|
|
761
888
|
isSceneOwed = true;
|
|
762
889
|
return true;
|
|
@@ -842,16 +969,22 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
842
969
|
hit.triangleIndex = triangleIndex ?? null;
|
|
843
970
|
hit.surfaceName = colliderInfo.surfaceIndices && hit.triangleIndex !== null ? (world.surfaceNames[colliderInfo.surfaceIndices[hit.triangleIndex]] ?? null) : colliderInfo.surfaceName;
|
|
844
971
|
}
|
|
972
|
+
/** A collider's surface where a contact touches it (the contact's subshape there: a mesh's triangle), or null. */
|
|
973
|
+
const touchedSurface = { triangleIndex: null, surfaceName: null };
|
|
974
|
+
const surfaceOfCollider = (collider, subshapeNumber) => {
|
|
975
|
+
noteSurface(touchedSurface, colliderNumberOf(collider.handle), subshapeNumber);
|
|
976
|
+
return touchedSurface.surfaceName;
|
|
977
|
+
};
|
|
978
|
+
const NO_SPEED = { x: 0, y: 0, z: 0 };
|
|
845
979
|
/**
|
|
846
980
|
* A hit as a query answers it, written into the caller's own object when it gives one (a game casting thousands of
|
|
847
981
|
* rays a second keeps one), else a new one.
|
|
848
982
|
*/
|
|
849
|
-
function hitInto(into,
|
|
983
|
+
function hitInto(into, tagNumber, triangleNumber, colliderNumber, pointX, pointY, pointZ, normalX, normalY, normalZ, distanceM) {
|
|
850
984
|
const hit = into ?? { bodyId: null, characterId: null, pointM: { x: 0, y: 0, z: 0 }, normal: { x: 0, y: 0, z: 0 }, distanceM: 0, triangleIndex: null, surfaceName: null };
|
|
851
|
-
const tagNumber = numbers[0];
|
|
852
985
|
hit.bodyId = bodyIdOfTag(tagNumber);
|
|
853
986
|
hit.characterId = characterIdOfTag(tagNumber);
|
|
854
|
-
noteSurface(hit,
|
|
987
|
+
noteSurface(hit, colliderNumber, triangleNumber);
|
|
855
988
|
hit.pointM ??= { x: 0, y: 0, z: 0 };
|
|
856
989
|
hit.normal ??= { x: 0, y: 0, z: 0 };
|
|
857
990
|
hit.pointM.x = pointX;
|
|
@@ -863,14 +996,47 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
863
996
|
hit.distanceM = distanceM;
|
|
864
997
|
return hit;
|
|
865
998
|
}
|
|
866
|
-
/** A ball (shapeKindNumber 0)
|
|
867
|
-
function castShapeQuery(shapeKindNumber, radiusM, halfSegmentM, rotation, { fromM, directionM, maximumDistanceM, collisionLayerNames = null, excludedId = null, isStoppedAtPenetration = true }, into) {
|
|
999
|
+
/** A ball (shapeKindNumber 0), a capsule (1) or a box (2: half its width, height and depth) moved along a direction: the first thing it meets, or null. Its own space is turned by rotation. */
|
|
1000
|
+
function castShapeQuery(shapeKindNumber, radiusM, halfSegmentM, rotation, { fromM, directionM, maximumDistanceM, collisionLayerNames = null, excludedId = null, isStoppedAtPenetration = true }, into, halfDepthM = 0) {
|
|
868
1001
|
const lengthNumber = Math.hypot(directionM.x, directionM.y, directionM.z) || 1;
|
|
869
1002
|
const excluded = excludedOf(excludedId);
|
|
870
|
-
const isHit = raw.castShape(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, shapeKindNumber, radiusM, halfSegmentM, rotation.x, rotation.y, rotation.z, rotation.w, fromM.x, fromM.y, fromM.z, directionM.x / lengthNumber, directionM.y / lengthNumber, directionM.z / lengthNumber, maximumDistanceM, isStoppedAtPenetration, queryGroupsOf(collisionLayerNames), excluded ? excluded.handle : 0, queryFlagsOf(excluded));
|
|
1003
|
+
const isHit = raw.castShape(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, shapeKindNumber, radiusM, halfSegmentM, halfDepthM, rotation.x, rotation.y, rotation.z, rotation.w, fromM.x, fromM.y, fromM.z, directionM.x / lengthNumber, directionM.y / lengthNumber, directionM.z / lengthNumber, maximumDistanceM, isStoppedAtPenetration, queryGroupsOf(collisionLayerNames), excluded ? excluded.handle : 0, queryFlagsOf(excluded));
|
|
871
1004
|
if (!isHit) return null;
|
|
872
1005
|
const floats = batch.floats();
|
|
873
|
-
|
|
1006
|
+
const numbers = batch.numbers();
|
|
1007
|
+
return hitInto(into, numbers[0], numbers[1], numbers[2], floats[1], floats[2], floats[3], floats[4], floats[5], floats[6], floats[0]);
|
|
1008
|
+
}
|
|
1009
|
+
/** Everything a shape overlaps, each owner once: [{ bodyId, characterId }]. The lengths are as the engine's QueryShapes takes them. */
|
|
1010
|
+
function overlapShapeQuery(shapeKindNumber, firstM, secondM, thirdM, centerM, rotation, collisionLayerNames, excludedId) {
|
|
1011
|
+
const excluded = excludedOf(excludedId);
|
|
1012
|
+
const foundCount = raw.overlapShape(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, shapeKindNumber, firstM, secondM, thirdM, centerM.x, centerM.y, centerM.z, rotation.x, rotation.y, rotation.z, rotation.w, queryGroupsOf(collisionLayerNames), excluded ? excluded.handle : 0, queryFlagsOf(excluded));
|
|
1013
|
+
const found = [];
|
|
1014
|
+
const numbers = batch.numbers();
|
|
1015
|
+
for (let foundIndex = 0; foundIndex < foundCount; foundIndex += 1) {
|
|
1016
|
+
const tagNumber = numbers[foundIndex];
|
|
1017
|
+
if ((tagNumber & TAG_KIND_MASK_NUMBER) === 0) continue;
|
|
1018
|
+
const bodyId = bodyIdOfTag(tagNumber);
|
|
1019
|
+
const characterId = characterIdOfTag(tagNumber);
|
|
1020
|
+
if (!found.some((each) => each.bodyId === bodyId && each.characterId === characterId)) found.push({ bodyId, characterId });
|
|
1021
|
+
}
|
|
1022
|
+
return found;
|
|
1023
|
+
}
|
|
1024
|
+
/** Hits' objects a caller's own list held and no longer shows, kept for the next longer answer. */
|
|
1025
|
+
const spareHits = [];
|
|
1026
|
+
/** What castRays answers into when the game gives nothing of its own: arrays as long as the rays asked, and how to read one ray's hit whole. */
|
|
1027
|
+
function raysAnswerOf(rayCount, into) {
|
|
1028
|
+
const answer = into ?? { rayCount: 0, hitCount: 0, distancesM: new Float32Array(0), normals: new Float32Array(0), hitNumbers: new Uint32Array(0), rays: null, hitAt: null };
|
|
1029
|
+
if (!(answer.distancesM instanceof Float32Array) || answer.distancesM.length < rayCount) answer.distancesM = new Float32Array(rayCount);
|
|
1030
|
+
if (!(answer.normals instanceof Float32Array) || answer.normals.length < rayCount * 3) answer.normals = new Float32Array(rayCount * 3);
|
|
1031
|
+
if (!(answer.hitNumbers instanceof Uint32Array) || answer.hitNumbers.length < rayCount * 3) answer.hitNumbers = new Uint32Array(rayCount * 3);
|
|
1032
|
+
answer.hitAt ??= (rayIndex, givenHit = null) => {
|
|
1033
|
+
const distanceM = answer.distancesM[rayIndex];
|
|
1034
|
+
if (!(rayIndex >= 0 && rayIndex < answer.rayCount) || distanceM < 0) return null;
|
|
1035
|
+
const { rays, normals, hitNumbers } = answer;
|
|
1036
|
+
const lengthNumber = Math.hypot(rays[rayIndex * 6 + 3], rays[rayIndex * 6 + 4], rays[rayIndex * 6 + 5]) || 1;
|
|
1037
|
+
return hitInto(givenHit, hitNumbers[rayIndex * 3], hitNumbers[rayIndex * 3 + 1], hitNumbers[rayIndex * 3 + 2], rays[rayIndex * 6] + (rays[rayIndex * 6 + 3] / lengthNumber) * distanceM, rays[rayIndex * 6 + 1] + (rays[rayIndex * 6 + 4] / lengthNumber) * distanceM, rays[rayIndex * 6 + 2] + (rays[rayIndex * 6 + 5] / lengthNumber) * distanceM, normals[rayIndex * 3], normals[rayIndex * 3 + 1], normals[rayIndex * 3 + 2], distanceM);
|
|
1038
|
+
};
|
|
1039
|
+
return answer;
|
|
874
1040
|
}
|
|
875
1041
|
/** Contacts' objects a caller's own list held and no longer shows, kept for the next longer answer. */
|
|
876
1042
|
const spareContacts = [];
|
|
@@ -888,8 +1054,71 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
888
1054
|
const isHit = raw.castRay(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, fromM.x, fromM.y, fromM.z, directionX, directionY, directionZ, maximumDistanceM, queryGroupsOf(collisionLayerNames), excluded ? excluded.handle : 0, queryFlagsOf(excluded));
|
|
889
1055
|
if (!isHit) return null;
|
|
890
1056
|
const floats = batch.floats();
|
|
1057
|
+
const numbers = batch.numbers();
|
|
891
1058
|
const distanceM = floats[0];
|
|
892
|
-
return hitInto(into,
|
|
1059
|
+
return hitInto(into, numbers[0], numbers[1], numbers[2], fromM.x + directionX * distanceM, fromM.y + directionY * distanceM, fromM.z + directionZ * distanceM, floats[1], floats[2], floats[3], distanceM);
|
|
1060
|
+
},
|
|
1061
|
+
/**
|
|
1062
|
+
* Everything a ray passes through, nearest first, one hit a shape (a mesh answers where the ray first meets it):
|
|
1063
|
+
* a list of hits as castRay's, up to maximumHitCount (default 16). What a bullet that goes through thin walls
|
|
1064
|
+
* asks. With into (a list of the caller's own, kept and given again), written there.
|
|
1065
|
+
*/
|
|
1066
|
+
castRayAll({ fromM, directionM, maximumDistanceM, maximumHitCount = 16, collisionLayerNames = null, excludedId = null }, into = null) {
|
|
1067
|
+
const lengthNumber = Math.hypot(directionM.x, directionM.y, directionM.z) || 1;
|
|
1068
|
+
const directionX = directionM.x / lengthNumber;
|
|
1069
|
+
const directionY = directionM.y / lengthNumber;
|
|
1070
|
+
const directionZ = directionM.z / lengthNumber;
|
|
1071
|
+
const excluded = excludedOf(excludedId);
|
|
1072
|
+
const hitCount = raw.castRayAll(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, fromM.x, fromM.y, fromM.z, directionX, directionY, directionZ, maximumDistanceM, queryGroupsOf(collisionLayerNames), excluded ? excluded.handle : 0, queryFlagsOf(excluded), maximumHitCount);
|
|
1073
|
+
const hits = into ?? [];
|
|
1074
|
+
while (hits.length > hitCount) spareHits.push(hits.pop());
|
|
1075
|
+
const floats = batch.floats();
|
|
1076
|
+
const numbers = batch.numbers();
|
|
1077
|
+
for (let hitIndex = 0; hitIndex < hitCount; hitIndex += 1) {
|
|
1078
|
+
const distanceM = floats[hitIndex * RAY_HIT_FLOAT_COUNT];
|
|
1079
|
+
hits[hitIndex] = hitInto(hits[hitIndex] ?? ((into && spareHits.pop()) || null), numbers[hitIndex * 3], numbers[hitIndex * 3 + 1], numbers[hitIndex * 3 + 2], fromM.x + directionX * distanceM, fromM.y + directionY * distanceM, fromM.z + directionZ * distanceM, floats[hitIndex * RAY_HIT_FLOAT_COUNT + 1], floats[hitIndex * RAY_HIT_FLOAT_COUNT + 2], floats[hitIndex * RAY_HIT_FLOAT_COUNT + 3], distanceM);
|
|
1080
|
+
}
|
|
1081
|
+
return hits;
|
|
1082
|
+
},
|
|
1083
|
+
/**
|
|
1084
|
+
* Many rays in one call (a shotgun's pellets, a lidar, a crowd's feet): rays holds six numbers a ray, where it
|
|
1085
|
+
* starts (x, y, z) and its direction (x, y, z, of any length). Answers { rayCount, hitCount, distancesM (how
|
|
1086
|
+
* far each went, -1 for one that met nothing), normals (three numbers a ray), hitAt(rayIndex, into) (one ray's
|
|
1087
|
+
* hit whole, as castRay's, or null) }. With into (an answer of the caller's own, kept and given again), written
|
|
1088
|
+
* there: nothing is left for the garbage collector.
|
|
1089
|
+
*/
|
|
1090
|
+
castRays({ rays, rayCount = Math.floor(rays.length / 6), maximumDistanceM, collisionLayerNames = null, excludedId = null }, into = null) {
|
|
1091
|
+
const answer = raysAnswerOf(rayCount, into);
|
|
1092
|
+
const excluded = excludedOf(excludedId);
|
|
1093
|
+
const groupsNumber = queryGroupsOf(collisionLayerNames);
|
|
1094
|
+
const flagsNumber = queryFlagsOf(excluded);
|
|
1095
|
+
answer.rayCount = rayCount;
|
|
1096
|
+
answer.rays = rays;
|
|
1097
|
+
answer.hitCount = 0;
|
|
1098
|
+
// As many rays a call as answer before the awake bodies the last step left.
|
|
1099
|
+
for (let firstRayIndex = 0; firstRayIndex < rayCount; firstRayIndex += RAYS_PER_CALL_COUNT) {
|
|
1100
|
+
const callRayCount = Math.min(RAYS_PER_CALL_COUNT, rayCount - firstRayIndex);
|
|
1101
|
+
batch.floats().set(rays.subarray(firstRayIndex * 6, (firstRayIndex + callRayCount) * 6));
|
|
1102
|
+
answer.hitCount += raw.castRays(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, callRayCount, maximumDistanceM, groupsNumber, excluded ? excluded.handle : 0, flagsNumber);
|
|
1103
|
+
const floats = batch.floats();
|
|
1104
|
+
const numbers = batch.numbers();
|
|
1105
|
+
for (let rayIndex = 0; rayIndex < callRayCount; rayIndex += 1) {
|
|
1106
|
+
const firstIndex = callRayCount * 6 + rayIndex * RAY_HIT_FLOAT_COUNT;
|
|
1107
|
+
const intoIndex = firstRayIndex + rayIndex;
|
|
1108
|
+
answer.distancesM[intoIndex] = floats[firstIndex];
|
|
1109
|
+
answer.normals[intoIndex * 3] = floats[firstIndex + 1];
|
|
1110
|
+
answer.normals[intoIndex * 3 + 1] = floats[firstIndex + 2];
|
|
1111
|
+
answer.normals[intoIndex * 3 + 2] = floats[firstIndex + 3];
|
|
1112
|
+
answer.hitNumbers[intoIndex * 3] = numbers[rayIndex * 3];
|
|
1113
|
+
answer.hitNumbers[intoIndex * 3 + 1] = numbers[rayIndex * 3 + 1];
|
|
1114
|
+
answer.hitNumbers[intoIndex * 3 + 2] = numbers[rayIndex * 3 + 2];
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
return answer;
|
|
1118
|
+
},
|
|
1119
|
+
/** The first thing a box (turned by rotation) meets moving along a direction, or null: what a crate's width, a vehicle's body or a melee swing sweeps. With into, written there. */
|
|
1120
|
+
castBox(query, into = null) {
|
|
1121
|
+
return castShapeQuery(2, query.sizeM.x / 2, query.sizeM.y / 2, query.rotation ?? NO_TURN, query, into, query.sizeM.z / 2);
|
|
893
1122
|
},
|
|
894
1123
|
/** The first thing a ball meets moving along a direction: { bodyId, characterId, pointM, normal, distanceM }, or null. With into, written there. */
|
|
895
1124
|
castBall(query, into = null) {
|
|
@@ -939,21 +1168,166 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
939
1168
|
},
|
|
940
1169
|
/** Everything a ball overlaps: [{ bodyId, characterId }]. */
|
|
941
1170
|
overlapBall({ centerM, radiusM, collisionLayerNames = null, excludedId = null }) {
|
|
942
|
-
|
|
943
|
-
|
|
1171
|
+
return overlapShapeQuery(0, radiusM, 0, 0, centerM, NO_TURN, collisionLayerNames, excludedId);
|
|
1172
|
+
},
|
|
1173
|
+
/** Everything a box (turned by rotation) overlaps: [{ bodyId, characterId }]. */
|
|
1174
|
+
overlapBox({ centerM, sizeM, rotation = NO_TURN, collisionLayerNames = null, excludedId = null }) {
|
|
1175
|
+
return overlapShapeQuery(2, sizeM.x / 2, sizeM.y / 2, sizeM.z / 2, centerM, rotation, collisionLayerNames, excludedId);
|
|
1176
|
+
},
|
|
1177
|
+
/**
|
|
1178
|
+
* The ids of the zones that are on and that a place touches now: a point (centerM alone), a ball (with radiusM)
|
|
1179
|
+
* or a capsule (with radiusM and heightM, standing up or turned by rotation).
|
|
1180
|
+
*/
|
|
1181
|
+
zonesAt({ centerM, radiusM = 0, heightM = 0, rotation = NO_TURN }) {
|
|
1182
|
+
if (!zones.length) return [];
|
|
1183
|
+
const isCapsule = heightM > radiusM * 2;
|
|
1184
|
+
const foundCount = raw.zonesOfShape(batch.narrowPhase, batch.bodies, isCapsule ? 1 : 0, Math.max(radiusM, POINT_RADIUS_M), isCapsule ? heightM / 2 - radiusM : 0, 0, centerM.x, centerM.y, centerM.z, rotation.x, rotation.y, rotation.z, rotation.w);
|
|
944
1185
|
const found = [];
|
|
945
1186
|
const numbers = batch.numbers();
|
|
946
|
-
for (let foundIndex = 0; foundIndex < foundCount; foundIndex += 1)
|
|
947
|
-
const tagNumber = numbers[foundIndex];
|
|
948
|
-
if ((tagNumber & TAG_KIND_MASK_NUMBER) === 0) continue;
|
|
949
|
-
const bodyId = bodyIdOfTag(tagNumber);
|
|
950
|
-
const characterId = characterIdOfTag(tagNumber);
|
|
951
|
-
if (!found.some((each) => each.bodyId === bodyId && each.characterId === characterId)) found.push({ bodyId, characterId });
|
|
952
|
-
}
|
|
1187
|
+
for (let foundIndex = 0; foundIndex < foundCount; foundIndex += 1) found.push(zones[numbers[foundIndex]].id);
|
|
953
1188
|
return found;
|
|
954
1189
|
},
|
|
955
1190
|
};
|
|
956
1191
|
|
|
1192
|
+
// ---- Zones: places that take note of who's in them, and may pull, push and slow what is ----
|
|
1193
|
+
|
|
1194
|
+
/** The world's zones as the engine holds them, in the world's order; filled once the bodies they ride are in. */
|
|
1195
|
+
const zones = [];
|
|
1196
|
+
const zoneIndexById = new Map();
|
|
1197
|
+
/** Whether any zone pulls, pushes or slows: a kinematic character's kind asks what its place does to it. */
|
|
1198
|
+
let hasZoneEffects = false;
|
|
1199
|
+
/** Zones whose insides changed since they were last told, and who left by leaving the world. */
|
|
1200
|
+
let isAnyZoneChanged = false;
|
|
1201
|
+
let goneFromZones = [];
|
|
1202
|
+
function addZones() {
|
|
1203
|
+
for (const declared of world.zones ?? []) {
|
|
1204
|
+
const ridden = declared.bodyId === null ? null : bodies[bodyIndexById.get(declared.bodyId)];
|
|
1205
|
+
const zoneIndex = raw.addZone(declared.positionM.x, declared.positionM.y, declared.positionM.z, declared.rotation.x, declared.rotation.y, declared.rotation.z, declared.rotation.w, queryGroupsOf(declared.collisionLayerNames), declared.gravityPct / 100, declared.pushMPerSecPerSec.x, declared.pushMPerSecPerSec.y, declared.pushMPerSecPerSec.z, declared.dampingNumber);
|
|
1206
|
+
for (const shape of declared.shapes) raw.addZoneShape(zoneIndex, shape.shapeKindNumber, shape.lengthsM[0], shape.lengthsM[1], shape.lengthsM[2], shape.positionM.x, shape.positionM.y, shape.positionM.z, shape.rotation.x, shape.rotation.y, shape.rotation.z, shape.rotation.w);
|
|
1207
|
+
if (ridden) raw.setZoneBody(zoneIndex, ridden.rigidBody.handle);
|
|
1208
|
+
// A zone that rides a body this simulation doesn't hold (a moving one, over a level) isn't here.
|
|
1209
|
+
const isHere = declared.bodyId === null || Boolean(ridden);
|
|
1210
|
+
if (!declared.isEnabled || !isHere) raw.setZoneEnabled(zoneIndex, false);
|
|
1211
|
+
zones.push({ id: declared.id, declared, index: zoneIndex, isHere, isChanged: false, toldTagNumbers: new Set() });
|
|
1212
|
+
zoneIndexById.set(declared.id, zoneIndex);
|
|
1213
|
+
hasZoneEffects ||= declared.hasEffects;
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
/** Before a step: who's in each zone now, and which moving bodies the zones' pull, push and slowing act on through the step's substeps. */
|
|
1217
|
+
function stepZones() {
|
|
1218
|
+
const changeCount = raw.stepZones(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders);
|
|
1219
|
+
if (!changeCount) return;
|
|
1220
|
+
const numbers = batch.numbers();
|
|
1221
|
+
for (let changeIndex = 0; changeIndex < changeCount; changeIndex += 1) zones[numbers[changeIndex * 2] & 0x7fffffff].isChanged = true;
|
|
1222
|
+
isAnyZoneChanged = true;
|
|
1223
|
+
}
|
|
1224
|
+
const idsOfTag = (tagNumber) => ({ bodyId: bodyIdOfTag(tagNumber), characterId: characterIdOfTag(tagNumber) });
|
|
1225
|
+
/** A body or a character left the world: it's out of every zone it was told to be in. */
|
|
1226
|
+
function leaveZones(tagNumber, bodyId, characterId) {
|
|
1227
|
+
if (!zones.length) return;
|
|
1228
|
+
for (const zone of zones) if (zone.toldTagNumbers.delete(tagNumber)) goneFromZones.push({ zoneId: zone.id, bodyId, characterId, isEntered: false });
|
|
1229
|
+
raw.forgetZoneOccupant(tagNumber);
|
|
1230
|
+
}
|
|
1231
|
+
/**
|
|
1232
|
+
* Who came into a zone and who left since this was last asked: [{ zoneId, bodyId, characterId, isEntered }]. It
|
|
1233
|
+
* goes by where everything is now, so a step run again tells nothing twice, and what one run got wrong is put
|
|
1234
|
+
* right by the next.
|
|
1235
|
+
*/
|
|
1236
|
+
function takeZoneChanges() {
|
|
1237
|
+
const changes = goneFromZones;
|
|
1238
|
+
goneFromZones = [];
|
|
1239
|
+
if (!isAnyZoneChanged) return changes;
|
|
1240
|
+
isAnyZoneChanged = false;
|
|
1241
|
+
for (const zone of zones) {
|
|
1242
|
+
if (!zone.isChanged) continue;
|
|
1243
|
+
zone.isChanged = false;
|
|
1244
|
+
const occupantCount = raw.zoneOccupants(zone.index);
|
|
1245
|
+
const nowTagNumbers = new Set(batch.numbers().subarray(0, occupantCount));
|
|
1246
|
+
for (const tagNumber of zone.toldTagNumbers) {
|
|
1247
|
+
if (nowTagNumbers.has(tagNumber)) continue;
|
|
1248
|
+
zone.toldTagNumbers.delete(tagNumber);
|
|
1249
|
+
const ids = idsOfTag(tagNumber);
|
|
1250
|
+
if (ids.bodyId !== null || ids.characterId !== null) changes.push({ zoneId: zone.id, ...ids, isEntered: false });
|
|
1251
|
+
}
|
|
1252
|
+
for (const tagNumber of nowTagNumbers) {
|
|
1253
|
+
if (zone.toldTagNumbers.has(tagNumber)) continue;
|
|
1254
|
+
zone.toldTagNumbers.add(tagNumber);
|
|
1255
|
+
const ids = idsOfTag(tagNumber);
|
|
1256
|
+
if (ids.bodyId !== null || ids.characterId !== null) changes.push({ zoneId: zone.id, ...ids, isEntered: true });
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
return changes;
|
|
1260
|
+
}
|
|
1261
|
+
/** Who was in a zone at the last step: [{ bodyId, characterId }]. Empty for a zone that isn't here, or is off. */
|
|
1262
|
+
function zoneOccupants(zoneId) {
|
|
1263
|
+
const zoneIndex = zoneIndexById.get(zoneId);
|
|
1264
|
+
if (zoneIndex === undefined) return [];
|
|
1265
|
+
const occupantCount = raw.zoneOccupants(zoneIndex);
|
|
1266
|
+
const occupants = [];
|
|
1267
|
+
const numbers = batch.numbers();
|
|
1268
|
+
for (let occupantIndex = 0; occupantIndex < occupantCount; occupantIndex += 1) {
|
|
1269
|
+
const ids = idsOfTag(numbers[occupantIndex]);
|
|
1270
|
+
if (ids.bodyId !== null || ids.characterId !== null) occupants.push(ids);
|
|
1271
|
+
}
|
|
1272
|
+
return occupants;
|
|
1273
|
+
}
|
|
1274
|
+
function setZoneEnabled(zoneId, isEnabled) {
|
|
1275
|
+
const zone = zones[zoneIndexById.get(zoneId)];
|
|
1276
|
+
if (!zone?.isHere) return false;
|
|
1277
|
+
raw.setZoneEnabled(zone.index, isEnabled);
|
|
1278
|
+
return true;
|
|
1279
|
+
}
|
|
1280
|
+
/** The numbers of the zones a character's capsule touches now, in the engine's whole numbers: answers how many. */
|
|
1281
|
+
function zonesOfCharacter(character) {
|
|
1282
|
+
raw.readBody(batch.bodies, character.rigidBody.handle);
|
|
1283
|
+
const floats = batch.floats();
|
|
1284
|
+
return raw.zonesOfShape(batch.narrowPhase, batch.bodies, 1, character.characterSize.radiusM, character.characterSize.halfSegmentM, 0, floats[0], floats[1] + colliderRiseM + character.characterSize.riseM, floats[2], 0, 0, 0, 1);
|
|
1285
|
+
}
|
|
1286
|
+
const zoneEffects = { gravityPct: 100, pushMPerSecPerSec: { x: 0, y: 0, z: 0 }, dampingNumber: 0 };
|
|
1287
|
+
/**
|
|
1288
|
+
* What the zones a character stands in do there, together: { gravityPct, pushMPerSecPerSec, dampingNumber }, or
|
|
1289
|
+
* null where nothing pulls, pushes or slows it. The object is the piece's own, filled again by the next call: a
|
|
1290
|
+
* kinematic character's kind reads it at once (the engine moves a dynamic one by it itself).
|
|
1291
|
+
*/
|
|
1292
|
+
function zoneEffectsOf(character) {
|
|
1293
|
+
if (!hasZoneEffects) return null;
|
|
1294
|
+
const foundCount = zonesOfCharacter(character);
|
|
1295
|
+
if (!foundCount) return null;
|
|
1296
|
+
const numbers = batch.numbers();
|
|
1297
|
+
let gravityNumber = 1;
|
|
1298
|
+
let pushX = 0;
|
|
1299
|
+
let pushY = 0;
|
|
1300
|
+
let pushZ = 0;
|
|
1301
|
+
let dampingNumber = 0;
|
|
1302
|
+
let isAffected = false;
|
|
1303
|
+
for (let foundIndex = 0; foundIndex < foundCount; foundIndex += 1) {
|
|
1304
|
+
const { declared } = zones[numbers[foundIndex]];
|
|
1305
|
+
if (!declared.hasEffects) continue;
|
|
1306
|
+
isAffected = true;
|
|
1307
|
+
gravityNumber *= declared.gravityPct / 100;
|
|
1308
|
+
pushX += declared.pushMPerSecPerSec.x;
|
|
1309
|
+
pushY += declared.pushMPerSecPerSec.y;
|
|
1310
|
+
pushZ += declared.pushMPerSecPerSec.z;
|
|
1311
|
+
dampingNumber += declared.dampingNumber;
|
|
1312
|
+
}
|
|
1313
|
+
if (!isAffected) return null;
|
|
1314
|
+
zoneEffects.gravityPct = gravityNumber * 100;
|
|
1315
|
+
zoneEffects.pushMPerSecPerSec.x = pushX;
|
|
1316
|
+
zoneEffects.pushMPerSecPerSec.y = pushY;
|
|
1317
|
+
zoneEffects.pushMPerSecPerSec.z = pushZ;
|
|
1318
|
+
zoneEffects.dampingNumber = dampingNumber;
|
|
1319
|
+
return zoneEffects;
|
|
1320
|
+
}
|
|
1321
|
+
/** The ids of the zones a character is in now. */
|
|
1322
|
+
function zoneIdsOf(character) {
|
|
1323
|
+
if (!zones.length) return [];
|
|
1324
|
+
const foundCount = zonesOfCharacter(character);
|
|
1325
|
+
const found = [];
|
|
1326
|
+
const numbers = batch.numbers();
|
|
1327
|
+
for (let foundIndex = 0; foundIndex < foundCount; foundIndex += 1) found.push(zones[numbers[foundIndex]].id);
|
|
1328
|
+
return found;
|
|
1329
|
+
}
|
|
1330
|
+
|
|
957
1331
|
/**
|
|
958
1332
|
* Moves a kinematic character by as much of desiredM as the world lets it: sliding along walls, up steps and
|
|
959
1333
|
* slopes it can climb, snapped down to the ground under it. Answers { movedM, isGrounded }: a new one, or into
|
|
@@ -961,7 +1335,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
961
1335
|
*/
|
|
962
1336
|
function moveAndSlide(character, desiredM, into = null) {
|
|
963
1337
|
const moved = into ?? { movedM: { x: 0, y: 0, z: 0 }, isGrounded: false };
|
|
964
|
-
const { controller } = character.
|
|
1338
|
+
const { controller } = character.characterSize;
|
|
965
1339
|
if (!controller) {
|
|
966
1340
|
moved.movedM.x = 0;
|
|
967
1341
|
moved.movedM.y = 0;
|
|
@@ -993,6 +1367,15 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
993
1367
|
...queries,
|
|
994
1368
|
moveAndSlide,
|
|
995
1369
|
isRestingOnLevel,
|
|
1370
|
+
zoneIdsOf,
|
|
1371
|
+
zoneEffectsOf,
|
|
1372
|
+
zoneOccupants,
|
|
1373
|
+
/** A body's place, rotation, speed and spin now: { positionM, rotation, velocityMPerSec, spinRadPerSec }, the body's own object filled again at each call (copy what you keep). Give the body a step was given, or an id. */
|
|
1374
|
+
bodyMotion,
|
|
1375
|
+
/** Pushes a moving body with a force in newtons for this one step, at its centre of mass or at a place in the world (which turns it too). Answers false for a body that isn't moving by physics. */
|
|
1376
|
+
addForce: (body, forceNewtons, atM = null) => forceBody(body, forceNewtons, atM, false),
|
|
1377
|
+
/** Turns a moving body with a torque in newton metres about the world's axes, for this one step. */
|
|
1378
|
+
addTorque: (body, torqueNewtonMetres) => forceBody(body, torqueNewtonMetres, null, true),
|
|
996
1379
|
bodies,
|
|
997
1380
|
characters,
|
|
998
1381
|
bodyIndexById,
|
|
@@ -1004,12 +1387,12 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1004
1387
|
},
|
|
1005
1388
|
/** The character kind's own memory for this world (what's held, what changed): its startKindState's answer. */
|
|
1006
1389
|
kindState: null,
|
|
1007
|
-
/** A body as the world has it now, read only: { positionM, rotation, velocityMPerSec, spinRadPerSec, massKg, motionKind, collisionLayerName, isResting }, or null. */
|
|
1390
|
+
/** A body as the world has it now, read only: { positionM, rotation, velocityMPerSec, spinRadPerSec, massKg, motionKind, collisionLayerName, isResting, bodyKindName, own }, or null. */
|
|
1008
1391
|
bodyState(bodyId) {
|
|
1009
1392
|
const body = bodies[bodyIndexById.get(bodyId)];
|
|
1010
1393
|
if (!body) return null;
|
|
1011
1394
|
const fields = readBody(body.index);
|
|
1012
|
-
return { positionM: { x: fields.x, y: fields.y, z: fields.z }, rotation: fields.rotation, velocityMPerSec: { x: fields.velocityX, y: fields.velocityY, z: fields.velocityZ }, spinRadPerSec: { x: fields.spinX, y: fields.spinY, z: fields.spinZ }, massKg: body.massKg ?? null, motionKind: MOTION_KINDS[body.motionIndex], collisionLayerName: world.collisionLayers[body.layerIndex].name, isResting: simulation.isBodyResting(body.index) };
|
|
1395
|
+
return { positionM: { x: fields.x, y: fields.y, z: fields.z }, rotation: fields.rotation, velocityMPerSec: { x: fields.velocityX, y: fields.velocityY, z: fields.velocityZ }, spinRadPerSec: { x: fields.spinX, y: fields.spinY, z: fields.spinZ }, massKg: body.massKg ?? null, motionKind: MOTION_KINDS[body.motionIndex], collisionLayerName: world.collisionLayers[body.layerIndex].name, isResting: simulation.isBodyResting(body.index), bodyKindName: body.bodyKindName, own: body.own ? { ...body.own } : null };
|
|
1013
1396
|
},
|
|
1014
1397
|
/** A character as the world has it now, read only: { positionM (its feet), velocityMPerSec, facingYawRad, isGrounded, rideBodyId, collisionLayerName, own }, or null. */
|
|
1015
1398
|
characterState(characterId) {
|
|
@@ -1021,12 +1404,17 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1021
1404
|
return { positionM: { x: floats[0], y: floats[1] - world.character.heightM / 2, z: floats[2] }, velocityMPerSec, facingYawRad: character.facingYawRad, isGrounded: character.isGrounded, rideBodyId: bodies[character.rideBodyIndex]?.declaration.id ?? null, collisionLayerName: world.collisionLayers[character.ownLayerIndex].name, characterSizeName: character.characterSizeName, own: character.own };
|
|
1022
1405
|
},
|
|
1023
1406
|
/**
|
|
1024
|
-
* Ties or lets go a joint from a step (a press that takes a cart's handles),
|
|
1025
|
-
* replay. Answers false for a
|
|
1407
|
+
* Ties or lets go a joint from a step (a press that takes a cart's handles), or gives its motor another target
|
|
1408
|
+
* ({ isEnabled, motorTargetNumber }, either or both), so it's run again exactly on a replay. Answers false for a
|
|
1409
|
+
* joint that isn't here.
|
|
1026
1410
|
*/
|
|
1027
1411
|
setJoint(jointId, changes) {
|
|
1028
|
-
|
|
1029
|
-
|
|
1412
|
+
const joint = joints.get(jointId);
|
|
1413
|
+
const isSwitched = typeof changes?.isEnabled === "boolean";
|
|
1414
|
+
const isAimed = Number.isFinite(changes?.motorTargetNumber);
|
|
1415
|
+
if (!joint || (!isSwitched && !isAimed)) return false;
|
|
1416
|
+
if (isSwitched) setJointEnabled(joint, changes.isEnabled);
|
|
1417
|
+
if (isAimed) setJointMotor(joint, changes.motorTargetNumber);
|
|
1030
1418
|
return true;
|
|
1031
1419
|
},
|
|
1032
1420
|
/** Puts a character on one of the world's collision layers from its step (walking through his own cart while he holds it). */
|
|
@@ -1037,7 +1425,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1037
1425
|
*/
|
|
1038
1426
|
setSize(character, characterSizeName) {
|
|
1039
1427
|
const sizeIndex = characterSizeIndexByName.get(characterSizeName);
|
|
1040
|
-
if (sizeIndex === undefined) refuse("bad_argument", `setSize was given ${JSON.stringify(characterSizeName)}.`, "characterSizeName", `Use one of the world's characterSizes (${world.characterSizes.map((
|
|
1428
|
+
if (sizeIndex === undefined) refuse("bad_argument", `setSize was given ${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.`);
|
|
1041
1429
|
return setCharacterSize(character, sizeIndex, true);
|
|
1042
1430
|
},
|
|
1043
1431
|
setLayer(character, collisionLayerName) {
|
|
@@ -1229,7 +1617,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1229
1617
|
|
|
1230
1618
|
/** What a character's capsule touches, within marginM of it: the contact count, read from the batch's answer. */
|
|
1231
1619
|
const characterContactsOf = (character, x, y, z, marginM) =>
|
|
1232
|
-
raw.capsuleContacts(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, x, y + CHARACTER_SKIN_M + character.
|
|
1620
|
+
raw.capsuleContacts(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, x, y + CHARACTER_SKIN_M + character.characterSize.riseM, z, 0, 0, 0, 1, character.characterSize.radiusM, character.characterSize.halfSegmentM, marginM, groupsOf(character.layerIndex), character.rigidBody.handle, SKIPS_CHARACTERS_FLAG_NUMBER | EXCLUDES_BODY_FLAG_NUMBER);
|
|
1233
1621
|
/** The body on a timetable a contact's tag is of, or null. */
|
|
1234
1622
|
const timetableBodyOfTag = (tagNumber) => ((tagNumber & TAG_KIND_MASK_NUMBER) === BODY_TAG_NUMBER ? (bodies[tagNumber >>> 8]?.timetable ? bodies[tagNumber >>> 8] : null) : null);
|
|
1235
1623
|
|
|
@@ -1264,7 +1652,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1264
1652
|
function shiftCharacter(character, x, y, z, shiftX, shiftY, shiftZ, mover) {
|
|
1265
1653
|
const shiftM = Math.hypot(shiftX, shiftY, shiftZ);
|
|
1266
1654
|
if (shiftM < 1e-7) return;
|
|
1267
|
-
const isBlocked = raw.castShape(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, 1, character.
|
|
1655
|
+
const isBlocked = raw.castShape(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, 1, character.characterSize.radiusM, character.characterSize.halfSegmentM, 0, 0, 0, 0, 1, x, y + CHARACTER_SKIN_M + character.characterSize.riseM, z, shiftX / shiftM, shiftY / shiftM, shiftZ / shiftM, shiftM, false, groupsOf(character.layerIndex), mover.rigidBody.handle, SKIPS_CHARACTERS_FLAG_NUMBER | EXCLUDES_BODY_FLAG_NUMBER);
|
|
1268
1656
|
const freeNumber = isBlocked ? Math.max(batch.floats()[0] - CHARACTER_SKIN_M, 0) / shiftM : 1;
|
|
1269
1657
|
if (freeNumber <= 0) return;
|
|
1270
1658
|
batch.bodies.rbSetTranslation(character.rigidBody.handle, x + shiftX * freeNumber, y + shiftY * freeNumber, z + shiftZ * freeNumber, false);
|
|
@@ -1296,7 +1684,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1296
1684
|
const firstIndex = contactIndex * CONTACT_FLOAT_COUNT;
|
|
1297
1685
|
const depthM = floats[firstIndex + 6];
|
|
1298
1686
|
// Under its feet: a surface that faces up enough to stand on.
|
|
1299
|
-
if (floats[firstIndex + 4] >= character.
|
|
1687
|
+
if (floats[firstIndex + 4] >= character.characterSize.minimumStandNormalNumber) {
|
|
1300
1688
|
if (depthM > closestM) {
|
|
1301
1689
|
closestM = depthM;
|
|
1302
1690
|
ridden = body;
|
|
@@ -1340,7 +1728,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1340
1728
|
let normalZ = 0;
|
|
1341
1729
|
for (let contactIndex = 0; contactIndex < contactCount; contactIndex += 1) {
|
|
1342
1730
|
const firstIndex = contactIndex * CONTACT_FLOAT_COUNT;
|
|
1343
|
-
if (floats[firstIndex + 4] < character.
|
|
1731
|
+
if (floats[firstIndex + 4] < character.characterSize.minimumStandNormalNumber || floats[firstIndex + 6] <= closestM) continue;
|
|
1344
1732
|
const body = timetableBodyOfTag(numbers[contactIndex * CONTACT_NUMBER_COUNT]);
|
|
1345
1733
|
if (!body) continue;
|
|
1346
1734
|
closestM = floats[firstIndex + 6];
|
|
@@ -1502,6 +1890,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1502
1890
|
*/
|
|
1503
1891
|
function step(stepContext) {
|
|
1504
1892
|
const worldStepContext = { ...stepTools, ...stepContext };
|
|
1893
|
+
isBeforeSubsteps = true;
|
|
1505
1894
|
if (timetableBodies.length) {
|
|
1506
1895
|
placeTimetables(stepContext.timetableTickIndex ?? stepContext.tickIndex);
|
|
1507
1896
|
timetablesNow(characterKind.isSteppedBeforeWorld ? 0 : 1 / world.substepCount);
|
|
@@ -1509,21 +1898,29 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1509
1898
|
// What was written since the last step (the word, a teleport) moves its colliders before anything searches them.
|
|
1510
1899
|
propagateIfOwed();
|
|
1511
1900
|
layGround();
|
|
1901
|
+
if (zones.length) stepZones();
|
|
1512
1902
|
characterKind.beforeWorldStep?.(worldStepContext);
|
|
1513
1903
|
if (characterKind.isSteppedBeforeWorld) stepCharacters(worldStepContext);
|
|
1514
1904
|
driveVehicles(worldStepContext);
|
|
1905
|
+
if (behavingBodies.length) stepBodies(worldStepContext);
|
|
1906
|
+
isBeforeSubsteps = false;
|
|
1907
|
+
if (hasZoneEffects) raw.forceZones(batch.bodies, rapierWorld.gravity.x, rapierWorld.gravity.y, rapierWorld.gravity.z);
|
|
1515
1908
|
for (let substepIndex = 0; substepIndex < world.substepCount; substepIndex += 1) {
|
|
1516
1909
|
if (substepIndex > 0 && !characterKind.isSteppedBeforeWorld) placeMovedCharacters(substepIndex);
|
|
1517
1910
|
if (timetableBodies.length) aimTimetables(substepIndex);
|
|
1518
1911
|
// Every awake moving body's speed is noted (what a hit is told from), and a small quick thing looks ahead as far
|
|
1519
1912
|
// as it goes in a substep, and a little more: the engine's own continuous collision misses heightfield ground,
|
|
1520
1913
|
// so a 7 cm apple at 4 m/s would fall through it.
|
|
1914
|
+
if (hasZoneEffects) raw.slowZones(batch.bodies, substepDurationSec);
|
|
1521
1915
|
raw.beforeSubstep(batch.bodies, batch.islands, substepDurationSec);
|
|
1522
1916
|
updateVehicles();
|
|
1523
1917
|
const hitCount = stepEngine();
|
|
1524
1918
|
if (hitCount) noteHits(hitCount);
|
|
1525
1919
|
if (substepIndex === 0 && !characterKind.isSteppedBeforeWorld) stepCharacters(worldStepContext);
|
|
1526
1920
|
}
|
|
1921
|
+
if (hasZoneEffects) raw.endZoneForces(batch.bodies);
|
|
1922
|
+
if (forcedBodies.size) endForces();
|
|
1923
|
+
if (breakableJoints.size) breakJoints();
|
|
1527
1924
|
stepCount += 1;
|
|
1528
1925
|
for (const character of characters) if (character && !character.isWaiting && character.rideBodyIndex >= 0) placeRider(character);
|
|
1529
1926
|
if (tracksTouches) noteTouches();
|
|
@@ -1574,8 +1971,14 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1574
1971
|
fields.motionNumber = body.motionIndex;
|
|
1575
1972
|
fields.steerNumber = body.vehicle ? body.vehicle.steerNumber : 0;
|
|
1576
1973
|
fields.massKg = body.massKg ?? 0;
|
|
1974
|
+
if (body.behavior) ownInto(body, fields);
|
|
1577
1975
|
return fields;
|
|
1578
1976
|
}
|
|
1977
|
+
/** A body's kind's own fields, beside the piece's. */
|
|
1978
|
+
function ownInto(body, fields) {
|
|
1979
|
+
const { fieldNames } = body.behavior;
|
|
1980
|
+
for (let nameIndex = 0; nameIndex < fieldNames.length; nameIndex += 1) fields[fieldNames[nameIndex]] = body.own[fieldNames[nameIndex]];
|
|
1981
|
+
}
|
|
1579
1982
|
|
|
1580
1983
|
/** A body's fields: its place, rotation, speed and spin, its layer and how it moves now. */
|
|
1581
1984
|
function readBody(index) {
|
|
@@ -1604,6 +2007,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1604
2007
|
fields.rotation.w = rotation.w;
|
|
1605
2008
|
fields.layerNumber = body.layerIndex;
|
|
1606
2009
|
fields.motionNumber = body.motionIndex;
|
|
2010
|
+
if (body.behavior) ownInto(body, fields);
|
|
1607
2011
|
return fields;
|
|
1608
2012
|
}
|
|
1609
2013
|
if (body.settledStepCount === stepCount) return bodyFieldsFrom(body, batch.floats(), ANSWER_FLOAT_COUNT + body.settledIndex * BODY_FLOAT_COUNT, fields);
|
|
@@ -1616,6 +2020,10 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1616
2020
|
const body = bodies[index];
|
|
1617
2021
|
if (!body || body.declaredMotionIndex === 2) return;
|
|
1618
2022
|
if (fields.layerNumber !== undefined && fields.layerNumber < world.collisionLayers.length) setBodyLayer(body, fields.layerNumber);
|
|
2023
|
+
if (body.behavior) {
|
|
2024
|
+
const { fieldNames } = body.behavior;
|
|
2025
|
+
for (let nameIndex = 0; nameIndex < fieldNames.length; nameIndex += 1) if (fields[fieldNames[nameIndex]] !== undefined) body.own[fieldNames[nameIndex]] = fields[fieldNames[nameIndex]];
|
|
2026
|
+
}
|
|
1619
2027
|
// A body on a timetable takes its layer from the word, and its place from the step's index alone.
|
|
1620
2028
|
if (body.timetable) return;
|
|
1621
2029
|
if (fields.motionNumber !== undefined && fields.motionNumber >= 0 && fields.motionNumber <= 2) setBodyMotion(body, fields.motionNumber);
|
|
@@ -1739,12 +2147,13 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1739
2147
|
body.rigidBody.setAngularDamping(body.declaration.angularDampingNumber ?? nextTuning.angularDampingNumber);
|
|
1740
2148
|
body.rigidBody.wakeUp();
|
|
1741
2149
|
}
|
|
1742
|
-
for (const
|
|
2150
|
+
for (const characterSize of characterSizes) characterSize.controller?.setCharacterMass(nextTuning.characterMassKg ?? 70);
|
|
1743
2151
|
characterKind.onTuning?.(nextTuning, stepTools);
|
|
1744
2152
|
}
|
|
1745
2153
|
|
|
1746
2154
|
for (const declaration of world.bodies) addBody(declaration);
|
|
1747
2155
|
for (const declaration of world.joints) addJoint(declaration);
|
|
2156
|
+
addZones();
|
|
1748
2157
|
// Fixed bodies never move, and moving ones start where they're declared: a step settles what the engine knows of them.
|
|
1749
2158
|
const savedTimestep = rapierWorld.timestep;
|
|
1750
2159
|
rapierWorld.timestep = 0;
|
|
@@ -1776,6 +2185,23 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1776
2185
|
const joint = joints.get(jointId);
|
|
1777
2186
|
if (joint) setJointEnabled(joint, isEnabled);
|
|
1778
2187
|
},
|
|
2188
|
+
/** A joint's fields: whether it holds, whether it broke, and its motor's target. Written into the object given. */
|
|
2189
|
+
readJoint(jointId, into) {
|
|
2190
|
+
const joint = joints.get(jointId);
|
|
2191
|
+
if (!joint) return null;
|
|
2192
|
+
into.isEnabled = joint.isEnabled;
|
|
2193
|
+
into.isBroken = joint.isBroken;
|
|
2194
|
+
into.motorTargetNumber = joint.motorTargetNumber;
|
|
2195
|
+
return into;
|
|
2196
|
+
},
|
|
2197
|
+
writeJoint(jointId, fields) {
|
|
2198
|
+
const joint = joints.get(jointId);
|
|
2199
|
+
if (!joint) return;
|
|
2200
|
+
setJointEnabled(joint, fields.isEnabled);
|
|
2201
|
+
setJointBroken(joint, !fields.isEnabled && Boolean(fields.isBroken));
|
|
2202
|
+
if (fields.motorTargetNumber !== undefined) setJointMotor(joint, fields.motorTargetNumber);
|
|
2203
|
+
},
|
|
2204
|
+
jointBreakChangeCount: () => jointBreakChangeCount,
|
|
1779
2205
|
seat,
|
|
1780
2206
|
unseat,
|
|
1781
2207
|
step,
|
|
@@ -1784,7 +2210,9 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1784
2210
|
readBody,
|
|
1785
2211
|
readSteppedBody,
|
|
1786
2212
|
/** Whether the last step left this body on the wire's steps (it was awake, and nothing has written it since). */
|
|
1787
|
-
isBodyOnSteps: (index) => bodies[index]?.settledStepCount === stepCount && !bodies[index].timetable,
|
|
2213
|
+
isBodyOnSteps: (index) => bodies[index]?.settledStepCount === stepCount && !bodies[index].timetable && !bodies[index].behavior?.fieldNames.length,
|
|
2214
|
+
/** Whether the last step left a body's place, rotation, speed and spin on the wire's steps, whatever its kind's own fields. */
|
|
2215
|
+
isBodyMotionOnSteps: (index) => bodies[index]?.settledStepCount === stepCount && !bodies[index].timetable,
|
|
1788
2216
|
/** Puts the bodies on timetables where they are at a step, before the world as it stands then is asked anything. */
|
|
1789
2217
|
placeTimetables,
|
|
1790
2218
|
/** Where a body on a timetable is at a step (a whole one, or between two for what's drawn): written into { x, y, z, rotationX, rotationY, rotationZ, rotationW }. Null for a body without one. */
|
|
@@ -1798,6 +2226,11 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1798
2226
|
writeCharacter,
|
|
1799
2227
|
setTuning,
|
|
1800
2228
|
...queries,
|
|
2229
|
+
zoneOccupants,
|
|
2230
|
+
takeZoneChanges,
|
|
2231
|
+
setZoneEnabled,
|
|
2232
|
+
/** Whether a zone is on now. */
|
|
2233
|
+
isZoneEnabled: (zoneId) => zoneIndexById.has(zoneId) && raw.isZoneEnabled(zoneIndexById.get(zoneId)),
|
|
1801
2234
|
/** Lays the ground near a place for the next step, though nothing moves there: a camera looking past, a query far off. */
|
|
1802
2235
|
keepGroundNear(point) {
|
|
1803
2236
|
keptPoints.push({ x: point.x, y: point.y, z: point.z });
|
|
@@ -1816,7 +2249,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1816
2249
|
/** How many tiles of ground are laid now. */
|
|
1817
2250
|
laidGroundTileCount: () => grounds.reduce((total, ground) => total + ground.tiles.size, 0),
|
|
1818
2251
|
/** Whether a body is at rest: asleep, so nothing about it changes until something touches it. A fixed one always is. */
|
|
1819
|
-
isBodyResting: (index) => bodies[index].motionIndex === 2 || Boolean(bodies[index].timetable) || (bodies[index].motionIndex === 0 && bodies[index].rigidBody.isSleeping()),
|
|
2252
|
+
isBodyResting: (index) => !bodies[index].isOwnChanged && (bodies[index].motionIndex === 2 || Boolean(bodies[index].timetable) || (bodies[index].motionIndex === 0 && bodies[index].rigidBody.isSleeping())),
|
|
1820
2253
|
isCharacterResting(index) {
|
|
1821
2254
|
const character = characters[index];
|
|
1822
2255
|
// A step that changed the kind's own fields (taking a cart's handles, breath coming back) wakes it, so they're sent.
|
|
@@ -1863,6 +2296,103 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1863
2296
|
},
|
|
1864
2297
|
/** How many written bodies already were as written since the simulation was made, and how many weren't. */
|
|
1865
2298
|
writeCounts: () => ({ sameWriteCount, changedWriteCount }),
|
|
2299
|
+
/**
|
|
2300
|
+
* A hit in full, written onto it: where the two met (positionM), the surface each is there (surfaceName the moving
|
|
2301
|
+
* body's, otherSurfaceName the other's: one of the world's surfaceNames, or null where nothing says) and how
|
|
2302
|
+
* heavy the moving body is (massKg). Worked out only for a hit that's told, from the contact the engine still
|
|
2303
|
+
* holds; a glancing touch it kept nothing of answers the body's own place and each one's first shape.
|
|
2304
|
+
*/
|
|
2305
|
+
describeHit(hit) {
|
|
2306
|
+
const body = bodies[hit.bodyIndex];
|
|
2307
|
+
hit.positionM = null;
|
|
2308
|
+
hit.surfaceName = null;
|
|
2309
|
+
hit.otherSurfaceName = null;
|
|
2310
|
+
hit.massKg = body?.massKg ?? body?.declaration.massKg ?? 0;
|
|
2311
|
+
if (!body) return hit;
|
|
2312
|
+
for (const collider of body.colliders) {
|
|
2313
|
+
if (hit.positionM) break;
|
|
2314
|
+
rapierWorld.contactPairsWith(collider, (otherCollider) => {
|
|
2315
|
+
if (hit.positionM) return;
|
|
2316
|
+
const other = ownerByColliderHandle.get(otherCollider.handle);
|
|
2317
|
+
if (!other || (other.isCharacter ? other.index !== hit.otherCharacterIndex : other.index !== hit.otherBodyIndex)) return;
|
|
2318
|
+
rapierWorld.contactPair(collider, otherCollider, (manifold, isFlipped) => {
|
|
2319
|
+
if (hit.positionM || manifold.numSolverContacts() === 0) return;
|
|
2320
|
+
const point = manifold.solverContactPoint(0);
|
|
2321
|
+
if (!point) return;
|
|
2322
|
+
hit.positionM = { x: point.x, y: point.y, z: point.z };
|
|
2323
|
+
hit.surfaceName = surfaceOfCollider(collider, isFlipped ? manifold.subshape2() : manifold.subshape1());
|
|
2324
|
+
hit.otherSurfaceName = surfaceOfCollider(otherCollider, isFlipped ? manifold.subshape1() : manifold.subshape2());
|
|
2325
|
+
});
|
|
2326
|
+
});
|
|
2327
|
+
}
|
|
2328
|
+
if (!hit.positionM) {
|
|
2329
|
+
const bodyM = body.rigidBody.translation();
|
|
2330
|
+
hit.positionM = { x: bodyM.x, y: bodyM.y, z: bodyM.z };
|
|
2331
|
+
const otherCollider = hit.otherBodyIndex >= 0 ? bodies[hit.otherBodyIndex]?.colliders[0] : null;
|
|
2332
|
+
if (body.colliders[0]) hit.surfaceName = surfaceOfCollider(body.colliders[0], NO_TRIANGLE_INDEX);
|
|
2333
|
+
if (otherCollider) hit.otherSurfaceName = surfaceOfCollider(otherCollider, NO_TRIANGLE_INDEX);
|
|
2334
|
+
}
|
|
2335
|
+
return hit;
|
|
2336
|
+
},
|
|
2337
|
+
/**
|
|
2338
|
+
* What a moving body rests against while it moves: the touch it slides or rolls along fastest, as
|
|
2339
|
+
* { otherBodyIndex, otherCharacterIndex, positionM, surfaceName, otherSurfaceName, slideSpeedMPerSec,
|
|
2340
|
+
* rollSpeedMPerSec }, or null when it touches nothing, rests or isn't a moving body. Sliding is how fast its
|
|
2341
|
+
* surface drags across the other's at the touch; rolling is how fast it travels along it without dragging.
|
|
2342
|
+
*/
|
|
2343
|
+
bodyTouch(index) {
|
|
2344
|
+
const body = bodies[index];
|
|
2345
|
+
if (!body || body.motionIndex !== 0 || body.rigidBody.isSleeping()) return null;
|
|
2346
|
+
const linear = body.rigidBody.linvel();
|
|
2347
|
+
const angular = body.rigidBody.angvel();
|
|
2348
|
+
const centerM = body.rigidBody.worldCom();
|
|
2349
|
+
let best = null;
|
|
2350
|
+
let bestSpeedMPerSec = -1;
|
|
2351
|
+
for (const collider of body.colliders) {
|
|
2352
|
+
rapierWorld.contactPairsWith(collider, (otherCollider) => {
|
|
2353
|
+
const other = ownerByColliderHandle.get(otherCollider.handle);
|
|
2354
|
+
if (!other || (!other.isCharacter && other.index === index)) return;
|
|
2355
|
+
rapierWorld.contactPair(collider, otherCollider, (manifold, isFlipped) => {
|
|
2356
|
+
if (manifold.numSolverContacts() === 0) return;
|
|
2357
|
+
const point = manifold.solverContactPoint(0);
|
|
2358
|
+
if (!point) return;
|
|
2359
|
+
const normal = manifold.normal();
|
|
2360
|
+
// The other's speed there: a fixed thing's is none; a character's or a moving body's is its own.
|
|
2361
|
+
const otherRigidBody = other.isCharacter ? characters[other.index]?.rigidBody : bodies[other.index]?.motionIndex === 2 ? null : bodies[other.index]?.rigidBody;
|
|
2362
|
+
const otherLinear = otherRigidBody ? otherRigidBody.linvel() : NO_SPEED;
|
|
2363
|
+
const armX = point.x - centerM.x;
|
|
2364
|
+
const armY = point.y - centerM.y;
|
|
2365
|
+
const armZ = point.z - centerM.z;
|
|
2366
|
+
// The body's surface at the touch moves with its centre plus its spin round it.
|
|
2367
|
+
const centreX = linear.x - otherLinear.x;
|
|
2368
|
+
const centreY = linear.y - otherLinear.y;
|
|
2369
|
+
const centreZ = linear.z - otherLinear.z;
|
|
2370
|
+
const dragX = centreX + (angular.y * armZ - angular.z * armY);
|
|
2371
|
+
const dragY = centreY + (angular.z * armX - angular.x * armZ);
|
|
2372
|
+
const dragZ = centreZ + (angular.x * armY - angular.y * armX);
|
|
2373
|
+
// Along the surface only: what goes into or out of it is a hit or a lift, never a slide.
|
|
2374
|
+
const dragIntoMPerSec = dragX * normal.x + dragY * normal.y + dragZ * normal.z;
|
|
2375
|
+
const centreIntoMPerSec = centreX * normal.x + centreY * normal.y + centreZ * normal.z;
|
|
2376
|
+
const slideSpeedMPerSec = Math.hypot(dragX - dragIntoMPerSec * normal.x, dragY - dragIntoMPerSec * normal.y, dragZ - dragIntoMPerSec * normal.z);
|
|
2377
|
+
const travelSpeedMPerSec = Math.hypot(centreX - centreIntoMPerSec * normal.x, centreY - centreIntoMPerSec * normal.y, centreZ - centreIntoMPerSec * normal.z);
|
|
2378
|
+
const rollSpeedMPerSec = Math.max(travelSpeedMPerSec - slideSpeedMPerSec, 0);
|
|
2379
|
+
const speedMPerSec = Math.max(slideSpeedMPerSec, rollSpeedMPerSec);
|
|
2380
|
+
if (speedMPerSec <= bestSpeedMPerSec) return;
|
|
2381
|
+
bestSpeedMPerSec = speedMPerSec;
|
|
2382
|
+
best = {
|
|
2383
|
+
otherBodyIndex: other.isCharacter ? -1 : other.index,
|
|
2384
|
+
otherCharacterIndex: other.isCharacter ? other.index : -1,
|
|
2385
|
+
positionM: { x: point.x, y: point.y, z: point.z },
|
|
2386
|
+
surfaceName: surfaceOfCollider(collider, isFlipped ? manifold.subshape2() : manifold.subshape1()),
|
|
2387
|
+
otherSurfaceName: surfaceOfCollider(otherCollider, isFlipped ? manifold.subshape1() : manifold.subshape2()),
|
|
2388
|
+
slideSpeedMPerSec,
|
|
2389
|
+
rollSpeedMPerSec,
|
|
2390
|
+
};
|
|
2391
|
+
});
|
|
2392
|
+
});
|
|
2393
|
+
}
|
|
2394
|
+
return best;
|
|
2395
|
+
},
|
|
1866
2396
|
/** Hits since the last call. */
|
|
1867
2397
|
takeHits() {
|
|
1868
2398
|
const taken = hits;
|