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 BodyKindhow a body movesStatic-- 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 itDynamic-- by gravity, forces, contacts and joints
struct RigidBodyWhat [Simulation::add] makes a body from.RigidBody::dynamic(shape, iso)and thewith_methods for the rest.kind: BodyKind-- how it movesshape: Shape-- its shape (a mesh only for a static or kinematic body)iso: Iso-- where the shape's frame islinear_velocity: Vec3-- m/s, of the centre of massangular_velocity: Vec3-- rad/s, world framedensity: f64-- kg/m³ (1000: water), for the mass from the shapemass: 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 othersensor: bool-- it reports overlaps ([ContactEvent::SensorBegin]) and pushes nothingbullet: 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 inset_velocityandmove_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) -> RigidBodya body ofkindwith the defaultsfn fixed(shape: Shape, iso: Iso) -> RigidBodya body that never movesfn dynamic(shape: Shape, iso: Iso) -> RigidBodya body moved by gravity, forces, contacts and jointsfn kinematic(shape: Shape, iso: Iso) -> RigidBodya body moved by its velocity onlyfn with_velocity(mut self, v: Vec3) -> RigidBodythe velocity of the centre of mass at the start (m/s)fn with_angular_velocity(mut self, w: Vec3) -> RigidBodythe angular velocity at the start (rad/s, world frame)fn with_density(mut self, density: f64) -> RigidBodythe density the mass comes from (kg/m³)fn with_mass(mut self, mass: MassProps) -> RigidBodythe mass as given (in the shape's frame) instead of from the densityfn with_friction(mut self, friction: f64) -> RigidBodythe friction coefficientfn with_restitution(mut self, restitution: f64) -> RigidBodyhow much of an approach speed comes back (0 to 1)fn with_rolling_resistance(mut self, c: f64) -> RigidBodythe rolling resistance coefficient (0: none)fn with_damping(mut self, linear: f64, angular: f64) -> RigidBodythe linear and angular damping (1/s)fn with_gravity_scale(mut self, scale: f64) -> RigidBodyhow much of the gravity acts on itfn with_layers(mut self, layers: u32, mask: u32) -> RigidBodythe layers it is in and those it collides withfn with_user(mut self, user: u64) -> RigidBodya value for the caller (also the World body'suser)fn sensor(mut self) -> RigidBodyreports overlaps, pushes nothingfn bullet(mut self) -> RigidBodyswept also against moving bodies that are not bullets, not only against what does not movefn sleepless(mut self) -> RigidBodynever falls asleepfn gyroscopic(mut self) -> RigidBodywith gyroscopic forcesfn fixed_rotation(mut self) -> RigidBodynever turnsfn asleep(mut self) -> RigidBodystarts asleep (until something touches it)enum BodyErrorwhy [Simulation::add] refused a bodyDynamicMesh-- a mesh can be static or kinematic, not dynamicMass-- no valid mass: the density is not positive, or the given mass properties are not those of a bodyNotFinite-- the pose, a velocity or a parameter is not finiteShape-- 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 SimParamsHow 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 toldsleep: 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 BodyStatewhat a body is nowkind: BodyKind-- how it movesiso: Iso-- the shape's framecenter: Vec3-- the centre of mass (world)linear_velocity: Vec3-- of the centre of mass (m/s)angular_velocity: Vec3-- rad/s, world framemass: f64-- kg (0 for static and kinematic bodies)awake: bool-- awake (it moves in the next step)
struct ContactPointa point of a [ContactManifold]point: Vec3-- world, between the two surfaces, at the start of the last stepseparation: 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 ContactManifoldthe contact of two bodies along one normala: BodyId-- the first body (the convex one when the other is a mesh)b: BodyId-- the second bodynormal: Vec3-- unit, from a towards btriangle: u32-- with a mesh: its lowest triangle of the manifold; else [crate::NO_TRIANGLE]count: usize-- how many ofpointsare usedpoints: [ContactPoint; MAX_POINTS]-- the points (the firstcount)
enum ContactEventwhat happened between bodies in a stepBegin { 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 sensorSensorEnd { sensor: BodyId, other: BodyId }-- a body left a sensor (or one of them was removed)
struct SimStatscounters of the last stepbodies: usize-- all bodiesawake: usize-- awake dynamic and moving kinematic bodiesmanifolds: usize-- manifolds (also of islands asleep)points: usize-- their pointsjoints: usize-- jointspairs: usize-- pairs whose manifolds were computedsleeping_islands: usize-- islands asleepswept: usize-- bodies a sweep stopped
struct SimulationThe 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() -> Simulationan empty simulation with the default parameters (gravity 9.81 m/s² down -Y)fn with_params(params: SimParams) -> Simulationan empty simulation with these parametersfn params(&self) -> &SimParamsthe parametersfn set_params(&mut self, params: SimParams)change the parameters (they apply from the next step)fn world(&self) -> &Worldthe collision world of the bodies: rays, casts, overlaps and the character controller run on itfn len(&self) -> usizethe number of bodiesfn is_empty(&self) -> boolno bodiesfn 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) -> boolremove a body, its joints and its contacts -> false when the id is dead. Bodies it touched wake up.fn contains(&self, id: BodyId) -> boolis the id alivefn state(&self, id: BodyId) -> Option<BodyState>what the body is nowfn iso(&self, id: BodyId) -> Option<Iso>where its shape's frame isfn 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 atpointnowfn 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) -> boolis it awake (a static body never is)fn set_iso(&mut self, id: BodyId, iso: Iso) -> boolput 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) -> boolset the velocities (m/s, rad/s) -> false when the id is dead; a static body has nonefn apply_impulse(&mut self, id: BodyId, impulse: Vec3, point: Vec3) -> boolan impulse (N s) at a point (world) of a dynamic body -> false when the id is deadfn apply_angular_impulse(&mut self, id: BodyId, impulse: Vec3) -> boolan angular impulse (N m s) on a dynamic bodyfn apply_force(&mut self, id: BodyId, force: Vec3, point: Vec3) -> boola 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) -> boola torque (N m) on a dynamic body during the next stepfn move_kinematic(&mut self, id: BodyId, target: Iso, dt: f64) -> boolmove a kinematic body totargetover the next step ofdtseconds (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 withfixed_rotationkeeps its rotation). After that step it keeps those velocities until they are set again.fn wake(&mut self, id: BodyId) -> boolwake a body and its islandfn set_material(&mut self, id: BodyId, friction: f64, restitution: f64, rolling_resistance: f64) -> boolset friction, restitution and rolling resistancefn set_layers(&mut self, id: BodyId, layers: u32, mask: u32) -> boolset the layers the body is in and those it collides withfn set_gravity_scale(&mut self, id: BodyId, scale: f64) -> boolset the gravity scalefn add_joint(&mut self, a: BodyId, b: BodyId, frame: Iso, kind: JointKind) -> Result<JointId, JointError>a joint between a and b whose frame isframe(world) at their poses now -> its idfn add_distance_joint(&mut self, a: BodyId, b: BodyId, pa: Vec3, pb: Vec3, kind: JointKind) -> Result<JointId, JointError>a distance joint between a's pointpaand b's pointpb(world, now) -> its idfn add_joint_local(&mut self, joint: Joint) -> Result<JointId, JointError>a joint with its frames given in the bodies' own frames -> its idfn remove_joint(&mut self, id: JointId) -> boolremove a joint -> false when the id is dead. Its bodies wake.fn joint(&self, id: JointId) -> Option<&Joint>the jointfn set_joint(&mut self, id: JointId, kind: JointKind, collide_connected: bool) -> boolchange 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 wakefn joints(&self) -> impl Iterator<Item = (JointId, &Joint)> + '_every joint with its id, by indexfn 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), nowfn 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 measuringfn step(&mut self, dt: f64)advance the simulation bydtseconds (a fixed step, 1/60 s for example); the events of the step are in [Simulation::events] afterwardsfn events(&self) -> &[ContactEvent]the events of the last step (contacts that began and ended, sensors entered and left)fn stats(&self) -> SimStatsthe counters of the last stepfn manifolds(&self) -> impl Iterator<Item = ContactManifold> + '_the manifolds of the last step (also of islands asleep), by body