JFLib

physics/src/sim.rs#

Source: lib/physics/src/sim.rs

sim -- rigid bodies: a world of static, kinematic and dynamic bodies that move under gravity, forces,
contacts and joints, step by step, with the same bits on every target

A step: kinematic targets become velocities; every awake body looks for others near it in the trees of
the collision World (its box grown by how far it can move in this step), each pair gets its manifolds
(manifold.rs) and the impulses of the last step's points that lie within 2 cm of the new ones; a sleeping
body that an awake one would touch wakes with its island.  Then the substeps of the soft solver
(solver.rs, joint.rs), restitution, the new poses (into the World, so queries and the character controller
see them), a sweep of fast bodies by their translation against what does not move (they stop where they first
touch it, so they do not pass through a wall between two steps; against moving kinematic bodies, a bullet also
against moving dynamic ones, with the motion relative to them, and carried on with what they hit, again only
as far as what does not move lets them) and a ray of each centre of mass along that way; the turning is
covered only by the speculative contacts, up to about a radian a step for a long body), sleep: an island (bodies linked by contacts and joints) whose
bodies all moved slower than `sleep_speed` for `time_to_sleep` sleeps until something touches it.

Determinism: everything in slot order, pairs sorted, no hash containers, no threads; the same bits on every
target as the queries (checked by physicstest's checksums).
  • enum BodyKind how a body moves

    • Static -- never (a map, a wall); moved only by [Simulation::set_iso]
    • Kinematic -- by its velocity, which only the caller sets (a door, a platform, a lift); pushes dynamic bodies, nothing pushes it
    • Dynamic -- by gravity, forces, contacts and joints
  • struct RigidBody What [Simulation::add] makes a body from. RigidBody::dynamic(shape, iso) and the with_ methods for the rest.

    • kind: BodyKind -- how it moves
    • shape: Shape -- its shape (a mesh only for a static or kinematic body)
    • iso: Iso -- where the shape's frame is
    • linear_velocity: Vec3 -- m/s, of the centre of mass
    • angular_velocity: Vec3 -- rad/s, world frame
    • density: f64 -- kg/m³ (1000: water), for the mass from the shape
    • mass: Option<MassProps> -- the mass as given instead of from the shape and density (in the shape's frame)
    • friction: f64 -- Coulomb friction; two bodies use the square root of the product of theirs (default 0.6)
    • restitution: f64 -- how much of the approach speed comes back, 0 to 1; two bodies use the larger (default 0)
    • rolling_resistance: f64 -- rolling resistance: the torque that brakes a rolling body is this times the normal force times its smallest radius; two bodies use the larger (default 0: a ball rolls on until damping stops it)
    • linear_damping: f64 -- 1/s: the velocity loses this fraction per second (default 0)
    • angular_damping: f64 -- 1/s (default 0.05)
    • gravity_scale: f64 -- how much of the simulation's gravity acts on it (default 1)
    • layers: u32 -- the layers the body is in (also what queries filter by)
    • mask: u32 -- the layers it collides with: two bodies collide when each one's mask has a layer of the other
    • sensor: bool -- it reports overlaps ([ContactEvent::SensorBegin]) and pushes nothing
    • bullet: bool -- it is swept also against moving bodies that are not bullets themselves, not only against what does not move (for small fast projectiles)
    • can_sleep: bool -- it may fall asleep (default true)
    • gyroscopic: bool -- gyroscopic forces: a body tumbling about an unstable axis flips as it does in space (Bullet's implicit step; costs a little, default off)
    • fixed_rotation: bool -- it never turns (a figure's capsule pushed around as a dynamic body; a kinematic body keeps its rotation in set_velocity and move_kinematic)
    • awake: bool -- it starts awake (default true)
    • user: u64 -- free for the caller (the World's body has it too)

impl RigidBody

  • fn new(kind: BodyKind, shape: Shape, iso: Iso) -> RigidBody a body of kind with the defaults

  • fn fixed(shape: Shape, iso: Iso) -> RigidBody a body that never moves

  • fn dynamic(shape: Shape, iso: Iso) -> RigidBody a body moved by gravity, forces, contacts and joints

  • fn kinematic(shape: Shape, iso: Iso) -> RigidBody a body moved by its velocity only

  • fn with_velocity(mut self, v: Vec3) -> RigidBody the velocity of the centre of mass at the start (m/s)

  • fn with_angular_velocity(mut self, w: Vec3) -> RigidBody the angular velocity at the start (rad/s, world frame)

  • fn with_density(mut self, density: f64) -> RigidBody the density the mass comes from (kg/m³)

  • fn with_mass(mut self, mass: MassProps) -> RigidBody the mass as given (in the shape's frame) instead of from the density

  • fn with_friction(mut self, friction: f64) -> RigidBody the friction coefficient

  • fn with_restitution(mut self, restitution: f64) -> RigidBody how much of an approach speed comes back (0 to 1)

  • fn with_rolling_resistance(mut self, c: f64) -> RigidBody the rolling resistance coefficient (0: none)

  • fn with_damping(mut self, linear: f64, angular: f64) -> RigidBody the linear and angular damping (1/s)

  • fn with_gravity_scale(mut self, scale: f64) -> RigidBody how much of the gravity acts on it

  • fn with_layers(mut self, layers: u32, mask: u32) -> RigidBody the layers it is in and those it collides with

  • fn with_user(mut self, user: u64) -> RigidBody a value for the caller (also the World body's user)

  • fn sensor(mut self) -> RigidBody reports overlaps, pushes nothing

  • fn bullet(mut self) -> RigidBody swept also against moving bodies that are not bullets, not only against what does not move

  • fn sleepless(mut self) -> RigidBody never falls asleep

  • fn gyroscopic(mut self) -> RigidBody with gyroscopic forces

  • fn fixed_rotation(mut self) -> RigidBody never turns

  • fn asleep(mut self) -> RigidBody starts asleep (until something touches it)

  • enum BodyError why [Simulation::add] refused a body

    • DynamicMesh -- a mesh can be static or kinematic, not dynamic
    • Mass -- no valid mass: the density is not positive, or the given mass properties are not those of a body
    • NotFinite -- the pose, a velocity or a parameter is not finite
    • Shape -- a sphere's or capsule's radius, a capsule's half height or a box's half size is not finite or not positive (one NaN size of a static body broke the tree of every body near it)
  • struct SimParams How the simulation steps. The defaults suit bodies from centimetres to tens of metres at 60 steps a second.

    • gravity: Vec3 -- m/s²
    • substeps: u32 -- solver substeps per step (1 to 64; default 4)
    • contact_hertz: f64 -- how stiff contacts push apart (Hz; at most a quarter of the substep rate; default 30)
    • contact_damping_ratio: f64 -- their damping ratio (default 10)
    • joint_hertz: f64 -- how stiff joints hold (Hz; at most half the substep rate; default 60)
    • joint_damping_ratio: f64 -- their damping ratio (default 2)
    • max_push_speed: f64 -- the fastest an overlap is pushed apart (m/s; default 3)
    • restitution_threshold: f64 -- slower approaches do not bounce (m/s; default 1)
    • linear_slop: f64 -- a contact touches when its gap is at most this (events, restitution), a sweep stops this far before a surface, and contact points within four times this of the last step's keep their impulses (m; default 0.005). Overlaps are pushed apart down to 0, as in Box2D v3: a slop there let stacks sink further.
    • speculative_distance: f64 -- contact points are made this far before touching, plus how far the bodies can move in the step (m; default 0.02)
    • max_speed: f64 -- no dynamic body moves faster (m/s; default 1000); kinematic bodies move as they are told
    • sleep: bool -- may islands fall asleep (default true)
    • time_to_sleep: f64 -- how long an island must be slow to fall asleep (s; default 0.5)
    • sleep_speed: f64 -- slow: every point of every body of the island slower than this (m/s; default 0.05)
    • continuous: bool -- sweep fast bodies against what does not move (default true)
  • struct BodyState what a body is now

    • kind: BodyKind -- how it moves
    • iso: Iso -- the shape's frame
    • center: Vec3 -- the centre of mass (world)
    • linear_velocity: Vec3 -- of the centre of mass (m/s)
    • angular_velocity: Vec3 -- rad/s, world frame
    • mass: f64 -- kg (0 for static and kinematic bodies)
    • awake: bool -- awake (it moves in the next step)
  • struct ContactPoint a point of a [ContactManifold]

    • point: Vec3 -- world, between the two surfaces, at the start of the last step
    • separation: f64 -- the gap then (negative: overlap)
    • normal_impulse: f64 -- the impulse along the normal in the last substep (N s; divided by the substep: the force)
  • struct ContactManifold the contact of two bodies along one normal

    • a: BodyId -- the first body (the convex one when the other is a mesh)
    • b: BodyId -- the second body
    • normal: Vec3 -- unit, from a towards b
    • triangle: u32 -- with a mesh: its lowest triangle of the manifold; else [crate::NO_TRIANGLE]
    • count: usize -- how many of points are used
    • points: [ContactPoint; MAX_POINTS] -- the points (the first count)
  • enum ContactEvent what happened between bodies in a step

    • Begin { a: BodyId, b: BodyId, point: Vec3, normal: Vec3, speed: f64 } -- a and b started to touch: where, the normal from a towards b, how fast they approached (m/s, along the normal: for the loudness of a sound)
    • End { a: BodyId, b: BodyId } -- a and b no longer touch (also when one of them was removed: then its id is dead)
    • SensorBegin { sensor: BodyId, other: BodyId } -- a body entered a sensor
    • SensorEnd { sensor: BodyId, other: BodyId } -- a body left a sensor (or one of them was removed)
  • struct SimStats counters of the last step

    • bodies: usize -- all bodies
    • awake: usize -- awake dynamic and moving kinematic bodies
    • manifolds: usize -- manifolds (also of islands asleep)
    • points: usize -- their points
    • joints: usize -- joints
    • pairs: usize -- pairs whose manifolds were computed
    • sleeping_islands: usize -- islands asleep
    • swept: usize -- bodies a sweep stopped
  • struct Simulation The rigid bodies of a game, and the collision [World] they live in (for rays, casts and the character controller; [Simulation::world]). Bodies are added and removed here, not in the World. A clone is a snapshot: it steps on to the same bits as the original (the impulses kept for the next step and the islands asleep included), for a client that rolls back and steps again.

impl Simulation

  • fn new() -> Simulation an empty simulation with the default parameters (gravity 9.81 m/s² down -Y)
  • fn with_params(params: SimParams) -> Simulation an empty simulation with these parameters
  • fn params(&self) -> &SimParams the parameters
  • fn set_params(&mut self, params: SimParams) change the parameters (they apply from the next step)
  • fn world(&self) -> &World the collision world of the bodies: rays, casts, overlaps and the character controller run on it
  • fn len(&self) -> usize the number of bodies
  • fn is_empty(&self) -> bool no bodies
  • fn add(&mut self, body: RigidBody) -> Result<BodyId, BodyError> add a body -> its id (also its id in [Simulation::world])
  • fn remove(&mut self, id: BodyId) -> bool remove a body, its joints and its contacts -> false when the id is dead. Bodies it touched wake up.
  • fn contains(&self, id: BodyId) -> bool is the id alive
  • fn state(&self, id: BodyId) -> Option<BodyState> what the body is now
  • fn iso(&self, id: BodyId) -> Option<Iso> where its shape's frame is
  • fn velocity(&self, id: BodyId) -> Option<(Vec3, Vec3)> the velocity of the centre of mass (m/s) and the angular velocity (rad/s)
  • fn velocity_at(&self, id: BodyId, point: Vec3) -> Option<Vec3> the velocity of the body's point that is at point now
  • fn mass(&self, id: BodyId) -> Option<MassProps> the mass properties (in the shape's frame; mass 0 for static and kinematic bodies)
  • fn is_awake(&self, id: BodyId) -> bool is it awake (a static body never is)
  • fn set_iso(&mut self, id: BodyId, iso: Iso) -> bool put the body somewhere else (teleport) -> false when the id is dead. It wakes, and so does what touched it.
  • fn set_velocity(&mut self, id: BodyId, linear: Vec3, angular: Vec3) -> bool set the velocities (m/s, rad/s) -> false when the id is dead; a static body has none
  • fn apply_impulse(&mut self, id: BodyId, impulse: Vec3, point: Vec3) -> bool an impulse (N s) at a point (world) of a dynamic body -> false when the id is dead
  • fn apply_angular_impulse(&mut self, id: BodyId, impulse: Vec3) -> bool an angular impulse (N m s) on a dynamic body
  • fn apply_force(&mut self, id: BodyId, force: Vec3, point: Vec3) -> bool a force (N) at a point (world) of a dynamic body during the next step (forces add up; a step clears them)
  • fn apply_torque(&mut self, id: BodyId, torque: Vec3) -> bool a torque (N m) on a dynamic body during the next step
  • fn move_kinematic(&mut self, id: BodyId, target: Iso, dt: f64) -> bool move a kinematic body to target over the next step of dt seconds (positive and finite): its velocities are set so it gets there (what it touches on the way is pushed), and it ends exactly there (one with fixed_rotation keeps its rotation). After that step it keeps those velocities until they are set again.
  • fn wake(&mut self, id: BodyId) -> bool wake a body and its island
  • fn set_material(&mut self, id: BodyId, friction: f64, restitution: f64, rolling_resistance: f64) -> bool set friction, restitution and rolling resistance
  • fn set_layers(&mut self, id: BodyId, layers: u32, mask: u32) -> bool set the layers the body is in and those it collides with
  • fn set_gravity_scale(&mut self, id: BodyId, scale: f64) -> bool set the gravity scale
  • fn add_joint(&mut self, a: BodyId, b: BodyId, frame: Iso, kind: JointKind) -> Result<JointId, JointError> a joint between a and b whose frame is frame (world) at their poses now -> its id
  • fn add_distance_joint(&mut self, a: BodyId, b: BodyId, pa: Vec3, pb: Vec3, kind: JointKind) -> Result<JointId, JointError> a distance joint between a's point pa and b's point pb (world, now) -> its id
  • fn add_joint_local(&mut self, joint: Joint) -> Result<JointId, JointError> a joint with its frames given in the bodies' own frames -> its id
  • fn remove_joint(&mut self, id: JointId) -> bool remove a joint -> false when the id is dead. Its bodies wake.
  • fn joint(&self, id: JointId) -> Option<&Joint> the joint
  • fn set_joint(&mut self, id: JointId, kind: JointKind, collide_connected: bool) -> bool change a joint's kind (limits, motor, spring) or whether its bodies collide -> false when the id is dead or the new joint is not valid; its bodies wake
  • fn joints(&self) -> impl Iterator<Item = (JointId, &Joint)> + '_ every joint with its id, by index
  • fn joint_position(&self, id: JointId) -> Option<f64> a hinge's angle (rad), a slider's position (m), a distance joint's length (m), a ball joint's twist (rad), now
  • fn joint_force(&self, id: JointId) -> Option<(Vec3, Vec3)> the force (N) and torque (N m) the joint applied to b in the last step (world; a got the opposite): for breakable joints and for measuring
  • fn step(&mut self, dt: f64) advance the simulation by dt seconds (a fixed step, 1/60 s for example); the events of the step are in [Simulation::events] afterwards
  • fn events(&self) -> &[ContactEvent] the events of the last step (contacts that began and ended, sensors entered and left)
  • fn stats(&self) -> SimStats the counters of the last step
  • fn manifolds(&self) -> impl Iterator<Item = ContactManifold> + '_ the manifolds of the last step (also of islands asleep), by body

Source: docs/API.md in the JFLib repository.