fabrilis/crates/app/src/runtime/sim/mod.rs
loki5512344 1042269d7e
Finish M4: cart, log facade, idle diagnostics and terrain LOD
Add the core::log facade with five levels and a sink; migrate the app dev log and enable trace in --dev. Replace the dropped cubes with a four-wheel cart on revolute joints driven by velocity motors, add WASD controls, a golden trajectory and a slope test. Instrument idle frame spikes and throttle the window title. Add chunked terrain LOD with skirts (2368 vs 8192 triangles) while physics keeps the full mesh. Pin Rust 1.100.0; edition stays 2024.
2026-11-17 14:32:52 +01:00

134 lines
3.8 KiB
Rust

//! Fixed-step physics for the cart shown in the window.
mod cart;
mod pacing;
#[cfg(test)]
mod tests;
use std::time::Duration;
use fabrilis_core::time::SimDelta;
use fabrilis_core::vec::{Quat, Vec3};
use fabrilis_physics::{PhysicsBackend, RapierBackend, TrimeshDesc};
use fabrilis_render::Scene;
use fabrilis_worldgen::terrain::{Heightmap, TerrainMesh};
use crate::runtime::AppError;
use crate::runtime::metrics::Stopwatch;
use cart::{Cart, CartInfo, CartPose};
use pacing::{MAX_STEPS, Pacer};
pub(crate) use cart::Drive;
/// Physics rate; the step never changes with the frame time.
const HZ: u64 = 1_000;
/// The Rapier world and the cart it drives.
pub(crate) struct Simulation {
backend: RapierBackend,
cart: Cart,
step: SimDelta,
pacer: Pacer,
total_steps: u64,
slowest_step: Duration,
}
impl Simulation {
/// Builds the terrain collider and spawns the cart into the scene.
pub(crate) fn new(
terrain: &TerrainMesh,
heightmap: &Heightmap,
scene: &mut Scene,
) -> Result<Self, AppError> {
let step = SimDelta::from_hz(HZ).ok_or_else(|| {
AppError::Physics("physics step is not a whole nanosecond".to_owned())
})?;
let mut backend = RapierBackend::new();
let collider = TrimeshDesc {
vertices: terrain.vertices.clone(),
indices: terrain.indices.clone(),
position: Vec3::ZERO,
rotation: Quat::IDENTITY,
};
backend
.add_trimesh(collider)
.ok_or_else(|| AppError::Physics("terrain collider was rejected".to_owned()))?;
let cart = Cart::new(&mut backend, heightmap, scene);
Ok(Self {
backend,
cart,
step,
pacer: Pacer::new(),
total_steps: 0,
slowest_step: Duration::ZERO,
})
}
/// Runs the fixed steps owed for this frame and copies transforms to the scene.
///
/// Diagnostics time each step individually, but only observe it: the number
/// of steps, their order and the Rapier calls stay exactly the same, so the
/// resulting state hash does not depend on logging being enabled.
pub(crate) fn advance(&mut self, scene: &mut Scene, drive: Drive) -> pacing::Frame {
let frame = self.pacer.advance(self.step.nanos(), MAX_STEPS);
self.slowest_step = Duration::ZERO;
self.total_steps = self.total_steps.saturating_add(u64::from(frame.steps));
self.cart.drive(&mut self.backend, drive);
self.run_steps(frame.steps);
self.cart.sync(&self.backend, scene);
frame
}
/// Runs exactly `steps` fixed steps with no wall clock, for golden tests and
/// a future headless CLI. The motors are set once, before the batch.
#[allow(
dead_code,
reason = "the headless CLI will step the same world without wall clock"
)]
pub(crate) fn step_fixed(&mut self, steps: u32, drive: Drive) {
self.slowest_step = Duration::ZERO;
self.total_steps = self.total_steps.saturating_add(u64::from(steps));
self.cart.drive(&mut self.backend, drive);
for _ in 0..steps {
self.backend.step(self.step);
}
}
/// Simulated seconds represented by the steps that have actually run.
#[must_use]
pub(crate) fn sim_seconds(&self) -> f64 {
self.total_steps as f64 * self.step.nanos() as f64 / 1_000_000_000.0
}
/// The slowest single physics step of the latest frame.
#[must_use]
pub(crate) fn slowest_step(&self) -> Duration {
self.slowest_step
}
/// The current chassis pose and wheel angles, used by the golden test.
#[allow(
dead_code,
reason = "read by the golden test and by the future headless CLI"
)]
#[must_use]
pub(crate) fn cart_pose(&self) -> Option<CartPose> {
self.cart.pose(&self.backend)
}
/// What the startup banner reports about the cart.
#[must_use]
pub(crate) fn cart_info(&self) -> CartInfo {
self.cart.info()
}
/// Steps the backend while observing how long each step took.
fn run_steps(&mut self, steps: u32) {
for _ in 0..steps {
let step_start = Stopwatch::start();
self.backend.step(self.step);
self.slowest_step = self.slowest_step.max(step_start.elapsed());
}
}
}