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.
This commit is contained in:
parent
190ef9cc4b
commit
1042269d7e
38 changed files with 2348 additions and 374 deletions
|
|
@ -1,8 +1,14 @@
|
|||
//! The application handler: window installation, resize, redraw and logging.
|
||||
|
||||
use std::sync::Arc;
|
||||
mod title;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use fabrilis_core::log::{Level, error, info, set_level, set_sink, warn};
|
||||
use fabrilis_render::Overlay;
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::dpi::PhysicalSize;
|
||||
|
|
@ -13,29 +19,38 @@ use winit::window::{Window, WindowId};
|
|||
|
||||
use super::camera::Controls;
|
||||
use super::config::Config;
|
||||
use super::devlog::{self, DevLog, Level};
|
||||
use super::devlog::{self, DevLog, DevLogSink};
|
||||
use super::gpu::WindowRenderer;
|
||||
use super::metrics::{CsvLog, FrameWork, Metrics, Row, Stopwatch, spike_reason, unix_now};
|
||||
use super::metrics::{
|
||||
CsvLog, FrameDetail, FrameWork, Metrics, Row, Stopwatch, spike_reason, unix_now,
|
||||
};
|
||||
use super::scene::View;
|
||||
use super::sim::Simulation;
|
||||
use super::{AppError, aspect, log_startup};
|
||||
use super::{AppError, aspect};
|
||||
use title::title_due;
|
||||
|
||||
/// Runs the window loop until the user closes the window or presses Escape.
|
||||
pub(super) fn run() -> Result<(), AppError> {
|
||||
let config = super::parse_config();
|
||||
let csv = super::open_csv(&config)?;
|
||||
let level = if config.dev {
|
||||
Level::Debug
|
||||
Level::Trace
|
||||
} else {
|
||||
Level::Info
|
||||
};
|
||||
set_level(level);
|
||||
let dev = match &config.log {
|
||||
Some(path) => Some(
|
||||
DevLog::open(path, level, config.append)
|
||||
Some(path) => Some(Arc::new(Mutex::new(
|
||||
DevLog::open(path, config.append)
|
||||
.map_err(|error| AppError::Log(format!("{}: {error}", path.display())))?,
|
||||
),
|
||||
))),
|
||||
None => None,
|
||||
};
|
||||
// The sink is installed before the event loop, so the startup banner and
|
||||
// every later record go through the same facade.
|
||||
if let Some(log) = &dev {
|
||||
set_sink(Arc::new(DevLogSink::new(Arc::clone(log))));
|
||||
}
|
||||
let event_loop = EventLoop::new().map_err(|error| AppError::EventLoop(error.to_string()))?;
|
||||
event_loop.set_control_flow(ControlFlow::Poll);
|
||||
let mut application = Fabrilis::new(config, csv, dev);
|
||||
|
|
@ -51,7 +66,7 @@ pub(super) fn run() -> Result<(), AppError> {
|
|||
struct Fabrilis {
|
||||
config: Config,
|
||||
csv: Option<CsvLog>,
|
||||
dev: Option<DevLog>,
|
||||
dev: Option<Arc<Mutex<DevLog>>>,
|
||||
frame: u64,
|
||||
window: Option<Arc<Window>>,
|
||||
renderer: Option<WindowRenderer>,
|
||||
|
|
@ -60,10 +75,11 @@ struct Fabrilis {
|
|||
controls: Controls,
|
||||
metrics: Metrics,
|
||||
overlay: Overlay,
|
||||
title_clock: Duration,
|
||||
}
|
||||
|
||||
impl Fabrilis {
|
||||
fn new(config: Config, csv: Option<CsvLog>, dev: Option<DevLog>) -> Self {
|
||||
fn new(config: Config, csv: Option<CsvLog>, dev: Option<Arc<Mutex<DevLog>>>) -> Self {
|
||||
Self {
|
||||
config,
|
||||
csv,
|
||||
|
|
@ -76,6 +92,7 @@ impl Fabrilis {
|
|||
controls: Controls::default(),
|
||||
metrics: Metrics::default(),
|
||||
overlay: Overlay::new(),
|
||||
title_clock: Duration::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -91,7 +108,7 @@ impl Fabrilis {
|
|||
let mut view = super::scene::build(aspect(window.inner_size()))?;
|
||||
let simulation = Simulation::new(&view.terrain, &view.heightmap, &mut view.scene)?;
|
||||
let renderer = WindowRenderer::new(window.clone())?;
|
||||
log_startup(self.dev.as_mut(), &self.config, &view, &renderer, &window);
|
||||
super::log_startup(&self.config, &view, &renderer, &window, &simulation);
|
||||
self.window = Some(window);
|
||||
self.renderer = Some(renderer);
|
||||
self.view = Some(view);
|
||||
|
|
@ -117,39 +134,58 @@ impl Fabrilis {
|
|||
}
|
||||
}
|
||||
|
||||
/// Refreshes the RTF in the window title at most once per second.
|
||||
///
|
||||
/// The clock accumulates frame time instead of reading wall time, so the
|
||||
/// policy stays testable and frames that are not due pay nothing.
|
||||
fn update_title(
|
||||
window: Option<&Window>,
|
||||
clock: &mut Duration,
|
||||
frame_time: Duration,
|
||||
rtf: Option<f32>,
|
||||
) -> Duration {
|
||||
*clock = clock.saturating_add(frame_time);
|
||||
if !title_due(*clock) {
|
||||
return Duration::ZERO;
|
||||
}
|
||||
let (Some(rtf), Some(window)) = (rtf, window) else {
|
||||
return Duration::ZERO;
|
||||
};
|
||||
let start = Stopwatch::start();
|
||||
window.set_title(&format!("Fabrilis — RTF {rtf:.2}"));
|
||||
*clock = Duration::ZERO;
|
||||
start.elapsed()
|
||||
}
|
||||
|
||||
fn redraw(&mut self) {
|
||||
let Some(view) = self.view.as_mut() else {
|
||||
let (Some(view), Some(simulation)) = (self.view.as_mut(), self.simulation.as_mut()) else {
|
||||
return;
|
||||
};
|
||||
let Some(simulation) = self.simulation.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let unix_s = if self.csv.is_some() {
|
||||
Some(unix_now())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let unix_s = self.csv.is_some().then(unix_now);
|
||||
let frame_time = self.metrics.frame_time();
|
||||
let physics_start = Stopwatch::start();
|
||||
let frame = simulation.advance(&mut view.scene);
|
||||
let frame = simulation.advance(&mut view.scene, self.controls.drive());
|
||||
let physics = physics_start.elapsed();
|
||||
let slowest_step_ms = simulation.slowest_step().as_secs_f32() * 1000.0;
|
||||
let sim_seconds = simulation.sim_seconds();
|
||||
let motion = self.controls.motion(frame.elapsed_seconds);
|
||||
view.camera.apply(motion);
|
||||
if let (Some(rtf), Some(window)) = (frame.rtf, &self.window) {
|
||||
window.set_title(&format!("Fabrilis — RTF {rtf:.2}"));
|
||||
}
|
||||
view.update_terrain_lod(view.camera.eye());
|
||||
let title = Self::update_title(
|
||||
self.window.as_deref(),
|
||||
&mut self.title_clock,
|
||||
frame_time,
|
||||
frame.rtf,
|
||||
);
|
||||
self.metrics.set_rtf(frame.rtf);
|
||||
let camera = view.camera.view();
|
||||
let size = self
|
||||
.renderer
|
||||
.as_ref()
|
||||
.map_or((0, 0), |renderer| renderer.size());
|
||||
let size = self.renderer.as_ref().map_or((0, 0), WindowRenderer::size);
|
||||
let overlay_start = Stopwatch::start();
|
||||
self.overlay.clear();
|
||||
if size.0 > 0 && size.1 > 0 {
|
||||
self.metrics.draw_panel(&mut self.overlay);
|
||||
}
|
||||
let overlay = overlay_start.elapsed();
|
||||
let Some(renderer) = self.renderer.as_mut() else {
|
||||
return;
|
||||
};
|
||||
|
|
@ -158,7 +194,7 @@ impl Fabrilis {
|
|||
let render = render_start.elapsed();
|
||||
if let Err(error) = draw {
|
||||
eprintln!("fabrilis: draw failed: {error}");
|
||||
write_dev(&mut self.dev, Level::Error, "render", &error.to_string());
|
||||
error!("render", "{error}");
|
||||
}
|
||||
let recorded = self.metrics.record(
|
||||
frame_time,
|
||||
|
|
@ -172,23 +208,25 @@ impl Fabrilis {
|
|||
return;
|
||||
}
|
||||
self.frame = self.frame.saturating_add(1);
|
||||
self.log_frame(frame_time, slowest_step_ms, sim_seconds, unix_s);
|
||||
let detail = FrameDetail {
|
||||
frame_ms: frame_time.as_secs_f32() * 1000.0,
|
||||
physics_step_ms: slowest_step_ms,
|
||||
render_ms: render.as_secs_f32() * 1000.0,
|
||||
overlay_ms: overlay.as_secs_f32() * 1000.0,
|
||||
title_ms: title.as_secs_f32() * 1000.0,
|
||||
metrics_us: self.metrics.sample_time().as_secs_f32() * 1_000_000.0,
|
||||
steps: frame.steps,
|
||||
};
|
||||
self.log_frame(detail, sim_seconds, unix_s);
|
||||
}
|
||||
|
||||
/// Writes the CSV row and the dev-log summary and spike lines for one frame.
|
||||
///
|
||||
/// Both observers run after the frame was drawn and only read the metrics
|
||||
/// that the overlay already computed.
|
||||
fn log_frame(
|
||||
&mut self,
|
||||
frame_time: Duration,
|
||||
slowest_step_ms: f32,
|
||||
sim_seconds: f64,
|
||||
unix_s: Option<f64>,
|
||||
) {
|
||||
fn log_frame(&mut self, detail: FrameDetail, sim_seconds: f64, unix_s: Option<f64>) {
|
||||
let stats = self.metrics.stats();
|
||||
let frame_ms = frame_time.as_secs_f32() * 1000.0;
|
||||
let spike = spike_reason(frame_ms, slowest_step_ms);
|
||||
let spike = spike_reason(detail.frame_ms, detail.physics_step_ms);
|
||||
if let Some(unix_s) = unix_s {
|
||||
let row = Row {
|
||||
unix_s,
|
||||
|
|
@ -201,28 +239,23 @@ impl Fabrilis {
|
|||
&& let Err(error) = csv.record(&row)
|
||||
{
|
||||
eprintln!("fabrilis: metrics log write failed: {error}");
|
||||
write_dev(&mut self.dev, Level::Error, "metrics", &error.to_string());
|
||||
error!("metrics", "{error}");
|
||||
}
|
||||
}
|
||||
if let Some(dev) = self.dev.as_mut() {
|
||||
if dev.summary_due() {
|
||||
write_line(dev, Level::Info, "metrics", &devlog::summary(&stats));
|
||||
if let Some(dev) = &self.dev {
|
||||
let summary_due = devlog::lock(dev).summary_due();
|
||||
if summary_due {
|
||||
info!("metrics", "{}", devlog::summary(&stats));
|
||||
}
|
||||
if let Some(trigger) = spike {
|
||||
let line = devlog::spike(self.frame, frame_ms, slowest_step_ms, trigger);
|
||||
write_line(dev, Level::Warn, "spike", &line);
|
||||
warn!("spike", "{}", devlog::spike(self.frame, &detail, trigger));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Logs a failure with its context before the loop gives up on the step.
|
||||
fn report(&mut self, context: &str, detail: &str) {
|
||||
write_dev(
|
||||
&mut self.dev,
|
||||
Level::Error,
|
||||
"app",
|
||||
&format!("{context}: {detail}"),
|
||||
);
|
||||
fn report(&self, context: &str, detail: &str) {
|
||||
error!("app", "{context}: {detail}");
|
||||
}
|
||||
|
||||
/// Flushes the CSV and closes the dev session.
|
||||
|
|
@ -232,7 +265,7 @@ impl Fabrilis {
|
|||
{
|
||||
eprintln!("fabrilis: metrics log flush failed: {error}");
|
||||
}
|
||||
write_dev(&mut self.dev, Level::Info, "app", "session end");
|
||||
info!("app", "session end");
|
||||
}
|
||||
|
||||
fn is_escape(event: &KeyEvent) -> bool {
|
||||
|
|
@ -248,20 +281,6 @@ impl Fabrilis {
|
|||
}
|
||||
}
|
||||
|
||||
/// Writes one dev-log line and reports a write failure on stderr.
|
||||
fn write_line(dev: &mut DevLog, level: Level, target: &str, message: &str) {
|
||||
if let Err(error) = dev.write(level, target, message) {
|
||||
eprintln!("fabrilis: dev log write failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes one dev-log line when the log is enabled.
|
||||
fn write_dev(dev: &mut Option<DevLog>, level: Level, target: &str, message: &str) {
|
||||
if let Some(dev) = dev {
|
||||
write_line(dev, level, target, message);
|
||||
}
|
||||
}
|
||||
|
||||
impl ApplicationHandler for Fabrilis {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if self.window.is_some() {
|
||||
|
|
|
|||
18
crates/app/src/runtime/application/tests.rs
Normal file
18
crates/app/src/runtime/application/tests.rs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
//! Tests for the window title refresh policy.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use super::title::title_due;
|
||||
|
||||
#[test]
|
||||
fn the_title_is_not_due_before_the_interval() {
|
||||
assert!(!title_due(Duration::ZERO));
|
||||
assert!(!title_due(Duration::from_millis(999)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_title_is_due_once_the_interval_has_passed() {
|
||||
assert!(title_due(Duration::from_secs(1)));
|
||||
assert!(title_due(Duration::from_millis(1_500)));
|
||||
assert!(title_due(Duration::from_secs(5)));
|
||||
}
|
||||
20
crates/app/src/runtime/application/title.rs
Normal file
20
crates/app/src/runtime/application/title.rs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
//! Window title refresh policy.
|
||||
//!
|
||||
//! The title only carries the simulation clock ratio, which the pacer updates
|
||||
//! roughly once per second. Asking the compositor for a new title on every
|
||||
//! frame adds a surface commit per frame on Wayland, so the update is
|
||||
//! throttled instead.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
/// Minimum wall time between two title updates.
|
||||
const TITLE_INTERVAL: Duration = Duration::from_secs(1);
|
||||
|
||||
/// Whether the title is due after the time accumulated since the last update.
|
||||
///
|
||||
/// Pure so the boundary is testable without a wall clock: exactly one second
|
||||
/// counts as due, everything below does not.
|
||||
#[must_use]
|
||||
pub(crate) fn title_due(elapsed: Duration) -> bool {
|
||||
elapsed >= TITLE_INTERVAL
|
||||
}
|
||||
|
|
@ -1,20 +1,25 @@
|
|||
//! Keyboard and mouse state mapped to camera motion.
|
||||
//! Keyboard and mouse state mapped to camera motion and cart drive.
|
||||
|
||||
use winit::event::ElementState;
|
||||
use winit::keyboard::KeyCode;
|
||||
|
||||
use super::Motion;
|
||||
use crate::runtime::sim::Drive;
|
||||
|
||||
/// Radians of rotation per pixel of mouse drag.
|
||||
const LOOK_SENSITIVITY: f32 = 0.0035;
|
||||
|
||||
/// Which movement keys are held and how far the mouse was dragged.
|
||||
/// Which keys are held and how far the mouse was dragged.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Controls {
|
||||
forward: bool,
|
||||
back: bool,
|
||||
left: bool,
|
||||
right: bool,
|
||||
throttle_forward: bool,
|
||||
throttle_back: bool,
|
||||
steer_left: bool,
|
||||
steer_right: bool,
|
||||
up: bool,
|
||||
down: bool,
|
||||
fast: bool,
|
||||
|
|
@ -25,12 +30,19 @@ pub(crate) struct Controls {
|
|||
|
||||
impl Controls {
|
||||
/// Tracks a movement or modifier key.
|
||||
///
|
||||
/// Arrows fly the camera; WASD drives the cart. Keeping the sets disjoint
|
||||
/// means no key has two meanings at once.
|
||||
pub(crate) fn key(&mut self, code: KeyCode, pressed: bool) {
|
||||
match code {
|
||||
KeyCode::KeyW | KeyCode::ArrowUp => self.forward = pressed,
|
||||
KeyCode::KeyS | KeyCode::ArrowDown => self.back = pressed,
|
||||
KeyCode::KeyA | KeyCode::ArrowLeft => self.left = pressed,
|
||||
KeyCode::KeyD | KeyCode::ArrowRight => self.right = pressed,
|
||||
KeyCode::ArrowUp => self.forward = pressed,
|
||||
KeyCode::ArrowDown => self.back = pressed,
|
||||
KeyCode::ArrowLeft => self.left = pressed,
|
||||
KeyCode::ArrowRight => self.right = pressed,
|
||||
KeyCode::KeyW => self.throttle_forward = pressed,
|
||||
KeyCode::KeyS => self.throttle_back = pressed,
|
||||
KeyCode::KeyA => self.steer_left = pressed,
|
||||
KeyCode::KeyD => self.steer_right = pressed,
|
||||
KeyCode::KeyE => self.up = pressed,
|
||||
KeyCode::KeyQ => self.down = pressed,
|
||||
KeyCode::ShiftLeft | KeyCode::ShiftRight => self.fast = pressed,
|
||||
|
|
@ -63,6 +75,10 @@ impl Controls {
|
|||
self.back = false;
|
||||
self.left = false;
|
||||
self.right = false;
|
||||
self.throttle_forward = false;
|
||||
self.throttle_back = false;
|
||||
self.steer_left = false;
|
||||
self.steer_right = false;
|
||||
self.up = false;
|
||||
self.down = false;
|
||||
self.fast = false;
|
||||
|
|
@ -71,7 +87,15 @@ impl Controls {
|
|||
self.turn = [0.0, 0.0];
|
||||
}
|
||||
|
||||
/// Builds this frame's motion and consumes the accumulated look deltas.
|
||||
/// Builds this frame's cart input: `W`/`S` throttle, `A`/`D` steer left/right.
|
||||
pub(crate) fn drive(&self) -> Drive {
|
||||
Drive {
|
||||
throttle: axis(self.throttle_forward, self.throttle_back),
|
||||
steer: axis(self.steer_left, self.steer_right),
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds this frame's camera motion and consumes the accumulated look deltas.
|
||||
pub(crate) fn motion(&mut self, seconds: f32) -> Motion {
|
||||
let [yaw, pitch] = self.turn;
|
||||
self.turn = [0.0, 0.0];
|
||||
|
|
|
|||
|
|
@ -3,8 +3,11 @@
|
|||
use core::f32::consts::FRAC_PI_2;
|
||||
|
||||
use fabrilis_core::math;
|
||||
use winit::keyboard::KeyCode;
|
||||
|
||||
use super::input::Controls;
|
||||
use super::{FlyCamera, MOVE_SPEED, Motion, PITCH_LIMIT};
|
||||
use crate::runtime::sim::Drive;
|
||||
|
||||
fn close(actual: f32, expected: f32) -> bool {
|
||||
(actual - expected).abs() < 1.0e-4
|
||||
|
|
@ -81,6 +84,60 @@ fn lift_moves_only_vertically() {
|
|||
assert!(close(after[2] - before[2], -MOVE_SPEED * 0.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn w_and_s_set_the_cart_throttle() {
|
||||
let mut controls = Controls::default();
|
||||
controls.key(KeyCode::KeyW, true);
|
||||
assert_eq!(controls.drive().throttle, 1.0);
|
||||
controls.key(KeyCode::KeyW, false);
|
||||
controls.key(KeyCode::KeyS, true);
|
||||
assert_eq!(controls.drive().throttle, -1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_and_d_steer_the_cart() {
|
||||
let mut controls = Controls::default();
|
||||
controls.key(KeyCode::KeyA, true);
|
||||
assert_eq!(controls.drive().steer, 1.0, "A steers left");
|
||||
controls.key(KeyCode::KeyA, false);
|
||||
controls.key(KeyCode::KeyD, true);
|
||||
assert_eq!(controls.drive().steer, -1.0, "D steers right");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrows_move_the_camera_but_not_the_cart() {
|
||||
let mut controls = Controls::default();
|
||||
controls.key(KeyCode::ArrowUp, true);
|
||||
assert_eq!(controls.drive(), Drive::default());
|
||||
assert_eq!(controls.motion(1.0).forward, 1.0);
|
||||
controls.key(KeyCode::ArrowUp, false);
|
||||
controls.key(KeyCode::KeyW, true);
|
||||
assert_eq!(controls.drive().throttle, 1.0);
|
||||
assert_eq!(controls.motion(1.0).forward, 0.0, "W drives the cart");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_and_d_no_longer_strafe_the_camera() {
|
||||
let mut controls = Controls::default();
|
||||
controls.key(KeyCode::KeyA, true);
|
||||
controls.key(KeyCode::KeyD, true);
|
||||
assert_eq!(controls.motion(1.0).strafe, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_all_drops_drive_and_camera_keys() {
|
||||
let mut controls = Controls::default();
|
||||
controls.key(KeyCode::KeyW, true);
|
||||
controls.key(KeyCode::KeyA, true);
|
||||
controls.key(KeyCode::ArrowLeft, true);
|
||||
controls.key(KeyCode::ArrowUp, true);
|
||||
controls.release_all();
|
||||
assert_eq!(controls.drive(), Drive::default());
|
||||
let motion = controls.motion(1.0);
|
||||
assert_eq!(motion.forward, 0.0);
|
||||
assert_eq!(motion.strafe, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_multiplies_movement_speed() {
|
||||
let mut slow = level_camera();
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
//! Dev text log: wall-clock stamped lines with a level, a target and a message.
|
||||
//! Dev text log: a [`LogSink`] that writes wall-clock stamped lines.
|
||||
//!
|
||||
//! The logger is a diagnostic observer. It is off unless `--dev`, `--log` or a
|
||||
//! matching environment variable asks for it, and it never feeds data back into
|
||||
//! the simulation.
|
||||
//! the simulation. The app installs [`DevLogSink`] into the `fabrilis_core::log`
|
||||
//! facade before the startup banner, so every record goes through one filter.
|
||||
//!
|
||||
//! Line shape: `unix_s level target message`.
|
||||
|
||||
|
|
@ -14,68 +15,32 @@ mod tests;
|
|||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, Write};
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use crate::runtime::metrics::Stats;
|
||||
use fabrilis_core::log::{Level, LogSink, Record};
|
||||
|
||||
/// How much detail the log records.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(crate) enum Level {
|
||||
Error,
|
||||
Warn,
|
||||
Info,
|
||||
Debug,
|
||||
#[allow(
|
||||
dead_code,
|
||||
reason = "trace belongs to the documented level set; --dev stops at debug"
|
||||
)]
|
||||
Trace,
|
||||
}
|
||||
|
||||
impl Level {
|
||||
/// Lower bounds `self`, so `self.rank() <= limit.rank()` means "log it".
|
||||
fn rank(self) -> u8 {
|
||||
match self {
|
||||
Self::Error => 0,
|
||||
Self::Warn => 1,
|
||||
Self::Info => 2,
|
||||
Self::Debug => 3,
|
||||
Self::Trace => 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl core::fmt::Display for Level {
|
||||
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
let name = match self {
|
||||
Self::Error => "error",
|
||||
Self::Warn => "warn",
|
||||
Self::Info => "info",
|
||||
Self::Debug => "debug",
|
||||
Self::Trace => "trace",
|
||||
};
|
||||
formatter.write_str(name)
|
||||
}
|
||||
}
|
||||
use crate::runtime::metrics::{FrameDetail, Stats};
|
||||
|
||||
/// How often a metrics summary line is written, seconds.
|
||||
const SUMMARY_INTERVAL_SECONDS: u64 = 1;
|
||||
|
||||
/// A dev log file, truncated or created when opened.
|
||||
///
|
||||
/// The facade already applies the level filter, so the log writes every record
|
||||
/// it receives.
|
||||
pub(crate) struct DevLog {
|
||||
file: File,
|
||||
level: Level,
|
||||
last_summary: Instant,
|
||||
}
|
||||
|
||||
impl DevLog {
|
||||
/// Creates or opens the file, truncating it unless `append` is set, and
|
||||
/// records `level` as the most detailed level to write.
|
||||
/// Creates or opens the file, truncating it unless `append` is set.
|
||||
#[allow(
|
||||
clippy::disallowed_methods,
|
||||
reason = "the dev log is a wall-clock observer of the app loop"
|
||||
)]
|
||||
pub(crate) fn open(path: &Path, level: Level, append: bool) -> io::Result<Self> {
|
||||
pub(crate) fn open(path: &Path, append: bool) -> io::Result<Self> {
|
||||
let file = OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
|
|
@ -84,16 +49,12 @@ impl DevLog {
|
|||
.open(path)?;
|
||||
Ok(Self {
|
||||
file,
|
||||
level,
|
||||
last_summary: Instant::now(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Writes one line and flushes it, so the log survives a crash.
|
||||
pub(crate) fn write(&mut self, level: Level, target: &str, message: &str) -> io::Result<()> {
|
||||
if level.rank() > self.level.rank() {
|
||||
return Ok(());
|
||||
}
|
||||
let line = format_line(unix_now(), level, target, message);
|
||||
writeln!(self.file, "{line}")?;
|
||||
self.file.flush()
|
||||
|
|
@ -113,6 +74,35 @@ impl DevLog {
|
|||
}
|
||||
}
|
||||
|
||||
/// [`LogSink`] adapter over the shared dev log file.
|
||||
pub(crate) struct DevLogSink {
|
||||
log: Arc<Mutex<DevLog>>,
|
||||
}
|
||||
|
||||
impl DevLogSink {
|
||||
pub(crate) fn new(log: Arc<Mutex<DevLog>>) -> Self {
|
||||
Self { log }
|
||||
}
|
||||
}
|
||||
|
||||
impl LogSink for DevLogSink {
|
||||
fn log(&self, record: &Record<'_>) {
|
||||
let message = record.message.to_string();
|
||||
let mut log = lock(&self.log);
|
||||
if let Err(error) = log.write(record.level, record.target, &message) {
|
||||
eprintln!("fabrilis: dev log write failed: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Locks the shared dev log, recovering a poisoned mutex without panicking.
|
||||
pub(crate) fn lock(log: &Mutex<DevLog>) -> MutexGuard<'_, DevLog> {
|
||||
match log.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Formats one log line without the trailing newline.
|
||||
pub(crate) fn format_line(unix_s: f64, level: Level, target: &str, message: &str) -> String {
|
||||
format!("{unix_s:.3} {level} {target} {message}")
|
||||
|
|
@ -137,8 +127,21 @@ pub(crate) fn summary(stats: &Stats) -> String {
|
|||
}
|
||||
|
||||
/// One-line description of a frame that exceeded its budget.
|
||||
pub(crate) fn spike(frame: u64, frame_ms: f32, step_ms: f32, trigger: &str) -> String {
|
||||
format!("frame={frame} frame_ms={frame_ms:.2} physics_step_ms={step_ms:.3} trigger={trigger}")
|
||||
///
|
||||
/// The phase fields tell a slow simulation apart from a slow renderer, an
|
||||
/// expensive overlay or title update, and the `/proc` sampling cost. A frame
|
||||
/// with small phases but a large `frame_ms` was delayed outside the app.
|
||||
pub(crate) fn spike(frame: u64, detail: &FrameDetail, trigger: &str) -> String {
|
||||
format!(
|
||||
"frame={frame} frame_ms={:.2} physics_step_ms={:.3} render_ms={:.2} overlay_ms={:.2} title_ms={:.2} metrics_us={:.0} steps={} trigger={trigger}",
|
||||
detail.frame_ms,
|
||||
detail.physics_step_ms,
|
||||
detail.render_ms,
|
||||
detail.overlay_ms,
|
||||
detail.title_ms,
|
||||
detail.metrics_us,
|
||||
detail.steps,
|
||||
)
|
||||
}
|
||||
|
||||
/// Wall-clock seconds since the Unix epoch, as a float.
|
||||
|
|
|
|||
|
|
@ -1,19 +1,21 @@
|
|||
//! Startup banner for the dev log: versions, window, world, bodies and GPU.
|
||||
//!
|
||||
//! The banner is written through the log facade, so it only appears when a sink
|
||||
//! was installed and the app level allows `info`.
|
||||
|
||||
use std::io;
|
||||
|
||||
use fabrilis_core::log::info;
|
||||
use fabrilis_core::vec::Vec3;
|
||||
use fabrilis_worldgen::terrain::TerrainConfig;
|
||||
|
||||
use super::{DevLog, Level};
|
||||
|
||||
/// Everything the startup lines report, gathered before the loop starts.
|
||||
pub(crate) struct StartupInfo<'a> {
|
||||
pub(crate) window: (u32, u32),
|
||||
pub(crate) scale: f64,
|
||||
pub(crate) terrain: TerrainConfig,
|
||||
pub(crate) boxes: usize,
|
||||
pub(crate) box_mass_kg: f64,
|
||||
pub(crate) box_size_m: f64,
|
||||
pub(crate) cart_mass_kg: f64,
|
||||
pub(crate) wheels: usize,
|
||||
pub(crate) wheel_radius_m: f64,
|
||||
pub(crate) spawn: Vec3,
|
||||
pub(crate) eye: [f32; 3],
|
||||
pub(crate) target: [f32; 3],
|
||||
pub(crate) adapter: &'a str,
|
||||
|
|
@ -26,41 +28,51 @@ pub(crate) struct StartupInfo<'a> {
|
|||
}
|
||||
|
||||
/// Writes the startup banner, one line per fact.
|
||||
pub(crate) fn write(log: &mut DevLog, info: &StartupInfo<'_>) -> io::Result<()> {
|
||||
pub(crate) fn write(info: &StartupInfo<'_>) {
|
||||
let terrain = info.terrain;
|
||||
let [width, height] = [info.window.0, info.window.1];
|
||||
let [x, y, z] = info.eye;
|
||||
let [tx, ty, tz] = info.target;
|
||||
let lines = [
|
||||
format!(
|
||||
"fabrilis-app {} {} {}",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
std::env::consts::OS,
|
||||
std::env::consts::ARCH
|
||||
),
|
||||
format!("window {width}x{height} scale {:.2}", info.scale),
|
||||
format!(
|
||||
"terrain seed={} size={} extent={:.1} height_scale={:.1}",
|
||||
terrain.seed, terrain.size, terrain.extent, terrain.height_scale
|
||||
),
|
||||
format!(
|
||||
"boxes={} mass={:.1} kg size={:.2} m",
|
||||
info.boxes, info.box_mass_kg, info.box_size_m
|
||||
),
|
||||
format!("camera eye=[{x:.2}, {y:.2}, {z:.2}] target=[{tx:.2}, {ty:.2}, {tz:.2}]"),
|
||||
format!("gpu adapter {}", info.adapter),
|
||||
format!("gpu driver {}", info.driver),
|
||||
format!("gpu surface {}", info.surface),
|
||||
format!(
|
||||
"metrics_log {} append={} dev={}",
|
||||
info.metrics_path.unwrap_or("off"),
|
||||
info.append,
|
||||
info.dev
|
||||
),
|
||||
format!("log {}", info.log_path.unwrap_or("off")),
|
||||
];
|
||||
for line in &lines {
|
||||
log.write(Level::Info, "startup", line)?;
|
||||
}
|
||||
Ok(())
|
||||
let spawn = info.spawn;
|
||||
info!(
|
||||
"startup",
|
||||
"fabrilis-app {} {} {}",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
std::env::consts::OS,
|
||||
std::env::consts::ARCH
|
||||
);
|
||||
info!("startup", "window {width}x{height} scale {:.2}", info.scale);
|
||||
info!(
|
||||
"startup",
|
||||
"terrain seed={} size={} extent={:.1} height_scale={:.1}",
|
||||
terrain.seed,
|
||||
terrain.size,
|
||||
terrain.extent,
|
||||
terrain.height_scale
|
||||
);
|
||||
info!(
|
||||
"startup",
|
||||
"cart mass={:.1} kg wheels={} wheel_radius={:.2} m spawn=[{:.2}, {:.2}, {:.2}]",
|
||||
info.cart_mass_kg,
|
||||
info.wheels,
|
||||
info.wheel_radius_m,
|
||||
spawn.x,
|
||||
spawn.y,
|
||||
spawn.z
|
||||
);
|
||||
info!(
|
||||
"startup",
|
||||
"camera eye=[{x:.2}, {y:.2}, {z:.2}] target=[{tx:.2}, {ty:.2}, {tz:.2}]"
|
||||
);
|
||||
info!("startup", "gpu adapter {}", info.adapter);
|
||||
info!("startup", "gpu driver {}", info.driver);
|
||||
info!("startup", "gpu surface {}", info.surface);
|
||||
info!(
|
||||
"startup",
|
||||
"metrics_log {} append={} dev={}",
|
||||
info.metrics_path.unwrap_or("off"),
|
||||
info.append,
|
||||
info.dev
|
||||
);
|
||||
info!("startup", "log {}", info.log_path.unwrap_or("off"));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,24 @@
|
|||
//! Tests for the dev log line format and its file lifecycle.
|
||||
//! Tests for the dev log line format, its file lifecycle and the facade hookup.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
|
||||
use fabrilis_core::log::{clear_sink, debug, info, set_level, set_sink};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Serializes tests that touch the process-wide log facade.
|
||||
static FACADE: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Acquires the facade lock, recovering it after a failed test.
|
||||
fn facade_lock() -> MutexGuard<'static, ()> {
|
||||
match FACADE.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
}
|
||||
}
|
||||
|
||||
struct TempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
|
@ -60,8 +74,20 @@ fn the_summary_and_spike_lines_are_stable() {
|
|||
"fps=60.0 tps=999.5 frame=16.25/20.50 ms physics=0.50/1.25 ms render=2.00 ms rtf=1.00 cpu=12.5% load1=0.75 rss=312.5 MB"
|
||||
);
|
||||
assert_eq!(
|
||||
spike(42, 25.1, 1.25, "frame+physics"),
|
||||
"frame=42 frame_ms=25.10 physics_step_ms=1.250 trigger=frame+physics"
|
||||
spike(
|
||||
42,
|
||||
&FrameDetail {
|
||||
frame_ms: 25.1,
|
||||
physics_step_ms: 1.25,
|
||||
render_ms: 3.5,
|
||||
overlay_ms: 0.4,
|
||||
title_ms: 0.02,
|
||||
metrics_us: 75.0,
|
||||
steps: 48,
|
||||
},
|
||||
"frame+physics"
|
||||
),
|
||||
"frame=42 frame_ms=25.10 physics_step_ms=1.250 render_ms=3.50 overlay_ms=0.40 title_ms=0.02 metrics_us=75 steps=48 trigger=frame+physics"
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -70,7 +96,7 @@ fn writing_creates_then_truncates_the_file() {
|
|||
let dir = TempDir::new("create");
|
||||
let path = dir.path.join("fabrilis-dev.log");
|
||||
{
|
||||
let mut log = DevLog::open(&path, Level::Debug, false).expect("create the log");
|
||||
let mut log = DevLog::open(&path, false).expect("create the log");
|
||||
log.write(Level::Info, "app", "first run").expect("write");
|
||||
}
|
||||
assert!(path.is_file(), "the log file exists");
|
||||
|
|
@ -78,7 +104,7 @@ fn writing_creates_then_truncates_the_file() {
|
|||
assert_eq!(first.lines().count(), 1);
|
||||
assert!(first.ends_with(" info app first run\n"));
|
||||
{
|
||||
let mut log = DevLog::open(&path, Level::Debug, false).expect("truncate the log");
|
||||
let mut log = DevLog::open(&path, false).expect("truncate the log");
|
||||
log.write(Level::Warn, "app", "second run").expect("write");
|
||||
}
|
||||
let second = std::fs::read_to_string(&path).expect("read");
|
||||
|
|
@ -91,11 +117,11 @@ fn append_keeps_the_previous_lines() {
|
|||
let dir = TempDir::new("append");
|
||||
let path = dir.path.join("fabrilis-dev.log");
|
||||
{
|
||||
let mut log = DevLog::open(&path, Level::Debug, false).expect("create the log");
|
||||
let mut log = DevLog::open(&path, false).expect("create the log");
|
||||
log.write(Level::Info, "app", "first").expect("write");
|
||||
}
|
||||
{
|
||||
let mut log = DevLog::open(&path, Level::Debug, true).expect("append the log");
|
||||
let mut log = DevLog::open(&path, true).expect("append the log");
|
||||
log.write(Level::Info, "app", "second").expect("write");
|
||||
}
|
||||
let text = std::fs::read_to_string(&path).expect("read");
|
||||
|
|
@ -104,15 +130,18 @@ fn append_keeps_the_previous_lines() {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn levels_above_the_limit_are_dropped() {
|
||||
fn the_facade_drops_levels_above_the_maximum_before_the_sink() {
|
||||
let _guard = facade_lock();
|
||||
let dir = TempDir::new("levels");
|
||||
let path = dir.path.join("fabrilis-dev.log");
|
||||
{
|
||||
let mut log = DevLog::open(&path, Level::Info, false).expect("create the log");
|
||||
log.write(Level::Debug, "app", "too detailed")
|
||||
.expect("write");
|
||||
log.write(Level::Info, "app", "kept").expect("write");
|
||||
}
|
||||
let log = Arc::new(Mutex::new(
|
||||
DevLog::open(&path, false).expect("create the log"),
|
||||
));
|
||||
set_level(Level::Info);
|
||||
set_sink(Arc::new(DevLogSink::new(log)));
|
||||
debug!("app", "too detailed");
|
||||
info!("app", "kept");
|
||||
clear_sink();
|
||||
let text = std::fs::read_to_string(&path).expect("read");
|
||||
assert_eq!(text.lines().count(), 1);
|
||||
assert!(text.contains("kept"));
|
||||
|
|
|
|||
|
|
@ -32,6 +32,22 @@ pub(crate) struct FrameWork {
|
|||
pub(crate) steps: u32,
|
||||
}
|
||||
|
||||
/// Timings of one observed frame, written next to a spike.
|
||||
///
|
||||
/// The fields separate the phases a late frame can come from: simulation,
|
||||
/// rendering, overlay building and window title updates, plus the cost of the
|
||||
/// `/proc` sample taken by [`Metrics::record`].
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub(crate) struct FrameDetail {
|
||||
pub(crate) frame_ms: f32,
|
||||
pub(crate) physics_step_ms: f32,
|
||||
pub(crate) render_ms: f32,
|
||||
pub(crate) overlay_ms: f32,
|
||||
pub(crate) title_ms: f32,
|
||||
pub(crate) metrics_us: f32,
|
||||
pub(crate) steps: u32,
|
||||
}
|
||||
|
||||
/// One frame in the rolling statistics window.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct Sample {
|
||||
|
|
@ -92,6 +108,7 @@ pub(crate) struct Metrics {
|
|||
rtf: Option<f32>,
|
||||
primed: bool,
|
||||
stats: Stats,
|
||||
last_sample: Duration,
|
||||
}
|
||||
|
||||
impl Default for Metrics {
|
||||
|
|
@ -116,6 +133,7 @@ impl Metrics {
|
|||
rtf: None,
|
||||
primed: false,
|
||||
stats: Stats::default(),
|
||||
last_sample: Duration::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -152,7 +170,9 @@ impl Metrics {
|
|||
let physics_ms = work.physics.as_secs_f32() * 1000.0;
|
||||
let render_ms = work.render.as_secs_f32() * 1000.0;
|
||||
self.clock += frame.as_secs_f32();
|
||||
let sample_start = Stopwatch::start();
|
||||
let sample: ProcSample = proc::sample();
|
||||
self.last_sample = sample_start.elapsed();
|
||||
let cpu_ticks = match (sample.ticks, self.last_ticks) {
|
||||
(Some(now), Some(before)) => u32::try_from(now.saturating_sub(before)).unwrap_or(0),
|
||||
_ => 0,
|
||||
|
|
@ -180,6 +200,11 @@ impl Metrics {
|
|||
self.stats
|
||||
}
|
||||
|
||||
/// How long the `/proc` sample of the latest frame took.
|
||||
pub(crate) fn sample_time(&self) -> Duration {
|
||||
self.last_sample
|
||||
}
|
||||
|
||||
/// Drops samples that fell out of the statistics window.
|
||||
fn trim(&mut self) {
|
||||
while self.window.len() > 1 {
|
||||
|
|
|
|||
|
|
@ -12,7 +12,6 @@ mod sim;
|
|||
|
||||
pub use error::AppError;
|
||||
|
||||
use devlog::DevLog;
|
||||
use devlog::startup::StartupInfo;
|
||||
use gpu::WindowRenderer;
|
||||
use scene::View;
|
||||
|
|
@ -52,17 +51,14 @@ fn open_csv(config: &Config) -> Result<Option<CsvLog>, AppError> {
|
|||
.map_err(|error| AppError::Log(format!("{}: {error}", path.display())))
|
||||
}
|
||||
|
||||
/// Writes the startup banner, reporting a write failure without stopping the app.
|
||||
/// Writes the startup banner through the log facade.
|
||||
fn log_startup(
|
||||
dev: Option<&mut DevLog>,
|
||||
config: &Config,
|
||||
view: &View,
|
||||
renderer: &WindowRenderer,
|
||||
window: &Window,
|
||||
simulation: &sim::Simulation,
|
||||
) {
|
||||
let Some(dev) = dev else {
|
||||
return;
|
||||
};
|
||||
let gpu = renderer.info();
|
||||
let size = window.inner_size();
|
||||
let metrics_path = config
|
||||
|
|
@ -70,13 +66,15 @@ fn log_startup(
|
|||
.as_ref()
|
||||
.map(|path| path.display().to_string());
|
||||
let log_path = config.log.as_ref().map(|path| path.display().to_string());
|
||||
let cart = simulation.cart_info();
|
||||
let info = StartupInfo {
|
||||
window: (size.width, size.height),
|
||||
scale: window.scale_factor(),
|
||||
terrain: view.terrain_config,
|
||||
boxes: sim::DROPS.len(),
|
||||
box_mass_kg: sim::BOX_MASS,
|
||||
box_size_m: sim::BOX_SIZE,
|
||||
cart_mass_kg: cart.mass_kg,
|
||||
wheels: cart.wheels,
|
||||
wheel_radius_m: cart.wheel_radius_m,
|
||||
spawn: cart.spawn,
|
||||
eye: view.camera.eye(),
|
||||
target: view.camera.target(),
|
||||
adapter: &gpu.adapter,
|
||||
|
|
@ -87,9 +85,7 @@ fn log_startup(
|
|||
dev: config.dev,
|
||||
append: config.append,
|
||||
};
|
||||
if let Err(error) = devlog::startup::write(dev, &info) {
|
||||
eprintln!("fabrilis: dev log write failed: {error}");
|
||||
}
|
||||
devlog::startup::write(&info);
|
||||
}
|
||||
|
||||
fn aspect(size: winit::dpi::PhysicalSize<u32>) -> f32 {
|
||||
|
|
|
|||
|
|
@ -1,11 +1,16 @@
|
|||
//! The seeded world shown by the window: terrain, camera and collider mesh.
|
||||
|
||||
use fabrilis_core::log::debug;
|
||||
use fabrilis_core::vec::Vec3;
|
||||
use fabrilis_render::{MeshData, Scene};
|
||||
use fabrilis_worldgen::terrain::{Heightmap, TerrainConfig, TerrainMesh};
|
||||
use fabrilis_worldgen::terrain::{Heightmap, LodConfig, TerrainConfig, TerrainMesh};
|
||||
|
||||
use super::AppError;
|
||||
use super::camera::FlyCamera;
|
||||
|
||||
/// Distance the camera must travel before the render LOD is rebuilt, m.
|
||||
const LOD_REBUILD_M: f32 = 4.0;
|
||||
|
||||
/// Render scene plus the geometry and camera state shared with physics.
|
||||
pub(crate) struct View {
|
||||
pub scene: Scene,
|
||||
|
|
@ -14,6 +19,36 @@ pub(crate) struct View {
|
|||
pub terrain: TerrainMesh,
|
||||
/// The parameters the heightmap was generated from.
|
||||
pub terrain_config: TerrainConfig,
|
||||
/// Where the render LOD was last built from, world X and Y.
|
||||
pub lod_center: [f32; 2],
|
||||
/// Tuning of the chunked render LOD.
|
||||
pub lod_config: LodConfig,
|
||||
}
|
||||
|
||||
impl View {
|
||||
/// Rebuilds the render terrain when the camera moved far enough.
|
||||
///
|
||||
/// Returns `false` while the camera stays inside [`LOD_REBUILD_M`], so most
|
||||
/// frames pay one distance check. The physics collider in `terrain` is never
|
||||
/// touched: only the picture uses the reduced mesh.
|
||||
pub(crate) fn update_terrain_lod(&mut self, eye: [f32; 3]) -> bool {
|
||||
let dx = eye[0] - self.lod_center[0];
|
||||
let dy = eye[1] - self.lod_center[1];
|
||||
if dx * dx + dy * dy < LOD_REBUILD_M * LOD_REBUILD_M {
|
||||
return false;
|
||||
}
|
||||
self.lod_center = [eye[0], eye[1]];
|
||||
let center = Vec3::new(f64::from(eye[0]), f64::from(eye[1]), 0.0);
|
||||
self.scene.mesh = mesh_data(&self.heightmap.mesh_lod(center, self.lod_config));
|
||||
debug!(
|
||||
"terrain",
|
||||
"lod_x={:.1} lod_y={:.1} triangles={}",
|
||||
eye[0],
|
||||
eye[1],
|
||||
self.scene.mesh.triangle_count()
|
||||
);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the M4c slice: seeded heightmap terrain and a fly camera.
|
||||
|
|
@ -26,8 +61,30 @@ pub(crate) fn build(aspect: f32) -> Result<View, AppError> {
|
|||
..Default::default()
|
||||
};
|
||||
let heightmap = Heightmap::generate(config)?;
|
||||
// Physics keeps the full mesh; the renderer starts from the same LOD rule
|
||||
// the frame loop uses afterwards.
|
||||
let terrain = heightmap.mesh();
|
||||
let mesh = MeshData {
|
||||
let target = heightmap.height_at(0.0, 0.0) as f32;
|
||||
let camera = FlyCamera::look_at([10.0, -16.0, 7.5], [0.0, 0.0, target], aspect);
|
||||
let lod_config = LodConfig::default();
|
||||
let lod_center = [camera.eye()[0], camera.eye()[1]];
|
||||
let center = Vec3::new(f64::from(lod_center[0]), f64::from(lod_center[1]), 0.0);
|
||||
let lod = heightmap.mesh_lod(center, lod_config);
|
||||
let scene = Scene::new(mesh_data(&lod));
|
||||
Ok(View {
|
||||
scene,
|
||||
camera,
|
||||
heightmap,
|
||||
terrain,
|
||||
terrain_config: config,
|
||||
lod_center,
|
||||
lod_config,
|
||||
})
|
||||
}
|
||||
|
||||
/// Converts a world-space terrain mesh into the renderer's `f32` buffers.
|
||||
fn mesh_data(terrain: &TerrainMesh) -> MeshData {
|
||||
MeshData {
|
||||
vertices: terrain
|
||||
.vertices
|
||||
.iter()
|
||||
|
|
@ -38,15 +95,8 @@ pub(crate) fn build(aspect: f32) -> Result<View, AppError> {
|
|||
.iter()
|
||||
.flat_map(|triangle| triangle.iter().copied())
|
||||
.collect(),
|
||||
};
|
||||
let scene = Scene::new(mesh);
|
||||
let target = heightmap.height_at(0.0, 0.0) as f32;
|
||||
let camera = FlyCamera::look_at([10.0, -16.0, 7.5], [0.0, 0.0, target], aspect);
|
||||
Ok(View {
|
||||
scene,
|
||||
camera,
|
||||
heightmap,
|
||||
terrain,
|
||||
terrain_config: config,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
|
|
|||
41
crates/app/src/runtime/scene/tests.rs
Normal file
41
crates/app/src/runtime/scene/tests.rs
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
//! Tests for the render LOD state kept next to the scene.
|
||||
|
||||
use super::build;
|
||||
|
||||
/// The initial render mesh is the reduced LOD mesh, not the full collider.
|
||||
#[test]
|
||||
fn the_initial_scene_uses_the_lod_mesh() {
|
||||
let view = build(1.0).expect("the default world builds");
|
||||
let render = view.scene.mesh.triangle_count();
|
||||
let collider = view.terrain.indices.len() / 3;
|
||||
assert!(
|
||||
render < collider,
|
||||
"render {render} triangles should be below the full {collider}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A camera that does not move reuses the mesh and reports no rebuild.
|
||||
#[test]
|
||||
fn the_same_eye_keeps_the_render_mesh() {
|
||||
let mut view = build(1.0).expect("the default world builds");
|
||||
let before = view.scene.mesh.clone();
|
||||
assert!(!view.update_terrain_lod(view.camera.eye()));
|
||||
assert_eq!(view.scene.mesh, before);
|
||||
}
|
||||
|
||||
/// A ten-metre move changes the LOD mesh but never the physics collider.
|
||||
#[test]
|
||||
fn moving_ten_metres_rebuilds_only_the_render_mesh() {
|
||||
let mut view = build(1.0).expect("the default world builds");
|
||||
let before = view.scene.mesh.clone();
|
||||
let collider = view.terrain.clone();
|
||||
let eye = view.camera.eye();
|
||||
let moved = [eye[0] + 10.0, eye[1], eye[2]];
|
||||
assert!(view.update_terrain_lod(moved));
|
||||
assert_ne!(view.scene.mesh, before, "the LOD mesh was rebuilt");
|
||||
assert_eq!(
|
||||
view.terrain, collider,
|
||||
"the collider stays at full resolution"
|
||||
);
|
||||
assert_eq!(view.lod_center, [moved[0], moved[1]]);
|
||||
}
|
||||
265
crates/app/src/runtime/sim/cart.rs
Normal file
265
crates/app/src/runtime/sim/cart.rs
Normal file
|
|
@ -0,0 +1,265 @@
|
|||
//! The M4 cart: a chassis on four revolute wheels driven by velocity motors.
|
||||
//!
|
||||
//! Geometry is in the chassis frame: X forward, Y left, Z up
|
||||
//! (docs/COORDINATES.md). Wheels are balls so rolling contact is isotropic; the
|
||||
//! renderer draws them as unit cylinders with the axle along local Y.
|
||||
|
||||
use fabrilis_core::units::{Kilograms, RadiansPerSecond};
|
||||
use fabrilis_core::vec::{Quat, Transform, Vec3};
|
||||
use fabrilis_physics::{
|
||||
BodyDesc, BodyId, JointId, PhysicsBackend, RapierBackend, RevoluteDesc, ShapeDesc,
|
||||
};
|
||||
use fabrilis_render::{Instance, Scene};
|
||||
use fabrilis_worldgen::terrain::Heightmap;
|
||||
|
||||
/// Chassis half extents in its local frame, metres.
|
||||
const CHASSIS_HALF_EXTENTS: Vec3 = Vec3::new(0.8, 0.55, 0.15);
|
||||
|
||||
/// Chassis mass, kilograms.
|
||||
const CHASSIS_MASS_KG: f64 = 60.0;
|
||||
|
||||
/// Mass of one wheel, kilograms.
|
||||
const WHEEL_MASS_KG: f64 = 4.0;
|
||||
|
||||
/// Wheel radius, metres.
|
||||
pub(crate) const WHEEL_RADIUS_M: f64 = 0.30;
|
||||
|
||||
/// Wheel width along its axle, metres.
|
||||
const WHEEL_WIDTH_M: f64 = 0.20;
|
||||
|
||||
/// Wheels of the cart.
|
||||
const WHEEL_COUNT: usize = 4;
|
||||
|
||||
/// Wheel mount drop below the chassis centre, metres.
|
||||
const WHEEL_DROP_M: f64 = 0.35;
|
||||
|
||||
/// Wheel centres in the chassis frame and the side of the cart they sit on.
|
||||
const WHEEL_MOUNTS: [(Vec3, Side); WHEEL_COUNT] = [
|
||||
(Vec3::new(0.55, 0.62, -WHEEL_DROP_M), Side::Left),
|
||||
(Vec3::new(0.55, -0.62, -WHEEL_DROP_M), Side::Right),
|
||||
(Vec3::new(-0.55, 0.62, -WHEEL_DROP_M), Side::Left),
|
||||
(Vec3::new(-0.55, -0.62, -WHEEL_DROP_M), Side::Right),
|
||||
];
|
||||
|
||||
/// Extra drop between the wheel bottom and the terrain at spawn, metres.
|
||||
const SPAWN_CLEARANCE_M: f64 = 0.2;
|
||||
|
||||
/// Motor speed for full throttle, rad/s.
|
||||
const BASE_SPEED: f64 = 8.0;
|
||||
|
||||
/// Extra speed of the outer wheels for full steering, rad/s.
|
||||
const TURN_SPEED: f64 = 5.0;
|
||||
|
||||
/// Velocity-motor damping: how tightly the wheels follow the target.
|
||||
const MOTOR_FACTOR: f64 = 100.0;
|
||||
|
||||
/// Full chassis size for the renderer, metres.
|
||||
const CHASSIS_SIZE: [f32; 3] = [
|
||||
(CHASSIS_HALF_EXTENTS.x * 2.0) as f32,
|
||||
(CHASSIS_HALF_EXTENTS.y * 2.0) as f32,
|
||||
(CHASSIS_HALF_EXTENTS.z * 2.0) as f32,
|
||||
];
|
||||
|
||||
/// Full wheel size for the renderer's unit cylinder, metres.
|
||||
const WHEEL_SIZE: [f32; 3] = [
|
||||
(WHEEL_RADIUS_M * 2.0) as f32,
|
||||
WHEEL_WIDTH_M as f32,
|
||||
(WHEEL_RADIUS_M * 2.0) as f32,
|
||||
];
|
||||
|
||||
/// Warm chassis colour, linear RGBA.
|
||||
const CHASSIS_COLOR: [f32; 4] = [0.82, 0.40, 0.18, 1.0];
|
||||
|
||||
/// Dark wheel colour, linear RGBA.
|
||||
const WHEEL_COLOR: [f32; 4] = [0.10, 0.11, 0.13, 1.0];
|
||||
|
||||
/// Throttle and steering for one control interval.
|
||||
///
|
||||
/// Both inputs are in `[-1, 1]`: `throttle` drives both sides the same way and
|
||||
/// `steer` speeds one side up while slowing the other down. Zero throttle
|
||||
/// brakes the wheels to a stop.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub(crate) struct Drive {
|
||||
pub(crate) throttle: f32,
|
||||
pub(crate) steer: f32,
|
||||
}
|
||||
|
||||
/// Which side of the chassis a wheel is on.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Side {
|
||||
/// Left, `+Y`.
|
||||
Left,
|
||||
/// Right, `-Y`.
|
||||
Right,
|
||||
}
|
||||
|
||||
impl Side {
|
||||
/// Steering multiplies the turn speed: the outer side must spin faster.
|
||||
fn steer_sign(self) -> f64 {
|
||||
match self {
|
||||
Self::Left => -1.0,
|
||||
Self::Right => 1.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One wheel body and the hinge that ties it to the chassis.
|
||||
struct Wheel {
|
||||
body: BodyId,
|
||||
joint: JointId,
|
||||
side: Side,
|
||||
}
|
||||
|
||||
/// The chassis pose plus every joint angle, for golden hashes and diagnostics.
|
||||
#[allow(
|
||||
dead_code,
|
||||
reason = "read by the golden test and by the future headless CLI"
|
||||
)]
|
||||
pub(crate) struct CartPose {
|
||||
pub(crate) chassis: Transform,
|
||||
pub(crate) wheel_angles: [f64; WHEEL_COUNT],
|
||||
}
|
||||
|
||||
/// What the startup banner reports about the cart.
|
||||
pub(crate) struct CartInfo {
|
||||
/// Total mass of the chassis and its wheels, kilograms.
|
||||
pub(crate) mass_kg: f64,
|
||||
/// Number of wheels.
|
||||
pub(crate) wheels: usize,
|
||||
/// Wheel radius, metres.
|
||||
pub(crate) wheel_radius_m: f64,
|
||||
/// Initial chassis position, metres.
|
||||
pub(crate) spawn: Vec3,
|
||||
}
|
||||
|
||||
/// The chassis and its four motorised wheels.
|
||||
pub(crate) struct Cart {
|
||||
chassis: BodyId,
|
||||
wheels: [Wheel; WHEEL_COUNT],
|
||||
spawn: Vec3,
|
||||
}
|
||||
|
||||
impl Cart {
|
||||
/// Spawns the chassis above the terrain at `(0, 0)` and wheels it.
|
||||
pub(crate) fn new(
|
||||
backend: &mut RapierBackend,
|
||||
heightmap: &Heightmap,
|
||||
scene: &mut Scene,
|
||||
) -> Self {
|
||||
let spawn = Vec3::new(
|
||||
0.0,
|
||||
0.0,
|
||||
heightmap.height_at(0.0, 0.0) + WHEEL_RADIUS_M + WHEEL_DROP_M + SPAWN_CLEARANCE_M,
|
||||
);
|
||||
let chassis = backend.add_body(BodyDesc::dynamic(
|
||||
ShapeDesc::Cuboid {
|
||||
half_extents: CHASSIS_HALF_EXTENTS,
|
||||
},
|
||||
Kilograms::new(CHASSIS_MASS_KG),
|
||||
spawn,
|
||||
));
|
||||
scene.instances.clear();
|
||||
scene.wheels.clear();
|
||||
scene.instances.push(Instance::new(
|
||||
model(Transform::new(spawn, Quat::IDENTITY), CHASSIS_SIZE),
|
||||
CHASSIS_COLOR,
|
||||
));
|
||||
let wheels = core::array::from_fn(|index| {
|
||||
let (offset, side) = WHEEL_MOUNTS[index];
|
||||
let pose = Transform::new(spawn + offset, Quat::IDENTITY);
|
||||
let body = backend.add_body(BodyDesc::dynamic(
|
||||
ShapeDesc::Ball {
|
||||
radius: WHEEL_RADIUS_M,
|
||||
},
|
||||
Kilograms::new(WHEEL_MASS_KG),
|
||||
pose.position,
|
||||
));
|
||||
let joint = backend.add_revolute(RevoluteDesc::new(
|
||||
chassis,
|
||||
body,
|
||||
Vec3::Y,
|
||||
offset,
|
||||
Vec3::ZERO,
|
||||
));
|
||||
scene
|
||||
.wheels
|
||||
.push(Instance::new(model(pose, WHEEL_SIZE), WHEEL_COLOR));
|
||||
Wheel { body, joint, side }
|
||||
});
|
||||
Self {
|
||||
chassis,
|
||||
wheels,
|
||||
spawn,
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates every wheel motor; call before a batch of fixed steps.
|
||||
pub(crate) fn drive(&mut self, backend: &mut RapierBackend, drive: Drive) {
|
||||
let base = f64::from(drive.throttle) * BASE_SPEED;
|
||||
let turn = f64::from(drive.steer) * TURN_SPEED;
|
||||
for wheel in &self.wheels {
|
||||
let target = RadiansPerSecond::new(base + wheel.side.steer_sign() * turn);
|
||||
backend.set_motor_velocity(wheel.joint, target, MOTOR_FACTOR);
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies the body transforms into the chassis and wheel instances.
|
||||
pub(crate) fn sync(&self, backend: &RapierBackend, scene: &mut Scene) {
|
||||
if let Some(instance) = scene.instances.first_mut()
|
||||
&& let Some(transform) = backend.body_transform(self.chassis)
|
||||
{
|
||||
instance.model = model(transform, CHASSIS_SIZE);
|
||||
instance.color = CHASSIS_COLOR;
|
||||
}
|
||||
for (instance, wheel) in scene.wheels.iter_mut().zip(&self.wheels) {
|
||||
if let Some(transform) = backend.body_transform(wheel.body) {
|
||||
instance.model = model(transform, WHEEL_SIZE);
|
||||
instance.color = WHEEL_COLOR;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The current chassis pose and joint angles, or `None` if a body is gone.
|
||||
#[allow(
|
||||
dead_code,
|
||||
reason = "read by the golden test and by the future headless CLI"
|
||||
)]
|
||||
pub(crate) fn pose(&self, backend: &RapierBackend) -> Option<CartPose> {
|
||||
let chassis = backend.body_transform(self.chassis)?;
|
||||
let mut wheel_angles = [0.0; WHEEL_COUNT];
|
||||
for (angle, wheel) in wheel_angles.iter_mut().zip(&self.wheels) {
|
||||
*angle = backend.joint_angle(wheel.joint)?.get();
|
||||
}
|
||||
Some(CartPose {
|
||||
chassis,
|
||||
wheel_angles,
|
||||
})
|
||||
}
|
||||
|
||||
/// The facts the startup banner reports.
|
||||
pub(crate) fn info(&self) -> CartInfo {
|
||||
CartInfo {
|
||||
mass_kg: CHASSIS_MASS_KG + WHEEL_MASS_KG * WHEEL_COUNT as f64,
|
||||
wheels: self.wheels.len(),
|
||||
wheel_radius_m: WHEEL_RADIUS_M,
|
||||
spawn: self.spawn,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A column-major model matrix: rotate, scale along the local axes, translate.
|
||||
pub(crate) fn model(transform: Transform, size: [f32; 3]) -> [[f32; 4]; 4] {
|
||||
let [x, y, z] = transform.rotation.to_mat3().cols();
|
||||
let [sx, sy, sz] = size;
|
||||
let [px, py, pz] = [
|
||||
transform.position.x as f32,
|
||||
transform.position.y as f32,
|
||||
transform.position.z as f32,
|
||||
];
|
||||
[
|
||||
[x.x as f32 * sx, x.y as f32 * sx, x.z as f32 * sx, 0.0],
|
||||
[y.x as f32 * sy, y.y as f32 * sy, y.z as f32 * sy, 0.0],
|
||||
[z.x as f32 * sz, z.y as f32 * sz, z.z as f32 * sz, 0.0],
|
||||
[px, py, pz, 1.0],
|
||||
]
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
//! Fixed-step physics for the boxes shown in the window.
|
||||
//! Fixed-step physics for the cart shown in the window.
|
||||
|
||||
mod cart;
|
||||
mod pacing;
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
@ -8,45 +9,25 @@ mod tests;
|
|||
use std::time::Duration;
|
||||
|
||||
use fabrilis_core::time::SimDelta;
|
||||
use fabrilis_core::units::Kilograms;
|
||||
use fabrilis_core::vec::{Quat, Transform, Vec3};
|
||||
use fabrilis_physics::{BodyDesc, BodyId, PhysicsBackend, RapierBackend, ShapeDesc, TrimeshDesc};
|
||||
use fabrilis_render::{Instance, Scene};
|
||||
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;
|
||||
|
||||
/// Edge length of each dropped box, metres.
|
||||
pub(crate) const BOX_SIZE: f64 = 0.6;
|
||||
|
||||
/// Mass of each dropped box, kilograms.
|
||||
pub(crate) const BOX_MASS: f64 = 4.0;
|
||||
|
||||
/// Horizontal offset and drop height above the terrain for each box.
|
||||
pub(crate) const DROPS: [(f64, f64, f64); 3] =
|
||||
[(-1.5, 0.4, 2.0), (1.2, -0.8, 3.6), (0.2, 1.8, 5.2)];
|
||||
|
||||
/// One colour per box, linear RGBA.
|
||||
const COLORS: [[f32; 4]; 3] = [
|
||||
[0.85, 0.35, 0.15, 1.0],
|
||||
[0.20, 0.55, 0.85, 1.0],
|
||||
[0.85, 0.75, 0.20, 1.0],
|
||||
];
|
||||
|
||||
struct BoxBody {
|
||||
id: BodyId,
|
||||
color: [f32; 4],
|
||||
}
|
||||
|
||||
/// The Rapier world and the boxes it drives.
|
||||
/// The Rapier world and the cart it drives.
|
||||
pub(crate) struct Simulation {
|
||||
backend: RapierBackend,
|
||||
boxes: Vec<BoxBody>,
|
||||
cart: Cart,
|
||||
step: SimDelta,
|
||||
pacer: Pacer,
|
||||
total_steps: u64,
|
||||
|
|
@ -54,7 +35,7 @@ pub(crate) struct Simulation {
|
|||
}
|
||||
|
||||
impl Simulation {
|
||||
/// Builds the terrain collider and drops the boxes into the scene.
|
||||
/// Builds the terrain collider and spawns the cart into the scene.
|
||||
pub(crate) fn new(
|
||||
terrain: &TerrainMesh,
|
||||
heightmap: &Heightmap,
|
||||
|
|
@ -73,29 +54,10 @@ impl Simulation {
|
|||
backend
|
||||
.add_trimesh(collider)
|
||||
.ok_or_else(|| AppError::Physics("terrain collider was rejected".to_owned()))?;
|
||||
scene.instances.clear();
|
||||
let mut boxes = Vec::with_capacity(DROPS.len());
|
||||
for (offset, color) in DROPS.iter().zip(COLORS) {
|
||||
let (x, y, drop) = *offset;
|
||||
let center = Vec3::new(x, y, heightmap.height_at(x, y) + drop + BOX_SIZE * 0.5);
|
||||
let id = backend.add_body(BodyDesc::dynamic(
|
||||
ShapeDesc::Cuboid {
|
||||
half_extents: Vec3::new(BOX_SIZE * 0.5, BOX_SIZE * 0.5, BOX_SIZE * 0.5),
|
||||
},
|
||||
Kilograms::new(BOX_MASS),
|
||||
center,
|
||||
));
|
||||
let size = BOX_SIZE as f32;
|
||||
scene.instances.push(Instance::box_at(
|
||||
[center.x as f32, center.y as f32, center.z as f32],
|
||||
[size, size, size],
|
||||
color,
|
||||
));
|
||||
boxes.push(BoxBody { id, color });
|
||||
}
|
||||
let cart = Cart::new(&mut backend, heightmap, scene);
|
||||
Ok(Self {
|
||||
backend,
|
||||
boxes,
|
||||
cart,
|
||||
step,
|
||||
pacer: Pacer::new(),
|
||||
total_steps: 0,
|
||||
|
|
@ -108,19 +70,31 @@ impl Simulation {
|
|||
/// 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) -> pacing::Frame {
|
||||
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));
|
||||
for _ in 0..frame.steps {
|
||||
let step_start = Stopwatch::start();
|
||||
self.backend.step(self.step);
|
||||
self.slowest_step = self.slowest_step.max(step_start.elapsed());
|
||||
}
|
||||
self.sync(scene);
|
||||
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 {
|
||||
|
|
@ -133,30 +107,28 @@ impl Simulation {
|
|||
self.slowest_step
|
||||
}
|
||||
|
||||
/// Copies every body transform into its rendered instance.
|
||||
fn sync(&self, scene: &mut Scene) {
|
||||
for (instance, body) in scene.instances.iter_mut().zip(&self.boxes) {
|
||||
let Some(transform) = self.backend.body_transform(body.id) else {
|
||||
continue;
|
||||
};
|
||||
instance.model = model(transform, BOX_SIZE as f32);
|
||||
instance.color = body.color;
|
||||
/// 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A column-major model matrix for a rotated, translated box.
|
||||
fn model(transform: Transform, size: f32) -> [[f32; 4]; 4] {
|
||||
let [x, y, z] = transform.rotation.to_mat3().cols();
|
||||
let [px, py, pz] = [
|
||||
transform.position.x as f32,
|
||||
transform.position.y as f32,
|
||||
transform.position.z as f32,
|
||||
];
|
||||
[
|
||||
[x.x as f32 * size, x.y as f32 * size, x.z as f32 * size, 0.0],
|
||||
[y.x as f32 * size, y.y as f32 * size, y.z as f32 * size, 0.0],
|
||||
[z.x as f32 * size, z.y as f32 * size, z.z as f32 * size, 0.0],
|
||||
[px, py, pz, 1.0],
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,77 @@
|
|||
//! Tests for the fixed-step accumulator.
|
||||
//! Tests for the fixed-step accumulator and the M4 cart.
|
||||
|
||||
use fabrilis_core::snapshot::hash::StateHasher;
|
||||
use fabrilis_core::vec::Vec3;
|
||||
use fabrilis_render::{MeshData, Scene};
|
||||
use fabrilis_worldgen::terrain::{Heightmap, TerrainConfig, TerrainMesh};
|
||||
|
||||
use super::pacing::{MAX_STEPS, steps_for};
|
||||
use super::{Drive, Simulation};
|
||||
|
||||
const STEP_NS: u64 = 1_000_000;
|
||||
|
||||
/// Straight-ahead throttle for a whole run.
|
||||
const FORWARD: Drive = Drive {
|
||||
throttle: 1.0,
|
||||
steer: 0.0,
|
||||
};
|
||||
|
||||
/// A flat map and an empty render scene, rebuilt for every simulation.
|
||||
fn flat_world() -> (Heightmap, Scene) {
|
||||
let config = TerrainConfig {
|
||||
seed: 7,
|
||||
size: 9,
|
||||
extent: 40.0,
|
||||
height_scale: 0.0,
|
||||
..Default::default()
|
||||
};
|
||||
let heightmap = Heightmap::generate(config).expect("heightmap");
|
||||
let scene = Scene::new(MeshData::default());
|
||||
(heightmap, scene)
|
||||
}
|
||||
|
||||
/// A cart on flat ground plus the scene its instances are written into.
|
||||
fn simulation() -> (Simulation, Scene) {
|
||||
let (heightmap, mut scene) = flat_world();
|
||||
let terrain = heightmap.mesh();
|
||||
let sim = Simulation::new(&terrain, &heightmap, &mut scene).expect("simulation");
|
||||
(sim, scene)
|
||||
}
|
||||
|
||||
/// A plane rising along +X; the spawn point at the origin is on its surface.
|
||||
fn sloped_terrain() -> TerrainMesh {
|
||||
let slope = 0.08;
|
||||
let half = 20.0;
|
||||
TerrainMesh {
|
||||
vertices: vec![
|
||||
Vec3::new(-half, -half, -half * slope),
|
||||
Vec3::new(half, -half, half * slope),
|
||||
Vec3::new(half, half, half * slope),
|
||||
Vec3::new(-half, half, -half * slope),
|
||||
],
|
||||
indices: vec![[0, 1, 2], [0, 2, 3]],
|
||||
}
|
||||
}
|
||||
|
||||
/// Hashes the chassis pose and all four joint angles of the current state.
|
||||
fn trajectory_hash(sim: &Simulation) -> u64 {
|
||||
let pose = sim.cart_pose().expect("cart pose");
|
||||
let mut hasher = StateHasher::new();
|
||||
let position = pose.chassis.position;
|
||||
hasher.write_f64(position.x);
|
||||
hasher.write_f64(position.y);
|
||||
hasher.write_f64(position.z);
|
||||
let rotation = pose.chassis.rotation;
|
||||
hasher.write_f64(rotation.w);
|
||||
hasher.write_f64(rotation.x);
|
||||
hasher.write_f64(rotation.y);
|
||||
hasher.write_f64(rotation.z);
|
||||
for angle in pose.wheel_angles {
|
||||
hasher.write_f64(angle);
|
||||
}
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_time_means_no_steps() {
|
||||
assert_eq!(steps_for(0, STEP_NS, MAX_STEPS), 0);
|
||||
|
|
@ -39,3 +107,92 @@ fn a_zero_step_cannot_run() {
|
|||
fn a_zero_cap_runs_nothing() {
|
||||
assert_eq!(steps_for(16_000_000, STEP_NS, 0), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_scene_holds_one_chassis_and_four_wheels() {
|
||||
let (mut sim, mut scene) = simulation();
|
||||
assert_eq!(scene.instances.len(), 1, "one chassis instance");
|
||||
assert_eq!(scene.wheels.len(), 4, "four wheel instances");
|
||||
let before = scene.instances.first().expect("chassis").model[3][0];
|
||||
sim.step_fixed(200, FORWARD);
|
||||
sim.advance(&mut scene, Drive::default());
|
||||
let after = scene.instances.first().expect("chassis").model[3][0];
|
||||
assert!(after > before, "the rendered chassis follows the body");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cart_drives_forward_on_flat_ground() {
|
||||
let (mut sim, _scene) = simulation();
|
||||
let start = sim.cart_pose().expect("start pose").chassis;
|
||||
sim.step_fixed(2000, FORWARD);
|
||||
let end = sim.cart_pose().expect("end pose").chassis;
|
||||
assert!(
|
||||
end.position.x - start.position.x > 1.0,
|
||||
"moved {:.3} m along X",
|
||||
end.position.x - start.position.x
|
||||
);
|
||||
assert!(end.position.z > 0.0, "the chassis stays above the terrain");
|
||||
let up = end.rotation.rotate(Vec3::Z);
|
||||
assert!(up.z > 0.7, "the cart is still upright: up.z={:.3}", up.z);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cart_drives_up_a_slope() {
|
||||
let (heightmap, mut scene) = flat_world();
|
||||
let terrain = sloped_terrain();
|
||||
let mut sim =
|
||||
Simulation::new(&terrain, &heightmap, &mut scene).expect("simulation on the slope");
|
||||
let start = sim.cart_pose().expect("start pose").chassis;
|
||||
sim.step_fixed(2000, FORWARD);
|
||||
let end = sim.cart_pose().expect("end pose").chassis;
|
||||
assert!(
|
||||
end.position.x - start.position.x > 0.5,
|
||||
"moved {:.3} m up the slope",
|
||||
end.position.x - start.position.x
|
||||
);
|
||||
let up = end.rotation.rotate(Vec3::Z);
|
||||
assert!(
|
||||
up.z > 0.5,
|
||||
"the cart is still upright on the slope: up.z={:.3}",
|
||||
up.z
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steering_left_turns_the_cart_left() {
|
||||
let (mut sim, _scene) = simulation();
|
||||
sim.step_fixed(
|
||||
2000,
|
||||
Drive {
|
||||
throttle: 1.0,
|
||||
steer: 1.0,
|
||||
},
|
||||
);
|
||||
let pose = sim.cart_pose().expect("end pose");
|
||||
let forward = pose.chassis.rotation.rotate(Vec3::X);
|
||||
assert!(
|
||||
forward.y > 0.1,
|
||||
"A leaves the heading turned towards +Y: forward.y={:.3}",
|
||||
forward.y
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_runs_match_bit_for_bit() {
|
||||
let (mut first, _) = simulation();
|
||||
let (mut second, _) = simulation();
|
||||
first.step_fixed(2000, FORWARD);
|
||||
second.step_fixed(2000, FORWARD);
|
||||
assert_eq!(trajectory_hash(&first), trajectory_hash(&second));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn golden_cart_trajectory_is_pinned() {
|
||||
let (mut sim, _scene) = simulation();
|
||||
sim.step_fixed(2000, FORWARD);
|
||||
let actual = trajectory_hash(&sim);
|
||||
assert_eq!(
|
||||
actual, 0x6475_1e5b_f483_b404,
|
||||
"actual cart hash is {actual:#018x}"
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue