use crcbl_ecs::{Entity, SystemTrait as _};
use crcbl_phys::{
ColliderComponent, ContactSettings, DistanceJoint, GravityForce, Joint, JointKind,
MassProperties, PhysicsSystem, RigidBody, SurfaceMaterial, Transform,
};
use glam::{DQuat, DVec3};
const DT: f64 = 1.0 / 60.0;
const G: f64 = 9.81;
const CRATE: SurfaceMaterial = SurfaceMaterial::new(0.6, 0.0);
fn entity(index: u32) -> Entity {
Entity::from_bits((1u64 << 32) | u64::from(index)).expect("generation 1 is never zero")
}
const AWAKE: ContactSettings = ContactSettings {
sleep: false,
..ContactSettings::DEFAULT
};
fn system_with(settings: ContactSettings, floor: SurfaceMaterial) -> PhysicsSystem {
let mut phys = PhysicsSystem::with_contacts(settings);
phys.add_force_provider(Box::new(GravityForce::EARTH));
phys.add_plane(DVec3::Y, 0.0, floor);
phys
}
fn system(floor: SurfaceMaterial) -> PhysicsSystem {
system_with(ContactSettings::DEFAULT, floor)
}
fn crate_(
phys: &mut PhysicsSystem,
index: u32,
at: DVec3,
rotation: DQuat,
half: DVec3,
mass: f64,
material: SurfaceMaterial,
) -> Entity {
let e = entity(index);
let inertia = MassProperties::cuboid(mass, half, DVec3::ZERO).inertia;
phys.set_body(e, RigidBody::new_dynamic(mass).with_inertia(inertia));
let transform = Transform::new(at, rotation);
phys.set_transform(e, transform);
phys.set_collider(
e,
&ColliderComponent::Box {
offset: DVec3::ZERO,
half_extents: half,
is_trigger: false,
},
&transform,
);
phys.set_material(e, material);
e
}
fn slab(phys: &mut PhysicsSystem, index: u32, centre: DVec3, half: DVec3) -> Entity {
let e = entity(index);
let transform = Transform::from_position(centre);
phys.set_transform(e, transform);
phys.set_collider(
e,
&ColliderComponent::Box {
offset: DVec3::ZERO,
half_extents: half,
is_trigger: false,
},
&transform,
);
phys.set_material(e, CRATE);
e
}
fn position(phys: &PhysicsSystem, e: Entity) -> DVec3 {
phys.transform(e).expect("registered").position
}
#[test]
fn a_box_resting_on_a_box_keeps_its_feature_ids() {
let mut phys = PhysicsSystem::with_contacts(AWAKE);
phys.add_force_provider(Box::new(GravityForce::EARTH));
slab(
&mut phys,
100,
DVec3::new(0.0, -0.5, 0.0),
DVec3::new(2.0, 0.5, 2.0),
);
let half = DVec3::new(0.3, 0.2, 0.4);
crate_(
&mut phys,
0,
DVec3::new(0.1, half.y, -0.2),
DQuat::IDENTITY,
half,
5.0,
CRATE,
);
let (mut points, mut persisted) = (0, 0);
for tick in 0..240 {
phys.step(DT);
let counters = phys.contact_counters();
if tick >= 1 {
assert_eq!(counters.touching, 1, "tick {tick}: {counters:?}");
assert_eq!(counters.points, 4, "tick {tick}: {counters:?}");
assert_eq!(
counters.begun + counters.ended,
0,
"tick {tick}: {counters:?}"
);
points += counters.points;
persisted += counters.persisted;
}
}
assert_eq!(
persisted, points,
"{persisted} of {points} points persisted"
);
assert_eq!(
phys.contact_counters().persisted_ratio(),
Some(1.0),
"the counter's own ratio"
);
}
fn column(phys: &mut PhysicsSystem, count: u32, half: f64) -> Vec<Entity> {
(0..count)
.map(|i| {
let y = half + 2.0 * half * f64::from(i);
crate_(
phys,
i,
DVec3::new(0.0, y, 0.0),
DQuat::IDENTITY,
DVec3::splat(half),
10.0,
CRATE,
)
})
.collect()
}
#[derive(Clone, Copy, Debug)]
struct ColumnSample {
sunk: f64,
sideways: f64,
tipped: f64,
asleep: bool,
}
fn column_trace(
settings: ContactSettings,
count: u32,
substeps: u32,
ticks: u32,
) -> Vec<ColumnSample> {
let mut phys = system_with(settings, CRATE);
let boxes = column(&mut phys, count, 0.5);
for &e in &boxes {
phys.set_substeps(e, substeps);
}
let top = *boxes.last().expect("a column has a top");
let start = position(&phys, top);
(0..ticks)
.map(|_| {
phys.step(DT);
let drift = position(&phys, top) - start;
let tipped = boxes
.iter()
.map(|&e| {
let up = phys.transform(e).expect("a box").rotation * DVec3::Y;
(up.x * up.x + up.z * up.z).sqrt()
})
.fold(0.0, f64::max);
ColumnSample {
sunk: -drift.y,
sideways: DVec3::new(drift.x, 0.0, drift.z).length(),
tipped,
asleep: boxes.iter().all(|&e| phys.is_sleeping(e)),
}
})
.collect()
}
#[test]
fn a_column_of_twenty_boxes_stands() {
let ColumnSample {
sunk,
sideways,
tipped,
..
} = *column_trace(ContactSettings::DEFAULT, 20, 12, 600)
.last()
.expect("600 ticks");
assert!(sideways < 5e-3, "the top box moved {sideways} m sideways");
assert!(sunk < 0.02, "the top box sank {sunk} m under the column");
assert!(tipped < 2e-3, "a box tipped by {tipped}");
}
#[test]
fn a_column_under_greenhills_height_stands_at_the_defaults() {
let trace = column_trace(ContactSettings::DEFAULT, 14, 0, 600);
let asleep_from = trace
.iter()
.position(|s| s.asleep)
.expect("the column falls asleep");
let tick = asleep_from + 1;
assert!(tick <= 60, "the column fell asleep at tick {tick}");
assert!(
trace[asleep_from..].iter().all(|s| s.asleep),
"the column woke after tick {tick}"
);
let frozen = trace[asleep_from];
let last = trace.last().expect("600 ticks");
assert_eq!(
(last.sunk, last.sideways, last.tipped),
(frozen.sunk, frozen.sideways, frozen.tipped),
"the column moved in its sleep"
);
let ColumnSample {
sunk,
sideways,
tipped,
..
} = frozen;
assert!(sideways < 1e-2, "the top box slept {sideways} m sideways");
assert!(sunk < 0.06, "the top box slept {sunk} m sunk");
assert!(tipped < 2e-3, "a box slept tipped by {tipped}");
}
#[test]
fn a_column_under_greenhills_height_damps_its_sway() {
let trace = column_trace(AWAKE, 14, 0, 600);
let most = |samples: &[ColumnSample], of: fn(&ColumnSample) -> f64| {
samples.iter().map(of).fold(0.0, f64::max)
};
let (first, second) = trace.split_at(300);
let first_swing = most(first, |s| s.sideways);
let second_swing = most(second, |s| s.sideways);
assert!(
first_swing < 0.016,
"the top box swung {first_swing} m sideways"
);
assert!(
second_swing < 0.6 * first_swing,
"the top box swung {first_swing} m and then {second_swing} m"
);
let sunk = most(&trace, |s| s.sunk);
let tipped = most(&trace, |s| s.tipped);
assert!(sunk < 0.06, "the top box sank {sunk} m under the column");
assert!(tipped < 2e-3, "a box tipped by {tipped}");
}
fn pyramid(phys: &mut PhysicsSystem, base: u32, half: f64) -> (Vec<Entity>, Entity) {
let mut boxes = Vec::new();
let mut index = 0;
for row in 0..base {
let across = base - row;
for k in 0..across {
let x = (f64::from(k) - 0.5 * f64::from(across - 1)) * 2.0 * half;
let y = half + 2.0 * half * f64::from(row);
boxes.push(crate_(
phys,
index,
DVec3::new(x, y, 0.0),
DQuat::IDENTITY,
DVec3::splat(half),
10.0,
CRATE,
));
index += 1;
}
}
let top = *boxes.last().expect("a pyramid has a top");
(boxes, top)
}
#[test]
fn a_base_twenty_pyramid_holds() {
let mut phys = system_with(AWAKE, CRATE);
let (boxes, top) = pyramid(&mut phys, 20, 0.5);
assert_eq!(boxes.len(), 210);
let starts: Vec<DVec3> = boxes.iter().map(|&e| position(&phys, e)).collect();
let top_start = position(&phys, top);
let mut least_persisted = 1.0f64;
for tick in 0..600 {
phys.step(DT);
if tick >= 60 {
let ratio = phys.contact_counters().persisted_ratio();
least_persisted = least_persisted.min(ratio.expect("the pyramid touches"));
}
}
let worst = boxes
.iter()
.zip(&starts)
.map(|(&e, &start)| (position(&phys, e) - start).length())
.fold(0.0, f64::max);
let top_drift = position(&phys, top) - top_start;
let sideways = DVec3::new(top_drift.x, 0.0, top_drift.z).length();
assert!(worst < 0.04, "a box moved {worst} m");
assert!(sideways < 1e-3, "the top box moved {sideways} m sideways");
assert!(least_persisted > 0.99, "a tick persisted {least_persisted}");
let counters = phys.contact_counters();
assert_eq!(counters.points_per_manifold(), Some(4.0), "{counters:?}");
}
#[test]
fn dominoes_topple_in_order() {
const COUNT: u32 = 10;
const SPACING: f64 = 0.6;
let half = DVec3::new(0.05, 0.5, 0.25);
let mut phys = system(CRATE);
let dominoes: Vec<Entity> = (0..COUNT)
.map(|i| {
crate_(
&mut phys,
i,
DVec3::new(SPACING * f64::from(i), half.y, 0.0),
DQuat::IDENTITY,
half,
2.0,
CRATE,
)
})
.collect();
phys.body_mut(dominoes[0]).expect("a body").angular_velocity = DVec3::new(0.0, 0.0, -2.0);
let mut fell_at = vec![None; dominoes.len()];
for tick in 0..240u32 {
phys.step(DT);
for (k, &e) in dominoes.iter().enumerate() {
let up = phys.transform(e).expect("a domino").rotation * DVec3::Y;
if fell_at[k].is_none() && up.y < 0.866 {
fell_at[k] = Some(tick);
}
}
}
let ticks: Vec<u32> = fell_at
.iter()
.enumerate()
.map(|(k, t)| t.unwrap_or_else(|| panic!("domino {k} never fell: {fell_at:?}")))
.collect();
assert!(
ticks.windows(2).all(|w| w[0] < w[1]),
"out of order: {ticks:?}"
);
let last = phys
.transform(dominoes[COUNT as usize - 1])
.expect("a domino");
assert!(
(last.rotation * DVec3::Y).y < 0.5,
"the last domino is still up: {last:?}"
);
}
#[test]
fn a_sliding_box_stops_where_friction_says() {
const MU: f64 = 0.5;
const SPEED: f64 = 3.0;
let material = SurfaceMaterial::new(MU, 0.0);
let mut phys = system(material);
let half = DVec3::new(0.3, 0.1, 0.2);
let b = crate_(
&mut phys,
0,
DVec3::new(0.0, half.y, 0.0),
DQuat::IDENTITY,
half,
4.0,
material,
);
phys.step(DT);
phys.body_mut(b).expect("a body").velocity = DVec3::new(SPEED, 0.0, 0.0);
let start = position(&phys, b).x;
for _ in 0..120 {
phys.step(DT);
}
let slid = position(&phys, b).x - start;
let analytic = SPEED * SPEED / (2.0 * MU * G);
assert!(
(slid - analytic).abs() < 0.03 * analytic,
"slid {slid} m against {analytic} m"
);
assert!(
phys.body(b).expect("a body").velocity.length() < 1e-3,
"still moving"
);
}
#[test]
fn a_box_spun_flat_is_stopped_by_twist_friction() {
const MU: f64 = 0.5;
const SPIN: f64 = 10.0;
const HALF: f64 = 0.3;
let material = SurfaceMaterial::new(MU, 0.0);
let mut phys = system(material);
let b = crate_(
&mut phys,
0,
DVec3::new(0.0, HALF, 0.0),
DQuat::IDENTITY,
DVec3::splat(HALF),
8.0,
material,
);
phys.step(DT);
phys.body_mut(b).expect("a body").angular_velocity = DVec3::new(0.0, SPIN, 0.0);
let start = position(&phys, b);
let mut stopped = None;
for tick in 1..=120u32 {
phys.step(DT);
if stopped.is_none() && phys.body(b).expect("a body").angular_velocity.y.abs() < 0.05 {
stopped = Some(f64::from(tick) * DT);
}
}
let alpha = MU * G * HALF * core::f64::consts::SQRT_2 / (2.0 / 3.0 * HALF * HALF);
let analytic = SPIN / alpha;
let stopped = stopped.expect("it never stopped spinning");
assert!(
(stopped - analytic).abs() < 0.1 * analytic,
"stopped after {stopped} s against {analytic} s"
);
let moved = (position(&phys, b) - start).length();
assert!(moved < 1e-3, "its centre moved {moved} m");
}
fn pyramid_hash(ticks: u32) -> u64 {
use std::hash::Hasher;
struct Fnv(u64);
impl Hasher for Fnv {
fn finish(&self) -> u64 {
self.0
}
fn write(&mut self, bytes: &[u8]) {
for byte in bytes {
self.0 = (self.0 ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
}
}
}
let mut phys = system_with(AWAKE, CRATE);
pyramid(&mut phys, 20, 0.5);
for _ in 0..ticks {
phys.step(DT);
}
let mut hasher = Fnv(0xcbf2_9ce4_8422_2325);
phys.hash_state(&mut hasher);
hasher.finish()
}
#[test]
fn a_pyramid_hashes_the_same_on_two_runs() {
assert_eq!(pyramid_hash(120), pyramid_hash(120));
assert_ne!(pyramid_hash(120), pyramid_hash(121));
}
fn tethered_column_trace(count: u32, rest: f64, ticks: u32) -> Vec<ColumnSample> {
let mut phys = system_with(AWAKE, CRATE);
let boxes = column(&mut phys, count, 0.5);
let corner = Transform::from_position(DVec3::new(0.5, 0.5, 0.5));
for pair in boxes.windows(2) {
phys.add_joint(
Joint::new(
pair[0],
pair[1],
corner,
corner,
JointKind::Distance(DistanceJoint::spring(rest, 1.0, 0.7)),
)
.colliding(true),
)
.expect("a valid spring");
}
let top = *boxes.last().expect("a column has a top");
let start = position(&phys, top);
(0..ticks)
.map(|_| {
phys.step(DT);
let drift = position(&phys, top) - start;
let tipped = boxes
.iter()
.map(|&e| {
let up = phys.transform(e).expect("a box").rotation * DVec3::Y;
(up.x * up.x + up.z * up.z).sqrt()
})
.fold(0.0, f64::max);
ColumnSample {
sunk: -drift.y,
sideways: DVec3::new(drift.x, 0.0, drift.z).length(),
tipped,
asleep: boxes.iter().all(|&e| phys.is_sleeping(e)),
}
})
.collect()
}
fn sway(trace: &[ColumnSample]) -> (f64, f64) {
let most = trace.iter().map(|s| s.sideways).fold(0.0, f64::max);
(most, trace.last().expect("a sample").sideways)
}
#[test]
fn a_column_tethered_by_weak_springs_sways_as_one_without_them() {
let (most, last) = sway(&tethered_column_trace(14, 1.0, 600));
assert!(most < 0.02, "the top cube swung {most} m sideways");
assert!(last < 5e-3, "the top cube was {last} m out at tick 600");
}
#[test]
fn a_column_tethered_under_tension_leans_only_as_far_as_its_contacts_give() {
let (most, last) = sway(&tethered_column_trace(14, 0.5, 600));
assert!(most < 0.25, "the top cube leaned {most} m");
assert!(last < 0.15, "the top cube was {last} m out at tick 600");
}