Add design persistence, world rendering, metrics overlay and logs
M3: STL/OBJ import with mesh validation, mass/COM/inertia, material database, RON scene with content-addressed blobs and v0->v1 migration. M4: deterministic heightmap terrain, trimesh colliders, wgpu renderer with instancing and depth, winit app with 1 kHz physics, fly camera, on-screen metrics overlay and per-frame CSV/dev logs. Docs: UI, logging, network and headless CLI plans.
This commit is contained in:
parent
79928b645b
commit
93075ab1fd
107 changed files with 14785 additions and 46 deletions
|
|
@ -11,6 +11,7 @@ workspace = true
|
|||
|
||||
[dependencies]
|
||||
fabrilis-core = { path = "../core" }
|
||||
rapier3d-f64 = { version = "0.36", features = ["enhanced-determinism"] }
|
||||
|
||||
[build-dependencies]
|
||||
fabrilis-limits = { path = "../../tools/limits" }
|
||||
|
|
|
|||
|
|
@ -1 +1,149 @@
|
|||
//! fabrilis-physics :: backend - stub (see docs/ARCHITECTURE.md)
|
||||
//! The engine-agnostic physics contract.
|
||||
//!
|
||||
//! Subsystems above physics talk to this trait, never to Rapier directly. All
|
||||
//! values cross the boundary in SI units and the project's Z-up world frame
|
||||
//! (docs/COORDINATES.md).
|
||||
|
||||
use fabrilis_core::time::SimDelta;
|
||||
use fabrilis_core::units::{Kilograms, Radians};
|
||||
use fabrilis_core::vec::{Quat, Transform, Vec3};
|
||||
|
||||
use crate::joints::{JointId, RevoluteDesc};
|
||||
|
||||
/// A handle to a body owned by a [`PhysicsBackend`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct BodyId(pub(crate) u32);
|
||||
|
||||
impl BodyId {
|
||||
/// The dense index behind the handle, for snapshots and diagnostics.
|
||||
#[must_use]
|
||||
pub const fn index(self) -> u32 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a body is immovable or integrated by the solver.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BodyKind {
|
||||
/// Static geometry: infinite mass, never moves.
|
||||
Fixed,
|
||||
/// Simulated body: moves under gravity, contacts and joint reactions.
|
||||
Dynamic,
|
||||
}
|
||||
|
||||
/// The collision shape of a body.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum ShapeDesc {
|
||||
/// A box aligned with the body frame, given by its half extents.
|
||||
Cuboid {
|
||||
/// Half the box size along each local axis, metres.
|
||||
half_extents: Vec3,
|
||||
},
|
||||
/// A sphere centred on the body frame.
|
||||
Ball {
|
||||
/// Radius, metres.
|
||||
radius: f64,
|
||||
},
|
||||
}
|
||||
|
||||
/// A static triangle mesh, used for terrain.
|
||||
///
|
||||
/// The mesh owns its vertex buffers, so unlike [`ShapeDesc`] it is not `Copy`;
|
||||
/// it is passed to [`PhysicsBackend::add_trimesh`] by value. Dynamic trimesh
|
||||
/// bodies are out of scope for now: the created body is always fixed.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct TrimeshDesc {
|
||||
/// Mesh vertices in the local frame of the body, metres.
|
||||
pub vertices: Vec<Vec3>,
|
||||
/// Zero-based triangles indexing `vertices`, one triangle per entry.
|
||||
pub indices: Vec<[u32; 3]>,
|
||||
/// World position of the local frame, metres.
|
||||
pub position: Vec3,
|
||||
/// World orientation of the local frame.
|
||||
pub rotation: Quat,
|
||||
}
|
||||
|
||||
/// Everything needed to create a body.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct BodyDesc {
|
||||
/// Fixed or dynamic.
|
||||
pub kind: BodyKind,
|
||||
/// Total mass, kilograms; ignored for fixed bodies.
|
||||
pub mass: Kilograms,
|
||||
/// Collision shape.
|
||||
pub shape: ShapeDesc,
|
||||
/// Initial world position, metres.
|
||||
pub position: Vec3,
|
||||
/// Initial orientation.
|
||||
pub rotation: Quat,
|
||||
}
|
||||
|
||||
impl BodyDesc {
|
||||
/// A dynamic body at rest with no rotation.
|
||||
#[must_use]
|
||||
pub fn dynamic(shape: ShapeDesc, mass: Kilograms, position: Vec3) -> Self {
|
||||
Self {
|
||||
kind: BodyKind::Dynamic,
|
||||
mass,
|
||||
shape,
|
||||
position,
|
||||
rotation: Quat::IDENTITY,
|
||||
}
|
||||
}
|
||||
|
||||
/// A fixed body at rest with no rotation.
|
||||
#[must_use]
|
||||
pub fn fixed(shape: ShapeDesc, position: Vec3) -> Self {
|
||||
Self {
|
||||
kind: BodyKind::Fixed,
|
||||
mass: Kilograms::ZERO,
|
||||
shape,
|
||||
position,
|
||||
rotation: Quat::IDENTITY,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The simulation operations available to the rest of the engine.
|
||||
pub trait PhysicsBackend {
|
||||
/// Adds a body and returns its handle.
|
||||
fn add_body(&mut self, desc: BodyDesc) -> BodyId;
|
||||
|
||||
/// Adds a static triangle mesh (terrain) and returns its handle.
|
||||
///
|
||||
/// The mesh is fixed terrain: it never moves and is not integrated by the
|
||||
/// solver. `vertices` are in the local frame; `position` and `rotation`
|
||||
/// place that frame in the Z-up world. Indices are zero-based triangles;
|
||||
/// winding follows the right-hand rule (counter-clockwise seen from the
|
||||
/// front), while terrain contacts themselves are two-sided.
|
||||
///
|
||||
/// Returns `None` for an empty mesh, an empty index list, out-of-range
|
||||
/// indices, non-finite vertices or placement, or a degenerate/zero-area
|
||||
/// mesh that Rapier rejects. Invalid input never panics and leaves the
|
||||
/// backend usable. Dynamic trimesh bodies are out of scope for now.
|
||||
fn add_trimesh(&mut self, desc: TrimeshDesc) -> Option<BodyId>;
|
||||
|
||||
/// Adds a revolute joint between two existing bodies and returns its handle.
|
||||
fn add_revolute(&mut self, desc: RevoluteDesc) -> JointId;
|
||||
|
||||
/// Drives a joint towards `target` with a spring-like position motor.
|
||||
///
|
||||
/// `stiffness` and `damping` use the backend's motor units; unknown joints are
|
||||
/// ignored. See [`RapierBackend`](crate::rapier::RapierBackend) for the model.
|
||||
fn set_motor_position(&mut self, joint: JointId, target: Radians, stiffness: f64, damping: f64);
|
||||
|
||||
/// Sets the world-frame torque for the next step, N·m; replaces the previous one.
|
||||
///
|
||||
/// A controller calls this every step; unknown bodies are ignored.
|
||||
fn apply_torque(&mut self, body: BodyId, torque: Vec3);
|
||||
|
||||
/// Advances the simulation by `dt`.
|
||||
fn step(&mut self, dt: SimDelta);
|
||||
|
||||
/// The current world transform of a body, or `None` for an unknown handle.
|
||||
fn body_transform(&self, id: BodyId) -> Option<Transform>;
|
||||
|
||||
/// The current angle of a revolute joint in `[-π, π]`, or `None` for an
|
||||
/// unknown handle.
|
||||
fn joint_angle(&self, id: JointId) -> Option<Radians>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1 +1,49 @@
|
|||
//! fabrilis-physics :: joints - stub (see docs/ARCHITECTURE.md)
|
||||
//! Joint descriptions shared by every backend.
|
||||
|
||||
use fabrilis_core::vec::Vec3;
|
||||
|
||||
use crate::backend::BodyId;
|
||||
|
||||
/// A handle to a joint owned by a [`PhysicsBackend`](crate::backend::PhysicsBackend).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct JointId(pub(crate) u32);
|
||||
|
||||
impl JointId {
|
||||
/// The dense index behind the handle, for snapshots and diagnostics.
|
||||
#[must_use]
|
||||
pub const fn index(self) -> u32 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// A hinge that allows only relative rotation around `axis`.
|
||||
///
|
||||
/// `anchor_a` and `anchor_b` are the same physical point expressed in each
|
||||
/// body's local frame, so a correct joint starts with the anchors coincident.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct RevoluteDesc {
|
||||
/// The body the joint frame is measured from.
|
||||
pub body_a: BodyId,
|
||||
/// The body that rotates relative to `body_a`.
|
||||
pub body_b: BodyId,
|
||||
/// Hinge axis in the local frames of both bodies; normalized by the backend.
|
||||
pub axis: Vec3,
|
||||
/// Hinge point in the local frame of `body_a`, metres.
|
||||
pub anchor_a: Vec3,
|
||||
/// Hinge point in the local frame of `body_b`, metres.
|
||||
pub anchor_b: Vec3,
|
||||
}
|
||||
|
||||
impl RevoluteDesc {
|
||||
/// A hinge with the given bodies, axis and local anchors.
|
||||
#[must_use]
|
||||
pub fn new(body_a: BodyId, body_b: BodyId, axis: Vec3, anchor_a: Vec3, anchor_b: Vec3) -> Self {
|
||||
Self {
|
||||
body_a,
|
||||
body_b,
|
||||
axis,
|
||||
anchor_a,
|
||||
anchor_b,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,3 +3,7 @@ pub mod backend;
|
|||
pub mod contact;
|
||||
pub mod joints;
|
||||
pub mod rapier;
|
||||
|
||||
pub use backend::{BodyDesc, BodyId, BodyKind, PhysicsBackend, ShapeDesc, TrimeshDesc};
|
||||
pub use joints::{JointId, RevoluteDesc};
|
||||
pub use rapier::RapierBackend;
|
||||
|
|
|
|||
|
|
@ -1 +1,268 @@
|
|||
//! fabrilis-physics :: rapier - stub (see docs/ARCHITECTURE.md)
|
||||
//! Rapier adapter: translates the project's SI/Z-up descriptions into Rapier
|
||||
//! handles and copies state back. See docs/DETERMINISM.md for the Rapier
|
||||
//! determinism caveats.
|
||||
|
||||
use fabrilis_core::time::SimDelta;
|
||||
use fabrilis_core::units::{Kilograms, Radians};
|
||||
use fabrilis_core::vec::{Quat, Transform, Vec3};
|
||||
use rapier3d_f64::dynamics::{
|
||||
CCDSolver, ImpulseJointHandle, ImpulseJointSet, IntegrationParameters, IslandManager,
|
||||
JointAxis, MultibodyJointSet, RevoluteJoint, RevoluteJointBuilder, RigidBodyBuilder,
|
||||
RigidBodyHandle, RigidBodySet, SoftBodySet,
|
||||
};
|
||||
use rapier3d_f64::geometry::{ColliderBuilder, ColliderSet, DefaultBroadPhase, NarrowPhase};
|
||||
use rapier3d_f64::math::{Pose, Rotation, Vector};
|
||||
use rapier3d_f64::pipeline::PhysicsPipeline;
|
||||
|
||||
use crate::backend::{BodyDesc, BodyId, BodyKind, PhysicsBackend, ShapeDesc, TrimeshDesc};
|
||||
use crate::joints::{JointId, RevoluteDesc};
|
||||
|
||||
/// Standard gravity in the project's Z-up world frame, m/s².
|
||||
pub const EARTH_GRAVITY: Vec3 = Vec3::new(0.0, 0.0, -9.81);
|
||||
|
||||
/// A Rapier world behind the [`PhysicsBackend`] trait.
|
||||
pub struct RapierBackend {
|
||||
gravity: Vector,
|
||||
integration: IntegrationParameters,
|
||||
pipeline: PhysicsPipeline,
|
||||
islands: IslandManager,
|
||||
broad_phase: DefaultBroadPhase,
|
||||
narrow_phase: NarrowPhase,
|
||||
bodies: RigidBodySet,
|
||||
colliders: ColliderSet,
|
||||
joints: ImpulseJointSet,
|
||||
multibody_joints: MultibodyJointSet,
|
||||
soft_bodies: SoftBodySet,
|
||||
ccd_solver: CCDSolver,
|
||||
body_handles: Vec<RigidBodyHandle>,
|
||||
joint_handles: Vec<Option<ImpulseJointHandle>>,
|
||||
}
|
||||
|
||||
impl RapierBackend {
|
||||
/// A world with standard gravity, Z down 9.81 m/s².
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self::with_gravity(EARTH_GRAVITY)
|
||||
}
|
||||
|
||||
/// A world with an explicit gravity vector, m/s².
|
||||
#[must_use]
|
||||
pub fn with_gravity(gravity: Vec3) -> Self {
|
||||
Self {
|
||||
gravity: vector(gravity),
|
||||
integration: IntegrationParameters::default(),
|
||||
pipeline: PhysicsPipeline::new(),
|
||||
islands: IslandManager::new(),
|
||||
broad_phase: DefaultBroadPhase::default(),
|
||||
narrow_phase: NarrowPhase::new(),
|
||||
bodies: RigidBodySet::new(),
|
||||
colliders: ColliderSet::new(),
|
||||
joints: ImpulseJointSet::new(),
|
||||
multibody_joints: MultibodyJointSet::new(),
|
||||
soft_bodies: SoftBodySet::new(),
|
||||
ccd_solver: CCDSolver::new(),
|
||||
body_handles: Vec::new(),
|
||||
joint_handles: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn body_handle(&self, id: BodyId) -> Option<RigidBodyHandle> {
|
||||
self.body_handles.get(id.0 as usize).copied()
|
||||
}
|
||||
|
||||
fn joint_handle(&self, id: JointId) -> Option<ImpulseJointHandle> {
|
||||
self.joint_handles.get(id.0 as usize).copied().flatten()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RapierBackend {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl PhysicsBackend for RapierBackend {
|
||||
fn add_body(&mut self, desc: BodyDesc) -> BodyId {
|
||||
let builder = match desc.kind {
|
||||
BodyKind::Fixed => RigidBodyBuilder::fixed(),
|
||||
BodyKind::Dynamic => RigidBodyBuilder::dynamic(),
|
||||
};
|
||||
let pose = Pose::from_parts(vector(desc.position), rotation(desc.rotation));
|
||||
let handle = self.bodies.insert(builder.pose(pose).build());
|
||||
let collider = collider(desc.shape, desc.mass);
|
||||
self.colliders
|
||||
.insert_with_parent(collider, handle, &mut self.bodies);
|
||||
let id = BodyId(self.body_handles.len() as u32);
|
||||
self.body_handles.push(handle);
|
||||
id
|
||||
}
|
||||
|
||||
fn add_trimesh(&mut self, desc: TrimeshDesc) -> Option<BodyId> {
|
||||
// Frame placement first: a non-finite pose must be rejected before any
|
||||
// Rapier data exists. Rapier normalizes the quaternion itself; a zero
|
||||
// quaternion falls back to the identity.
|
||||
if !desc.position.is_finite() || !quat_is_finite(desc.rotation) {
|
||||
return None;
|
||||
}
|
||||
let (vertices, indices) = trimesh_buffers(desc.vertices, desc.indices)?;
|
||||
// Rapier rejects an empty index list; other degenerate meshes are
|
||||
// reported through the error result instead of panicking.
|
||||
let collider = ColliderBuilder::trimesh(vertices, indices).ok()?;
|
||||
let pose = Pose::from_parts(vector(desc.position), rotation(desc.rotation));
|
||||
let handle = self
|
||||
.bodies
|
||||
.insert(RigidBodyBuilder::fixed().pose(pose).build());
|
||||
self.colliders
|
||||
.insert_with_parent(collider, handle, &mut self.bodies);
|
||||
let id = BodyId(self.body_handles.len() as u32);
|
||||
self.body_handles.push(handle);
|
||||
Some(id)
|
||||
}
|
||||
|
||||
fn add_revolute(&mut self, desc: RevoluteDesc) -> JointId {
|
||||
let id = JointId(self.joint_handles.len() as u32);
|
||||
let Some(body_a) = self.body_handle(desc.body_a) else {
|
||||
self.joint_handles.push(None);
|
||||
return id;
|
||||
};
|
||||
let Some(body_b) = self.body_handle(desc.body_b) else {
|
||||
self.joint_handles.push(None);
|
||||
return id;
|
||||
};
|
||||
let axis = desc.axis.normalized().unwrap_or(Vec3::Z);
|
||||
// Linked bodies often overlap around a hinge, so contacts between the pair
|
||||
// are disabled; both still collide with the rest of the world.
|
||||
let joint = RevoluteJointBuilder::new(vector(axis))
|
||||
.local_anchor1(vector(desc.anchor_a))
|
||||
.local_anchor2(vector(desc.anchor_b))
|
||||
.contacts_enabled(false);
|
||||
let handle = self.joints.insert(body_a, body_b, joint, true);
|
||||
self.joint_handles.push(Some(handle));
|
||||
id
|
||||
}
|
||||
|
||||
fn set_motor_position(
|
||||
&mut self,
|
||||
joint: JointId,
|
||||
target: Radians,
|
||||
stiffness: f64,
|
||||
damping: f64,
|
||||
) {
|
||||
let Some(handle) = self.joint_handle(joint) else {
|
||||
return;
|
||||
};
|
||||
let Some(entry) = self.joints.get_mut(handle, true) else {
|
||||
return;
|
||||
};
|
||||
entry
|
||||
.data
|
||||
.set_motor_position(JointAxis::AngX, target.get(), stiffness, damping);
|
||||
}
|
||||
|
||||
fn apply_torque(&mut self, body: BodyId, torque: Vec3) {
|
||||
let Some(handle) = self.body_handle(body) else {
|
||||
return;
|
||||
};
|
||||
if let Some(entry) = self.bodies.get_mut(handle) {
|
||||
// Rapier keeps user torques until they are cleared, so this sets the torque
|
||||
// for the coming step instead of accumulating it every step.
|
||||
entry.reset_torques(true);
|
||||
entry.add_torque(vector(torque), true);
|
||||
}
|
||||
}
|
||||
|
||||
fn step(&mut self, dt: SimDelta) {
|
||||
let seconds = dt.as_seconds().get();
|
||||
if seconds <= 0.0 {
|
||||
return;
|
||||
}
|
||||
self.integration.dt = seconds;
|
||||
self.pipeline.step(
|
||||
self.gravity,
|
||||
&self.integration,
|
||||
&mut self.islands,
|
||||
&mut self.broad_phase,
|
||||
&mut self.narrow_phase,
|
||||
&mut self.bodies,
|
||||
&mut self.colliders,
|
||||
&mut self.joints,
|
||||
&mut self.multibody_joints,
|
||||
&mut self.soft_bodies,
|
||||
&mut self.ccd_solver,
|
||||
&(),
|
||||
&(),
|
||||
);
|
||||
}
|
||||
|
||||
fn body_transform(&self, id: BodyId) -> Option<Transform> {
|
||||
let body = self.bodies.get(self.body_handle(id)?)?;
|
||||
let translation = body.translation();
|
||||
let rotation = body.rotation();
|
||||
Some(Transform::new(
|
||||
Vec3::new(translation.x, translation.y, translation.z),
|
||||
Quat::new(rotation.w, rotation.x, rotation.y, rotation.z),
|
||||
))
|
||||
}
|
||||
|
||||
fn joint_angle(&self, id: JointId) -> Option<Radians> {
|
||||
let joint = self.joints.get(self.joint_handle(id)?)?;
|
||||
let body_a = self.bodies.get(joint.body1())?;
|
||||
let body_b = self.bodies.get(joint.body2())?;
|
||||
let revolute = RevoluteJoint { data: joint.data };
|
||||
Some(Radians::new(
|
||||
revolute.angle(body_a.rotation(), body_b.rotation()),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn vector(v: Vec3) -> Vector {
|
||||
Vector::new(v.x, v.y, v.z)
|
||||
}
|
||||
|
||||
fn rotation(q: Quat) -> Rotation {
|
||||
let unit = q.normalize().unwrap_or(Quat::IDENTITY);
|
||||
Rotation::from_xyzw(unit.x, unit.y, unit.z, unit.w)
|
||||
}
|
||||
|
||||
fn collider(shape: ShapeDesc, mass: Kilograms) -> ColliderBuilder {
|
||||
let builder = match shape {
|
||||
ShapeDesc::Cuboid { half_extents } => {
|
||||
ColliderBuilder::cuboid(half_extents.x, half_extents.y, half_extents.z)
|
||||
}
|
||||
ShapeDesc::Ball { radius } => ColliderBuilder::ball(radius),
|
||||
};
|
||||
builder.mass(mass.get())
|
||||
}
|
||||
|
||||
fn quat_is_finite(q: Quat) -> bool {
|
||||
q.w.is_finite() && q.x.is_finite() && q.y.is_finite() && q.z.is_finite()
|
||||
}
|
||||
|
||||
/// Validates a trimesh and converts it to Rapier's point type.
|
||||
///
|
||||
/// Rapier does not check index bounds while building its BVH and would panic or
|
||||
/// read garbage on a bad index, so every index is validated here first. A mesh
|
||||
/// needs at least one triangle, hence at least three vertices.
|
||||
fn trimesh_buffers(
|
||||
vertices: Vec<Vec3>,
|
||||
indices: Vec<[u32; 3]>,
|
||||
) -> Option<(Vec<Vector>, Vec<[u32; 3]>)> {
|
||||
if indices.is_empty() || vertices.len() < 3 {
|
||||
return None;
|
||||
}
|
||||
let vertex_count = u32::try_from(vertices.len()).ok()?;
|
||||
if indices.iter().flatten().any(|&index| index >= vertex_count) {
|
||||
return None;
|
||||
}
|
||||
let mut points = Vec::with_capacity(vertices.len());
|
||||
for vertex in vertices {
|
||||
if !vertex.is_finite() {
|
||||
return None;
|
||||
}
|
||||
points.push(vector(vertex));
|
||||
}
|
||||
Some((points, indices))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
|
|
|||
285
crates/physics/src/rapier/tests.rs
Normal file
285
crates/physics/src/rapier/tests.rs
Normal file
|
|
@ -0,0 +1,285 @@
|
|||
use super::*;
|
||||
use crate::backend::{BodyDesc, BodyId, PhysicsBackend, ShapeDesc, TrimeshDesc};
|
||||
use crate::joints::{JointId, RevoluteDesc};
|
||||
use fabrilis_core::time::SimDelta;
|
||||
use fabrilis_core::units::{Kilograms, Radians};
|
||||
use fabrilis_core::vec::{Quat, Vec3};
|
||||
|
||||
fn step_at(hz: u64) -> SimDelta {
|
||||
SimDelta::from_hz(hz).expect("1 kHz divides a second evenly")
|
||||
}
|
||||
|
||||
fn build_motor_world() -> (RapierBackend, BodyId, JointId) {
|
||||
let mut world = RapierBackend::new();
|
||||
let base = world.add_body(BodyDesc::fixed(
|
||||
ShapeDesc::Cuboid {
|
||||
half_extents: Vec3::new(0.05, 0.05, 0.05),
|
||||
},
|
||||
Vec3::ZERO,
|
||||
));
|
||||
let link = world.add_body(BodyDesc::dynamic(
|
||||
ShapeDesc::Cuboid {
|
||||
half_extents: Vec3::new(0.5, 0.05, 0.05),
|
||||
},
|
||||
Kilograms::new(1.0),
|
||||
Vec3::new(0.5, 0.0, 0.0),
|
||||
));
|
||||
let joint = world.add_revolute(RevoluteDesc::new(
|
||||
base,
|
||||
link,
|
||||
Vec3::Z,
|
||||
Vec3::ZERO,
|
||||
Vec3::new(-0.5, 0.0, 0.0),
|
||||
));
|
||||
world.set_motor_position(joint, Radians::new(1.0), 100.0, 20.0);
|
||||
(world, link, joint)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn free_body_falls_under_gravity() {
|
||||
let mut world = RapierBackend::new();
|
||||
let body = world.add_body(BodyDesc::dynamic(
|
||||
ShapeDesc::Ball { radius: 0.2 },
|
||||
Kilograms::new(1.0),
|
||||
Vec3::new(0.0, 0.0, 10.0),
|
||||
));
|
||||
let dt = step_at(1_000);
|
||||
let steps = 100;
|
||||
for _ in 0..steps {
|
||||
world.step(dt);
|
||||
}
|
||||
let z = world
|
||||
.body_transform(body)
|
||||
.expect("the body exists")
|
||||
.position
|
||||
.z;
|
||||
let t = (steps as f64) * dt.as_seconds().get();
|
||||
let expected = 10.0 - 0.5 * EARTH_GRAVITY.z.abs() * t * t;
|
||||
assert!(z < 10.0);
|
||||
assert!(
|
||||
(z - expected).abs() < 1e-3,
|
||||
"z = {z}, expected = {expected}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn motor_reaches_target_angle() {
|
||||
let (mut world, _link, joint) = build_motor_world();
|
||||
let dt = step_at(1_000);
|
||||
for _ in 0..2_000 {
|
||||
world.step(dt);
|
||||
}
|
||||
let angle = world.joint_angle(joint).expect("the joint exists");
|
||||
assert!((angle.get() - 1.0).abs() <= 0.02, "angle = {}", angle.get());
|
||||
for _ in 0..200 {
|
||||
world.step(dt);
|
||||
let settled = world.joint_angle(joint).expect("the joint exists");
|
||||
assert!(
|
||||
(settled.get() - 1.0).abs() <= 0.02,
|
||||
"settled angle = {}",
|
||||
settled.get()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identical_worlds_match_bitwise() {
|
||||
let (mut first, first_body, first_joint) = build_motor_world();
|
||||
let (mut second, second_body, second_joint) = build_motor_world();
|
||||
let dt = step_at(1_000);
|
||||
for _ in 0..500 {
|
||||
first.step(dt);
|
||||
second.step(dt);
|
||||
}
|
||||
let a = first.body_transform(first_body).expect("the body exists");
|
||||
let b = second.body_transform(second_body).expect("the body exists");
|
||||
assert_eq!(a.position.x.to_bits(), b.position.x.to_bits());
|
||||
assert_eq!(a.position.y.to_bits(), b.position.y.to_bits());
|
||||
assert_eq!(a.position.z.to_bits(), b.position.z.to_bits());
|
||||
assert_eq!(a.rotation.w.to_bits(), b.rotation.w.to_bits());
|
||||
assert_eq!(a.rotation.x.to_bits(), b.rotation.x.to_bits());
|
||||
assert_eq!(a.rotation.y.to_bits(), b.rotation.y.to_bits());
|
||||
assert_eq!(a.rotation.z.to_bits(), b.rotation.z.to_bits());
|
||||
let angle_a = first.joint_angle(first_joint).expect("the joint exists");
|
||||
let angle_b = second.joint_angle(second_joint).expect("the joint exists");
|
||||
assert_eq!(angle_a.get().to_bits(), angle_b.get().to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_ids_return_none() {
|
||||
let mut world = RapierBackend::new();
|
||||
assert!(world.body_transform(BodyId(u32::MAX)).is_none());
|
||||
assert!(world.joint_angle(JointId(u32::MAX)).is_none());
|
||||
world.set_motor_position(JointId(7), Radians::new(1.0), 1.0, 1.0);
|
||||
assert!(world.body_transform(BodyId(7)).is_none());
|
||||
assert!(world.joint_angle(JointId(7)).is_none());
|
||||
}
|
||||
|
||||
fn flat_terrain() -> TrimeshDesc {
|
||||
TrimeshDesc {
|
||||
vertices: vec![
|
||||
Vec3::new(-5.0, -5.0, 0.0),
|
||||
Vec3::new(5.0, -5.0, 0.0),
|
||||
Vec3::new(5.0, 5.0, 0.0),
|
||||
Vec3::new(-5.0, 5.0, 0.0),
|
||||
],
|
||||
indices: vec![[0, 1, 2], [0, 2, 3]],
|
||||
position: Vec3::ZERO,
|
||||
rotation: Quat::IDENTITY,
|
||||
}
|
||||
}
|
||||
|
||||
fn dropped_ball(world: &mut RapierBackend, radius: f64, position: Vec3) -> BodyId {
|
||||
world.add_body(BodyDesc::dynamic(
|
||||
ShapeDesc::Ball { radius },
|
||||
Kilograms::new(1.0),
|
||||
position,
|
||||
))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ball_settles_on_flat_trimesh() {
|
||||
let mut world = RapierBackend::new();
|
||||
let terrain = world
|
||||
.add_trimesh(flat_terrain())
|
||||
.expect("flat terrain is valid");
|
||||
assert!(world.body_transform(terrain).is_some());
|
||||
let radius = 0.25;
|
||||
let ball = dropped_ball(&mut world, radius, Vec3::new(0.75, -0.5, 5.0));
|
||||
let dt = step_at(1_000);
|
||||
for _ in 0..2_000 {
|
||||
world.step(dt);
|
||||
}
|
||||
let resting = world
|
||||
.body_transform(ball)
|
||||
.expect("the ball exists")
|
||||
.position;
|
||||
assert!(
|
||||
(resting.z - radius).abs() <= 0.05,
|
||||
"resting z = {}, radius = {radius}",
|
||||
resting.z
|
||||
);
|
||||
for _ in 0..500 {
|
||||
world.step(dt);
|
||||
let z = world
|
||||
.body_transform(ball)
|
||||
.expect("the ball exists")
|
||||
.position
|
||||
.z;
|
||||
assert!((z - radius).abs() <= 0.05, "drifted z = {z}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trimesh_worlds_match_bitwise() {
|
||||
let mut first = RapierBackend::new();
|
||||
let mut second = RapierBackend::new();
|
||||
assert!(first.add_trimesh(flat_terrain()).is_some());
|
||||
assert!(second.add_trimesh(flat_terrain()).is_some());
|
||||
let first_ball = dropped_ball(&mut first, 0.25, Vec3::new(0.75, -0.5, 5.0));
|
||||
let second_ball = dropped_ball(&mut second, 0.25, Vec3::new(0.75, -0.5, 5.0));
|
||||
let dt = step_at(1_000);
|
||||
for _ in 0..500 {
|
||||
first.step(dt);
|
||||
second.step(dt);
|
||||
}
|
||||
let a = first.body_transform(first_ball).expect("the ball exists");
|
||||
let b = second.body_transform(second_ball).expect("the ball exists");
|
||||
assert_eq!(a.position.x.to_bits(), b.position.x.to_bits());
|
||||
assert_eq!(a.position.y.to_bits(), b.position.y.to_bits());
|
||||
assert_eq!(a.position.z.to_bits(), b.position.z.to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_trimesh_is_rejected_and_backend_stays_usable() {
|
||||
let mut world = RapierBackend::new();
|
||||
let empty_vertices = TrimeshDesc {
|
||||
vertices: Vec::new(),
|
||||
indices: vec![[0, 1, 2]],
|
||||
position: Vec3::ZERO,
|
||||
rotation: Quat::IDENTITY,
|
||||
};
|
||||
let empty_indices = TrimeshDesc {
|
||||
vertices: flat_terrain().vertices,
|
||||
indices: Vec::new(),
|
||||
position: Vec3::ZERO,
|
||||
rotation: Quat::IDENTITY,
|
||||
};
|
||||
let out_of_range = TrimeshDesc {
|
||||
vertices: flat_terrain().vertices,
|
||||
indices: vec![[0, 1, 4]],
|
||||
position: Vec3::ZERO,
|
||||
rotation: Quat::IDENTITY,
|
||||
};
|
||||
let mut non_finite_vertices = flat_terrain().vertices;
|
||||
non_finite_vertices[0] = Vec3::new(f64::NAN, 0.0, 0.0);
|
||||
let non_finite = TrimeshDesc {
|
||||
vertices: non_finite_vertices,
|
||||
indices: vec![[0, 1, 2]],
|
||||
position: Vec3::ZERO,
|
||||
rotation: Quat::IDENTITY,
|
||||
};
|
||||
for desc in [empty_vertices, empty_indices, out_of_range, non_finite] {
|
||||
assert!(world.add_trimesh(desc).is_none());
|
||||
}
|
||||
let ball = dropped_ball(&mut world, 0.2, Vec3::new(0.0, 0.0, 1.0));
|
||||
let dt = step_at(1_000);
|
||||
world.step(dt);
|
||||
let z = world
|
||||
.body_transform(ball)
|
||||
.expect("the ball exists")
|
||||
.position
|
||||
.z;
|
||||
assert!(z < 1.0, "the ball did not fall, z = {z}");
|
||||
}
|
||||
|
||||
/// Height of the plane through the origin with `normal` at `x`, `y`.
|
||||
fn plane_z(normal: Vec3, x: f64, y: f64) -> f64 {
|
||||
-(normal.x * x + normal.y * y) / normal.z
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ball_stays_above_inclined_trimesh() {
|
||||
let rotation =
|
||||
Quat::from_axis_angle(Vec3::Y, Radians::new(0.3)).expect("the Y axis is nonzero");
|
||||
let terrain = TrimeshDesc {
|
||||
vertices: vec![
|
||||
Vec3::new(-50.0, -50.0, 0.0),
|
||||
Vec3::new(50.0, -50.0, 0.0),
|
||||
Vec3::new(50.0, 50.0, 0.0),
|
||||
Vec3::new(-50.0, 50.0, 0.0),
|
||||
],
|
||||
indices: vec![[0, 1, 2], [0, 2, 3]],
|
||||
position: Vec3::ZERO,
|
||||
rotation,
|
||||
};
|
||||
let normal = rotation.rotate(Vec3::Z);
|
||||
let mut world = RapierBackend::new();
|
||||
assert!(world.add_trimesh(terrain).is_some());
|
||||
let radius = 0.25;
|
||||
let ball = dropped_ball(&mut world, radius, Vec3::new(0.0, 0.0, 3.0));
|
||||
let dt = step_at(1_000);
|
||||
for step in 0..2_000 {
|
||||
world.step(dt);
|
||||
let position = world
|
||||
.body_transform(ball)
|
||||
.expect("the ball exists")
|
||||
.position;
|
||||
let surface = plane_z(normal, position.x, position.y);
|
||||
assert!(
|
||||
position.z > surface,
|
||||
"step {step}: z = {} under surface {surface}",
|
||||
position.z
|
||||
);
|
||||
}
|
||||
let position = world
|
||||
.body_transform(ball)
|
||||
.expect("the ball exists")
|
||||
.position;
|
||||
let surface = plane_z(normal, position.x, position.y);
|
||||
assert!(
|
||||
(position.z - surface - radius / normal.z).abs() <= 0.1,
|
||||
"ball left the slope: z = {}, surface = {surface}",
|
||||
position.z
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue