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
10
README.md
10
README.md
|
|
@ -16,7 +16,9 @@
|
||||||
|---|---|
|
|---|---|
|
||||||
| M0 | workspace, правила кода (`tools/limits`), pre-commit |
|
| M0 | workspace, правила кода (`tools/limits`), pre-commit |
|
||||||
| M1 | ядро: СИ-единицы, целое время, детерминированная математика, планировщик, снимки |
|
| M1 | ядро: СИ-единицы, целое время, детерминированная математика, планировщик, снимки |
|
||||||
| M2 | в работе: своя векторная математика, RNG, один шарнир с мотором и датчиками |
|
| M2 | векторы, RNG, шарнир с мотором, датчики, PD-контур |
|
||||||
|
| M3 | импорт STL/OBJ, массы и инерция, материалы, RON-сцены, blob-store |
|
||||||
|
| M4 | рельеф и chunked LOD, wgpu-рендер, тележка на шарнирах, оверлей и логи |
|
||||||
|
|
||||||
План и критерии готовности: [TODO.md](TODO.md).
|
План и критерии готовности: [TODO.md](TODO.md).
|
||||||
|
|
||||||
|
|
@ -31,6 +33,12 @@ cargo clippy --workspace --all-targets -- -D warnings
|
||||||
Версия компилятора зафиксирована в `rust-toolchain.toml`. Правила кода
|
Версия компилятора зафиксирована в `rust-toolchain.toml`. Правила кода
|
||||||
проверяются в `build.rs` каждого crate'а, поэтому их нарушение ломает сборку.
|
проверяются в `build.rs` каждого crate'а, поэтому их нарушение ломает сборку.
|
||||||
|
|
||||||
|
## Управление
|
||||||
|
|
||||||
|
`WASD` — тележка (газ и поворот), стрелки — камера, `Q`/`E` — камера вниз/вверх,
|
||||||
|
`Shift` — ускоренная камера, левая кнопка мыши — обзор, `Escape` — выход.
|
||||||
|
Подробнее: [docs/UI.md](docs/UI.md).
|
||||||
|
|
||||||
## Документация
|
## Документация
|
||||||
|
|
||||||
Начать с [docs/README.md](docs/README.md): архитектура, решения, режимы, детерминизм,
|
Начать с [docs/README.md](docs/README.md): архитектура, решения, режимы, детерминизм,
|
||||||
|
|
|
||||||
26
TODO.md
26
TODO.md
|
|
@ -39,14 +39,18 @@
|
||||||
- [x] `worldgen`: высотная карта, коллайдеры (trimesh), golden-хеш; чанки — вместе с рендером
|
- [x] `worldgen`: высотная карта, коллайдеры (trimesh), golden-хеш; чанки — вместе с рендером
|
||||||
- [x] `render`: wgpu, окно, глубина, меш рельефа, инстансинг кубов, offscreen-тесты;
|
- [x] `render`: wgpu, окно, глубина, меш рельефа, инстансинг кубов, offscreen-тесты;
|
||||||
clipmap LOD — позже, отдельным шагом
|
clipmap LOD — позже, отдельным шагом
|
||||||
- [ ] `ui`: список команд рисования, glyph atlas, event-driven redraw, оверлей отладки
|
- [x] `ui`/оверлей: список команд рисования, glyph atlas, текст через `fontdue`,
|
||||||
(текст через `fontdue`, прямоугольники, линии, клип)
|
прямоугольники, линии, графики; event-driven redraw. Полный редактор — в crate `ui`
|
||||||
- [x] `app`: winit, окно 1280×720, событийный цикл, World-сцена с рельефом и кубом
|
- [x] `app`: winit, окно, событийный цикл, физика 1 кГц, камера, оверлей метрик
|
||||||
(физика в окне — следующий шаг)
|
- [x] тележка: корпус + 4 колеса на шарнирах, velocity-моторы, WASD, golden-хеш;
|
||||||
- [ ] профилировать простой: почему иногда подпрыгивает нагрузка при стоящих кубах
|
RTF 1.00 в окне, физика ~0.55 мс
|
||||||
(сон тел, островки контактов, оверлей); писать пики в лог (LOGGING.md)
|
- [x] chunked LOD рельефа с юбками: 2368 треугольников вместо 8192; физика на полном
|
||||||
- **DoD:** тележка едет по склону; RTF ≥ 1 на эталонной сцене (см. бюджет в
|
меше. Rings-clipmap — возможное продолжение (см. docs/ARCHITECTURE.md)
|
||||||
ARCHITECTURE.md); картинка не влияет на результат симуляции.
|
- [x] профилировать простой: причина — пропуски callback'ов композитора и внешние
|
||||||
|
заморозки, не приложение. Собственный кадр ~1.2 мс; в лог добавлены render/overlay/
|
||||||
|
title/metrics-фазы, заголовок обновляется раз в секунду (LOGGING.md)
|
||||||
|
- **DoD M4 выполнен:** тележка едет по склону (golden-тест + окно), RTF 1.00 на
|
||||||
|
эталонной сцене, физика ~0.55 мс; картинка не влияет на результат симуляции.
|
||||||
|
|
||||||
## M5 — Паук стоит и ходит
|
## M5 — Паук стоит и ходит
|
||||||
Цель: эталонный механизм, ради которого всё строится.
|
Цель: эталонный механизм, ради которого всё строится.
|
||||||
|
|
@ -113,10 +117,10 @@
|
||||||
- [ ] S5: интернет, дельты, переподключение, токен
|
- [ ] S5: интернет, дельты, переподключение, токен
|
||||||
|
|
||||||
## Диагностика и логи (сразу после M4d)
|
## Диагностика и логи (сразу после M4d)
|
||||||
- [ ] `core::log`: уровни, приёмник, макросы; выключенный уровень не форматирует строку
|
- [x] `core::log`: уровни, приёмник, макросы; выключенный уровень не форматирует строку
|
||||||
- [x] приложение: CSV метрик и dev-лог по флагам (`--metrics-log`, `--log`, `--dev`, `--append`)
|
- [x] приложение: CSV метрик и dev-лог по флагам (`--metrics-log`, `--log`, `--dev`, `--append`)
|
||||||
- [ ] `core::log`-фасад и приёмник: перевести приложение, затем добавлять логи в crate'ах
|
- [x] `core::log`-фасад и приёмник: приложение переведено; дальше добавлять логи в crate'ах
|
||||||
- [ ] логи в ключевых точках: старт и конфиг, деградации, ошибки, сводки раз в секунду, пики
|
- [x] логи в ключевых точках: старт и конфиг, деградации, ошибки, сводки раз в секунду, пики
|
||||||
- [ ] тест: golden-хеш симуляции не зависит от включённых логов
|
- [ ] тест: golden-хеш симуляции не зависит от включённых логов
|
||||||
- **DoD:** в библиотеках нет `println!`, `--dev` даёт debug/trace, обычный запуск — warn/info;
|
- **DoD:** в библиотеках нет `println!`, `--dev` даёт debug/trace, обычный запуск — warn/info;
|
||||||
выключенный уровень не строит строку
|
выключенный уровень не строит строку
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,14 @@
|
||||||
//! The application handler: window installation, resize, redraw and logging.
|
//! 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 std::time::Duration;
|
||||||
|
|
||||||
|
use fabrilis_core::log::{Level, error, info, set_level, set_sink, warn};
|
||||||
use fabrilis_render::Overlay;
|
use fabrilis_render::Overlay;
|
||||||
use winit::application::ApplicationHandler;
|
use winit::application::ApplicationHandler;
|
||||||
use winit::dpi::PhysicalSize;
|
use winit::dpi::PhysicalSize;
|
||||||
|
|
@ -13,29 +19,38 @@ use winit::window::{Window, WindowId};
|
||||||
|
|
||||||
use super::camera::Controls;
|
use super::camera::Controls;
|
||||||
use super::config::Config;
|
use super::config::Config;
|
||||||
use super::devlog::{self, DevLog, Level};
|
use super::devlog::{self, DevLog, DevLogSink};
|
||||||
use super::gpu::WindowRenderer;
|
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::scene::View;
|
||||||
use super::sim::Simulation;
|
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.
|
/// Runs the window loop until the user closes the window or presses Escape.
|
||||||
pub(super) fn run() -> Result<(), AppError> {
|
pub(super) fn run() -> Result<(), AppError> {
|
||||||
let config = super::parse_config();
|
let config = super::parse_config();
|
||||||
let csv = super::open_csv(&config)?;
|
let csv = super::open_csv(&config)?;
|
||||||
let level = if config.dev {
|
let level = if config.dev {
|
||||||
Level::Debug
|
Level::Trace
|
||||||
} else {
|
} else {
|
||||||
Level::Info
|
Level::Info
|
||||||
};
|
};
|
||||||
|
set_level(level);
|
||||||
let dev = match &config.log {
|
let dev = match &config.log {
|
||||||
Some(path) => Some(
|
Some(path) => Some(Arc::new(Mutex::new(
|
||||||
DevLog::open(path, level, config.append)
|
DevLog::open(path, config.append)
|
||||||
.map_err(|error| AppError::Log(format!("{}: {error}", path.display())))?,
|
.map_err(|error| AppError::Log(format!("{}: {error}", path.display())))?,
|
||||||
),
|
))),
|
||||||
None => None,
|
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()))?;
|
let event_loop = EventLoop::new().map_err(|error| AppError::EventLoop(error.to_string()))?;
|
||||||
event_loop.set_control_flow(ControlFlow::Poll);
|
event_loop.set_control_flow(ControlFlow::Poll);
|
||||||
let mut application = Fabrilis::new(config, csv, dev);
|
let mut application = Fabrilis::new(config, csv, dev);
|
||||||
|
|
@ -51,7 +66,7 @@ pub(super) fn run() -> Result<(), AppError> {
|
||||||
struct Fabrilis {
|
struct Fabrilis {
|
||||||
config: Config,
|
config: Config,
|
||||||
csv: Option<CsvLog>,
|
csv: Option<CsvLog>,
|
||||||
dev: Option<DevLog>,
|
dev: Option<Arc<Mutex<DevLog>>>,
|
||||||
frame: u64,
|
frame: u64,
|
||||||
window: Option<Arc<Window>>,
|
window: Option<Arc<Window>>,
|
||||||
renderer: Option<WindowRenderer>,
|
renderer: Option<WindowRenderer>,
|
||||||
|
|
@ -60,10 +75,11 @@ struct Fabrilis {
|
||||||
controls: Controls,
|
controls: Controls,
|
||||||
metrics: Metrics,
|
metrics: Metrics,
|
||||||
overlay: Overlay,
|
overlay: Overlay,
|
||||||
|
title_clock: Duration,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Fabrilis {
|
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 {
|
Self {
|
||||||
config,
|
config,
|
||||||
csv,
|
csv,
|
||||||
|
|
@ -76,6 +92,7 @@ impl Fabrilis {
|
||||||
controls: Controls::default(),
|
controls: Controls::default(),
|
||||||
metrics: Metrics::default(),
|
metrics: Metrics::default(),
|
||||||
overlay: Overlay::new(),
|
overlay: Overlay::new(),
|
||||||
|
title_clock: Duration::ZERO,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -91,7 +108,7 @@ impl Fabrilis {
|
||||||
let mut view = super::scene::build(aspect(window.inner_size()))?;
|
let mut view = super::scene::build(aspect(window.inner_size()))?;
|
||||||
let simulation = Simulation::new(&view.terrain, &view.heightmap, &mut view.scene)?;
|
let simulation = Simulation::new(&view.terrain, &view.heightmap, &mut view.scene)?;
|
||||||
let renderer = WindowRenderer::new(window.clone())?;
|
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.window = Some(window);
|
||||||
self.renderer = Some(renderer);
|
self.renderer = Some(renderer);
|
||||||
self.view = Some(view);
|
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) {
|
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;
|
return;
|
||||||
};
|
};
|
||||||
let Some(simulation) = self.simulation.as_mut() else {
|
let unix_s = self.csv.is_some().then(unix_now);
|
||||||
return;
|
|
||||||
};
|
|
||||||
let unix_s = if self.csv.is_some() {
|
|
||||||
Some(unix_now())
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
let frame_time = self.metrics.frame_time();
|
let frame_time = self.metrics.frame_time();
|
||||||
let physics_start = Stopwatch::start();
|
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 physics = physics_start.elapsed();
|
||||||
let slowest_step_ms = simulation.slowest_step().as_secs_f32() * 1000.0;
|
let slowest_step_ms = simulation.slowest_step().as_secs_f32() * 1000.0;
|
||||||
let sim_seconds = simulation.sim_seconds();
|
let sim_seconds = simulation.sim_seconds();
|
||||||
let motion = self.controls.motion(frame.elapsed_seconds);
|
let motion = self.controls.motion(frame.elapsed_seconds);
|
||||||
view.camera.apply(motion);
|
view.camera.apply(motion);
|
||||||
if let (Some(rtf), Some(window)) = (frame.rtf, &self.window) {
|
view.update_terrain_lod(view.camera.eye());
|
||||||
window.set_title(&format!("Fabrilis — RTF {rtf:.2}"));
|
let title = Self::update_title(
|
||||||
}
|
self.window.as_deref(),
|
||||||
|
&mut self.title_clock,
|
||||||
|
frame_time,
|
||||||
|
frame.rtf,
|
||||||
|
);
|
||||||
self.metrics.set_rtf(frame.rtf);
|
self.metrics.set_rtf(frame.rtf);
|
||||||
let camera = view.camera.view();
|
let camera = view.camera.view();
|
||||||
let size = self
|
let size = self.renderer.as_ref().map_or((0, 0), WindowRenderer::size);
|
||||||
.renderer
|
let overlay_start = Stopwatch::start();
|
||||||
.as_ref()
|
|
||||||
.map_or((0, 0), |renderer| renderer.size());
|
|
||||||
self.overlay.clear();
|
self.overlay.clear();
|
||||||
if size.0 > 0 && size.1 > 0 {
|
if size.0 > 0 && size.1 > 0 {
|
||||||
self.metrics.draw_panel(&mut self.overlay);
|
self.metrics.draw_panel(&mut self.overlay);
|
||||||
}
|
}
|
||||||
|
let overlay = overlay_start.elapsed();
|
||||||
let Some(renderer) = self.renderer.as_mut() else {
|
let Some(renderer) = self.renderer.as_mut() else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
@ -158,7 +194,7 @@ impl Fabrilis {
|
||||||
let render = render_start.elapsed();
|
let render = render_start.elapsed();
|
||||||
if let Err(error) = draw {
|
if let Err(error) = draw {
|
||||||
eprintln!("fabrilis: draw failed: {error}");
|
eprintln!("fabrilis: draw failed: {error}");
|
||||||
write_dev(&mut self.dev, Level::Error, "render", &error.to_string());
|
error!("render", "{error}");
|
||||||
}
|
}
|
||||||
let recorded = self.metrics.record(
|
let recorded = self.metrics.record(
|
||||||
frame_time,
|
frame_time,
|
||||||
|
|
@ -172,23 +208,25 @@ impl Fabrilis {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
self.frame = self.frame.saturating_add(1);
|
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.
|
/// 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
|
/// Both observers run after the frame was drawn and only read the metrics
|
||||||
/// that the overlay already computed.
|
/// that the overlay already computed.
|
||||||
fn log_frame(
|
fn log_frame(&mut self, detail: FrameDetail, sim_seconds: f64, unix_s: Option<f64>) {
|
||||||
&mut self,
|
|
||||||
frame_time: Duration,
|
|
||||||
slowest_step_ms: f32,
|
|
||||||
sim_seconds: f64,
|
|
||||||
unix_s: Option<f64>,
|
|
||||||
) {
|
|
||||||
let stats = self.metrics.stats();
|
let stats = self.metrics.stats();
|
||||||
let frame_ms = frame_time.as_secs_f32() * 1000.0;
|
let spike = spike_reason(detail.frame_ms, detail.physics_step_ms);
|
||||||
let spike = spike_reason(frame_ms, slowest_step_ms);
|
|
||||||
if let Some(unix_s) = unix_s {
|
if let Some(unix_s) = unix_s {
|
||||||
let row = Row {
|
let row = Row {
|
||||||
unix_s,
|
unix_s,
|
||||||
|
|
@ -201,28 +239,23 @@ impl Fabrilis {
|
||||||
&& let Err(error) = csv.record(&row)
|
&& let Err(error) = csv.record(&row)
|
||||||
{
|
{
|
||||||
eprintln!("fabrilis: metrics log write failed: {error}");
|
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 let Some(dev) = &self.dev {
|
||||||
if dev.summary_due() {
|
let summary_due = devlog::lock(dev).summary_due();
|
||||||
write_line(dev, Level::Info, "metrics", &devlog::summary(&stats));
|
if summary_due {
|
||||||
|
info!("metrics", "{}", devlog::summary(&stats));
|
||||||
}
|
}
|
||||||
if let Some(trigger) = spike {
|
if let Some(trigger) = spike {
|
||||||
let line = devlog::spike(self.frame, frame_ms, slowest_step_ms, trigger);
|
warn!("spike", "{}", devlog::spike(self.frame, &detail, trigger));
|
||||||
write_line(dev, Level::Warn, "spike", &line);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Logs a failure with its context before the loop gives up on the step.
|
/// Logs a failure with its context before the loop gives up on the step.
|
||||||
fn report(&mut self, context: &str, detail: &str) {
|
fn report(&self, context: &str, detail: &str) {
|
||||||
write_dev(
|
error!("app", "{context}: {detail}");
|
||||||
&mut self.dev,
|
|
||||||
Level::Error,
|
|
||||||
"app",
|
|
||||||
&format!("{context}: {detail}"),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Flushes the CSV and closes the dev session.
|
/// Flushes the CSV and closes the dev session.
|
||||||
|
|
@ -232,7 +265,7 @@ impl Fabrilis {
|
||||||
{
|
{
|
||||||
eprintln!("fabrilis: metrics log flush failed: {error}");
|
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 {
|
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 {
|
impl ApplicationHandler for Fabrilis {
|
||||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||||
if self.window.is_some() {
|
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::event::ElementState;
|
||||||
use winit::keyboard::KeyCode;
|
use winit::keyboard::KeyCode;
|
||||||
|
|
||||||
use super::Motion;
|
use super::Motion;
|
||||||
|
use crate::runtime::sim::Drive;
|
||||||
|
|
||||||
/// Radians of rotation per pixel of mouse drag.
|
/// Radians of rotation per pixel of mouse drag.
|
||||||
const LOOK_SENSITIVITY: f32 = 0.0035;
|
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)]
|
#[derive(Default)]
|
||||||
pub(crate) struct Controls {
|
pub(crate) struct Controls {
|
||||||
forward: bool,
|
forward: bool,
|
||||||
back: bool,
|
back: bool,
|
||||||
left: bool,
|
left: bool,
|
||||||
right: bool,
|
right: bool,
|
||||||
|
throttle_forward: bool,
|
||||||
|
throttle_back: bool,
|
||||||
|
steer_left: bool,
|
||||||
|
steer_right: bool,
|
||||||
up: bool,
|
up: bool,
|
||||||
down: bool,
|
down: bool,
|
||||||
fast: bool,
|
fast: bool,
|
||||||
|
|
@ -25,12 +30,19 @@ pub(crate) struct Controls {
|
||||||
|
|
||||||
impl Controls {
|
impl Controls {
|
||||||
/// Tracks a movement or modifier key.
|
/// 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) {
|
pub(crate) fn key(&mut self, code: KeyCode, pressed: bool) {
|
||||||
match code {
|
match code {
|
||||||
KeyCode::KeyW | KeyCode::ArrowUp => self.forward = pressed,
|
KeyCode::ArrowUp => self.forward = pressed,
|
||||||
KeyCode::KeyS | KeyCode::ArrowDown => self.back = pressed,
|
KeyCode::ArrowDown => self.back = pressed,
|
||||||
KeyCode::KeyA | KeyCode::ArrowLeft => self.left = pressed,
|
KeyCode::ArrowLeft => self.left = pressed,
|
||||||
KeyCode::KeyD | KeyCode::ArrowRight => self.right = 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::KeyE => self.up = pressed,
|
||||||
KeyCode::KeyQ => self.down = pressed,
|
KeyCode::KeyQ => self.down = pressed,
|
||||||
KeyCode::ShiftLeft | KeyCode::ShiftRight => self.fast = pressed,
|
KeyCode::ShiftLeft | KeyCode::ShiftRight => self.fast = pressed,
|
||||||
|
|
@ -63,6 +75,10 @@ impl Controls {
|
||||||
self.back = false;
|
self.back = false;
|
||||||
self.left = false;
|
self.left = false;
|
||||||
self.right = false;
|
self.right = false;
|
||||||
|
self.throttle_forward = false;
|
||||||
|
self.throttle_back = false;
|
||||||
|
self.steer_left = false;
|
||||||
|
self.steer_right = false;
|
||||||
self.up = false;
|
self.up = false;
|
||||||
self.down = false;
|
self.down = false;
|
||||||
self.fast = false;
|
self.fast = false;
|
||||||
|
|
@ -71,7 +87,15 @@ impl Controls {
|
||||||
self.turn = [0.0, 0.0];
|
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 {
|
pub(crate) fn motion(&mut self, seconds: f32) -> Motion {
|
||||||
let [yaw, pitch] = self.turn;
|
let [yaw, pitch] = self.turn;
|
||||||
self.turn = [0.0, 0.0];
|
self.turn = [0.0, 0.0];
|
||||||
|
|
|
||||||
|
|
@ -3,8 +3,11 @@
|
||||||
use core::f32::consts::FRAC_PI_2;
|
use core::f32::consts::FRAC_PI_2;
|
||||||
|
|
||||||
use fabrilis_core::math;
|
use fabrilis_core::math;
|
||||||
|
use winit::keyboard::KeyCode;
|
||||||
|
|
||||||
|
use super::input::Controls;
|
||||||
use super::{FlyCamera, MOVE_SPEED, Motion, PITCH_LIMIT};
|
use super::{FlyCamera, MOVE_SPEED, Motion, PITCH_LIMIT};
|
||||||
|
use crate::runtime::sim::Drive;
|
||||||
|
|
||||||
fn close(actual: f32, expected: f32) -> bool {
|
fn close(actual: f32, expected: f32) -> bool {
|
||||||
(actual - expected).abs() < 1.0e-4
|
(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));
|
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]
|
#[test]
|
||||||
fn shift_multiplies_movement_speed() {
|
fn shift_multiplies_movement_speed() {
|
||||||
let mut slow = level_camera();
|
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
|
//! 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
|
//! 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`.
|
//! Line shape: `unix_s level target message`.
|
||||||
|
|
||||||
|
|
@ -14,68 +15,32 @@ mod tests;
|
||||||
use std::fs::{File, OpenOptions};
|
use std::fs::{File, OpenOptions};
|
||||||
use std::io::{self, Write};
|
use std::io::{self, Write};
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
use std::sync::{Arc, Mutex, MutexGuard};
|
||||||
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
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.
|
use crate::runtime::metrics::{FrameDetail, Stats};
|
||||||
#[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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How often a metrics summary line is written, seconds.
|
/// How often a metrics summary line is written, seconds.
|
||||||
const SUMMARY_INTERVAL_SECONDS: u64 = 1;
|
const SUMMARY_INTERVAL_SECONDS: u64 = 1;
|
||||||
|
|
||||||
/// A dev log file, truncated or created when opened.
|
/// 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 {
|
pub(crate) struct DevLog {
|
||||||
file: File,
|
file: File,
|
||||||
level: Level,
|
|
||||||
last_summary: Instant,
|
last_summary: Instant,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DevLog {
|
impl DevLog {
|
||||||
/// Creates or opens the file, truncating it unless `append` is set, and
|
/// Creates or opens the file, truncating it unless `append` is set.
|
||||||
/// records `level` as the most detailed level to write.
|
|
||||||
#[allow(
|
#[allow(
|
||||||
clippy::disallowed_methods,
|
clippy::disallowed_methods,
|
||||||
reason = "the dev log is a wall-clock observer of the app loop"
|
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()
|
let file = OpenOptions::new()
|
||||||
.create(true)
|
.create(true)
|
||||||
.write(true)
|
.write(true)
|
||||||
|
|
@ -84,16 +49,12 @@ impl DevLog {
|
||||||
.open(path)?;
|
.open(path)?;
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
file,
|
file,
|
||||||
level,
|
|
||||||
last_summary: Instant::now(),
|
last_summary: Instant::now(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Writes one line and flushes it, so the log survives a crash.
|
/// 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<()> {
|
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);
|
let line = format_line(unix_now(), level, target, message);
|
||||||
writeln!(self.file, "{line}")?;
|
writeln!(self.file, "{line}")?;
|
||||||
self.file.flush()
|
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.
|
/// Formats one log line without the trailing newline.
|
||||||
pub(crate) fn format_line(unix_s: f64, level: Level, target: &str, message: &str) -> String {
|
pub(crate) fn format_line(unix_s: f64, level: Level, target: &str, message: &str) -> String {
|
||||||
format!("{unix_s:.3} {level} {target} {message}")
|
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.
|
/// 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.
|
/// 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.
|
//! 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 fabrilis_worldgen::terrain::TerrainConfig;
|
||||||
|
|
||||||
use super::{DevLog, Level};
|
|
||||||
|
|
||||||
/// Everything the startup lines report, gathered before the loop starts.
|
/// Everything the startup lines report, gathered before the loop starts.
|
||||||
pub(crate) struct StartupInfo<'a> {
|
pub(crate) struct StartupInfo<'a> {
|
||||||
pub(crate) window: (u32, u32),
|
pub(crate) window: (u32, u32),
|
||||||
pub(crate) scale: f64,
|
pub(crate) scale: f64,
|
||||||
pub(crate) terrain: TerrainConfig,
|
pub(crate) terrain: TerrainConfig,
|
||||||
pub(crate) boxes: usize,
|
pub(crate) cart_mass_kg: f64,
|
||||||
pub(crate) box_mass_kg: f64,
|
pub(crate) wheels: usize,
|
||||||
pub(crate) box_size_m: f64,
|
pub(crate) wheel_radius_m: f64,
|
||||||
|
pub(crate) spawn: Vec3,
|
||||||
pub(crate) eye: [f32; 3],
|
pub(crate) eye: [f32; 3],
|
||||||
pub(crate) target: [f32; 3],
|
pub(crate) target: [f32; 3],
|
||||||
pub(crate) adapter: &'a str,
|
pub(crate) adapter: &'a str,
|
||||||
|
|
@ -26,41 +28,51 @@ pub(crate) struct StartupInfo<'a> {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Writes the startup banner, one line per fact.
|
/// 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 terrain = info.terrain;
|
||||||
let [width, height] = [info.window.0, info.window.1];
|
let [width, height] = [info.window.0, info.window.1];
|
||||||
let [x, y, z] = info.eye;
|
let [x, y, z] = info.eye;
|
||||||
let [tx, ty, tz] = info.target;
|
let [tx, ty, tz] = info.target;
|
||||||
let lines = [
|
let spawn = info.spawn;
|
||||||
format!(
|
info!(
|
||||||
"fabrilis-app {} {} {}",
|
"startup",
|
||||||
env!("CARGO_PKG_VERSION"),
|
"fabrilis-app {} {} {}",
|
||||||
std::env::consts::OS,
|
env!("CARGO_PKG_VERSION"),
|
||||||
std::env::consts::ARCH
|
std::env::consts::OS,
|
||||||
),
|
std::env::consts::ARCH
|
||||||
format!("window {width}x{height} scale {:.2}", info.scale),
|
);
|
||||||
format!(
|
info!("startup", "window {width}x{height} scale {:.2}", info.scale);
|
||||||
"terrain seed={} size={} extent={:.1} height_scale={:.1}",
|
info!(
|
||||||
terrain.seed, terrain.size, terrain.extent, terrain.height_scale
|
"startup",
|
||||||
),
|
"terrain seed={} size={} extent={:.1} height_scale={:.1}",
|
||||||
format!(
|
terrain.seed,
|
||||||
"boxes={} mass={:.1} kg size={:.2} m",
|
terrain.size,
|
||||||
info.boxes, info.box_mass_kg, info.box_size_m
|
terrain.extent,
|
||||||
),
|
terrain.height_scale
|
||||||
format!("camera eye=[{x:.2}, {y:.2}, {z:.2}] target=[{tx:.2}, {ty:.2}, {tz:.2}]"),
|
);
|
||||||
format!("gpu adapter {}", info.adapter),
|
info!(
|
||||||
format!("gpu driver {}", info.driver),
|
"startup",
|
||||||
format!("gpu surface {}", info.surface),
|
"cart mass={:.1} kg wheels={} wheel_radius={:.2} m spawn=[{:.2}, {:.2}, {:.2}]",
|
||||||
format!(
|
info.cart_mass_kg,
|
||||||
"metrics_log {} append={} dev={}",
|
info.wheels,
|
||||||
info.metrics_path.unwrap_or("off"),
|
info.wheel_radius_m,
|
||||||
info.append,
|
spawn.x,
|
||||||
info.dev
|
spawn.y,
|
||||||
),
|
spawn.z
|
||||||
format!("log {}", info.log_path.unwrap_or("off")),
|
);
|
||||||
];
|
info!(
|
||||||
for line in &lines {
|
"startup",
|
||||||
log.write(Level::Info, "startup", line)?;
|
"camera eye=[{x:.2}, {y:.2}, {z:.2}] target=[{tx:.2}, {ty:.2}, {tz:.2}]"
|
||||||
}
|
);
|
||||||
Ok(())
|
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::path::PathBuf;
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
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::*;
|
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 {
|
struct TempDir {
|
||||||
path: PathBuf,
|
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"
|
"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!(
|
assert_eq!(
|
||||||
spike(42, 25.1, 1.25, "frame+physics"),
|
spike(
|
||||||
"frame=42 frame_ms=25.10 physics_step_ms=1.250 trigger=frame+physics"
|
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 dir = TempDir::new("create");
|
||||||
let path = dir.path.join("fabrilis-dev.log");
|
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");
|
log.write(Level::Info, "app", "first run").expect("write");
|
||||||
}
|
}
|
||||||
assert!(path.is_file(), "the log file exists");
|
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_eq!(first.lines().count(), 1);
|
||||||
assert!(first.ends_with(" info app first run\n"));
|
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");
|
log.write(Level::Warn, "app", "second run").expect("write");
|
||||||
}
|
}
|
||||||
let second = std::fs::read_to_string(&path).expect("read");
|
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 dir = TempDir::new("append");
|
||||||
let path = dir.path.join("fabrilis-dev.log");
|
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");
|
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");
|
log.write(Level::Info, "app", "second").expect("write");
|
||||||
}
|
}
|
||||||
let text = std::fs::read_to_string(&path).expect("read");
|
let text = std::fs::read_to_string(&path).expect("read");
|
||||||
|
|
@ -104,15 +130,18 @@ fn append_keeps_the_previous_lines() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[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 dir = TempDir::new("levels");
|
||||||
let path = dir.path.join("fabrilis-dev.log");
|
let path = dir.path.join("fabrilis-dev.log");
|
||||||
{
|
let log = Arc::new(Mutex::new(
|
||||||
let mut log = DevLog::open(&path, Level::Info, false).expect("create the log");
|
DevLog::open(&path, false).expect("create the log"),
|
||||||
log.write(Level::Debug, "app", "too detailed")
|
));
|
||||||
.expect("write");
|
set_level(Level::Info);
|
||||||
log.write(Level::Info, "app", "kept").expect("write");
|
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");
|
let text = std::fs::read_to_string(&path).expect("read");
|
||||||
assert_eq!(text.lines().count(), 1);
|
assert_eq!(text.lines().count(), 1);
|
||||||
assert!(text.contains("kept"));
|
assert!(text.contains("kept"));
|
||||||
|
|
|
||||||
|
|
@ -32,6 +32,22 @@ pub(crate) struct FrameWork {
|
||||||
pub(crate) steps: u32,
|
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.
|
/// One frame in the rolling statistics window.
|
||||||
#[derive(Debug, Clone, Copy)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
struct Sample {
|
struct Sample {
|
||||||
|
|
@ -92,6 +108,7 @@ pub(crate) struct Metrics {
|
||||||
rtf: Option<f32>,
|
rtf: Option<f32>,
|
||||||
primed: bool,
|
primed: bool,
|
||||||
stats: Stats,
|
stats: Stats,
|
||||||
|
last_sample: Duration,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for Metrics {
|
impl Default for Metrics {
|
||||||
|
|
@ -116,6 +133,7 @@ impl Metrics {
|
||||||
rtf: None,
|
rtf: None,
|
||||||
primed: false,
|
primed: false,
|
||||||
stats: Stats::default(),
|
stats: Stats::default(),
|
||||||
|
last_sample: Duration::ZERO,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -152,7 +170,9 @@ impl Metrics {
|
||||||
let physics_ms = work.physics.as_secs_f32() * 1000.0;
|
let physics_ms = work.physics.as_secs_f32() * 1000.0;
|
||||||
let render_ms = work.render.as_secs_f32() * 1000.0;
|
let render_ms = work.render.as_secs_f32() * 1000.0;
|
||||||
self.clock += frame.as_secs_f32();
|
self.clock += frame.as_secs_f32();
|
||||||
|
let sample_start = Stopwatch::start();
|
||||||
let sample: ProcSample = proc::sample();
|
let sample: ProcSample = proc::sample();
|
||||||
|
self.last_sample = sample_start.elapsed();
|
||||||
let cpu_ticks = match (sample.ticks, self.last_ticks) {
|
let cpu_ticks = match (sample.ticks, self.last_ticks) {
|
||||||
(Some(now), Some(before)) => u32::try_from(now.saturating_sub(before)).unwrap_or(0),
|
(Some(now), Some(before)) => u32::try_from(now.saturating_sub(before)).unwrap_or(0),
|
||||||
_ => 0,
|
_ => 0,
|
||||||
|
|
@ -180,6 +200,11 @@ impl Metrics {
|
||||||
self.stats
|
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.
|
/// Drops samples that fell out of the statistics window.
|
||||||
fn trim(&mut self) {
|
fn trim(&mut self) {
|
||||||
while self.window.len() > 1 {
|
while self.window.len() > 1 {
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,6 @@ mod sim;
|
||||||
|
|
||||||
pub use error::AppError;
|
pub use error::AppError;
|
||||||
|
|
||||||
use devlog::DevLog;
|
|
||||||
use devlog::startup::StartupInfo;
|
use devlog::startup::StartupInfo;
|
||||||
use gpu::WindowRenderer;
|
use gpu::WindowRenderer;
|
||||||
use scene::View;
|
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())))
|
.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(
|
fn log_startup(
|
||||||
dev: Option<&mut DevLog>,
|
|
||||||
config: &Config,
|
config: &Config,
|
||||||
view: &View,
|
view: &View,
|
||||||
renderer: &WindowRenderer,
|
renderer: &WindowRenderer,
|
||||||
window: &Window,
|
window: &Window,
|
||||||
|
simulation: &sim::Simulation,
|
||||||
) {
|
) {
|
||||||
let Some(dev) = dev else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let gpu = renderer.info();
|
let gpu = renderer.info();
|
||||||
let size = window.inner_size();
|
let size = window.inner_size();
|
||||||
let metrics_path = config
|
let metrics_path = config
|
||||||
|
|
@ -70,13 +66,15 @@ fn log_startup(
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|path| path.display().to_string());
|
.map(|path| path.display().to_string());
|
||||||
let log_path = config.log.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 {
|
let info = StartupInfo {
|
||||||
window: (size.width, size.height),
|
window: (size.width, size.height),
|
||||||
scale: window.scale_factor(),
|
scale: window.scale_factor(),
|
||||||
terrain: view.terrain_config,
|
terrain: view.terrain_config,
|
||||||
boxes: sim::DROPS.len(),
|
cart_mass_kg: cart.mass_kg,
|
||||||
box_mass_kg: sim::BOX_MASS,
|
wheels: cart.wheels,
|
||||||
box_size_m: sim::BOX_SIZE,
|
wheel_radius_m: cart.wheel_radius_m,
|
||||||
|
spawn: cart.spawn,
|
||||||
eye: view.camera.eye(),
|
eye: view.camera.eye(),
|
||||||
target: view.camera.target(),
|
target: view.camera.target(),
|
||||||
adapter: &gpu.adapter,
|
adapter: &gpu.adapter,
|
||||||
|
|
@ -87,9 +85,7 @@ fn log_startup(
|
||||||
dev: config.dev,
|
dev: config.dev,
|
||||||
append: config.append,
|
append: config.append,
|
||||||
};
|
};
|
||||||
if let Err(error) = devlog::startup::write(dev, &info) {
|
devlog::startup::write(&info);
|
||||||
eprintln!("fabrilis: dev log write failed: {error}");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn aspect(size: winit::dpi::PhysicalSize<u32>) -> f32 {
|
fn aspect(size: winit::dpi::PhysicalSize<u32>) -> f32 {
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,16 @@
|
||||||
//! The seeded world shown by the window: terrain, camera and collider mesh.
|
//! 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_render::{MeshData, Scene};
|
||||||
use fabrilis_worldgen::terrain::{Heightmap, TerrainConfig, TerrainMesh};
|
use fabrilis_worldgen::terrain::{Heightmap, LodConfig, TerrainConfig, TerrainMesh};
|
||||||
|
|
||||||
use super::AppError;
|
use super::AppError;
|
||||||
use super::camera::FlyCamera;
|
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.
|
/// Render scene plus the geometry and camera state shared with physics.
|
||||||
pub(crate) struct View {
|
pub(crate) struct View {
|
||||||
pub scene: Scene,
|
pub scene: Scene,
|
||||||
|
|
@ -14,6 +19,36 @@ pub(crate) struct View {
|
||||||
pub terrain: TerrainMesh,
|
pub terrain: TerrainMesh,
|
||||||
/// The parameters the heightmap was generated from.
|
/// The parameters the heightmap was generated from.
|
||||||
pub terrain_config: TerrainConfig,
|
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.
|
/// 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()
|
..Default::default()
|
||||||
};
|
};
|
||||||
let heightmap = Heightmap::generate(config)?;
|
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 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: terrain
|
||||||
.vertices
|
.vertices
|
||||||
.iter()
|
.iter()
|
||||||
|
|
@ -38,15 +95,8 @@ pub(crate) fn build(aspect: f32) -> Result<View, AppError> {
|
||||||
.iter()
|
.iter()
|
||||||
.flat_map(|triangle| triangle.iter().copied())
|
.flat_map(|triangle| triangle.iter().copied())
|
||||||
.collect(),
|
.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;
|
mod pacing;
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|
@ -8,45 +9,25 @@ mod tests;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use fabrilis_core::time::SimDelta;
|
use fabrilis_core::time::SimDelta;
|
||||||
use fabrilis_core::units::Kilograms;
|
use fabrilis_core::vec::{Quat, Vec3};
|
||||||
use fabrilis_core::vec::{Quat, Transform, Vec3};
|
use fabrilis_physics::{PhysicsBackend, RapierBackend, TrimeshDesc};
|
||||||
use fabrilis_physics::{BodyDesc, BodyId, PhysicsBackend, RapierBackend, ShapeDesc, TrimeshDesc};
|
use fabrilis_render::Scene;
|
||||||
use fabrilis_render::{Instance, Scene};
|
|
||||||
use fabrilis_worldgen::terrain::{Heightmap, TerrainMesh};
|
use fabrilis_worldgen::terrain::{Heightmap, TerrainMesh};
|
||||||
|
|
||||||
use crate::runtime::AppError;
|
use crate::runtime::AppError;
|
||||||
use crate::runtime::metrics::Stopwatch;
|
use crate::runtime::metrics::Stopwatch;
|
||||||
|
use cart::{Cart, CartInfo, CartPose};
|
||||||
use pacing::{MAX_STEPS, Pacer};
|
use pacing::{MAX_STEPS, Pacer};
|
||||||
|
|
||||||
|
pub(crate) use cart::Drive;
|
||||||
|
|
||||||
/// Physics rate; the step never changes with the frame time.
|
/// Physics rate; the step never changes with the frame time.
|
||||||
const HZ: u64 = 1_000;
|
const HZ: u64 = 1_000;
|
||||||
|
|
||||||
/// Edge length of each dropped box, metres.
|
/// The Rapier world and the cart it drives.
|
||||||
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.
|
|
||||||
pub(crate) struct Simulation {
|
pub(crate) struct Simulation {
|
||||||
backend: RapierBackend,
|
backend: RapierBackend,
|
||||||
boxes: Vec<BoxBody>,
|
cart: Cart,
|
||||||
step: SimDelta,
|
step: SimDelta,
|
||||||
pacer: Pacer,
|
pacer: Pacer,
|
||||||
total_steps: u64,
|
total_steps: u64,
|
||||||
|
|
@ -54,7 +35,7 @@ pub(crate) struct Simulation {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl 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(
|
pub(crate) fn new(
|
||||||
terrain: &TerrainMesh,
|
terrain: &TerrainMesh,
|
||||||
heightmap: &Heightmap,
|
heightmap: &Heightmap,
|
||||||
|
|
@ -73,29 +54,10 @@ impl Simulation {
|
||||||
backend
|
backend
|
||||||
.add_trimesh(collider)
|
.add_trimesh(collider)
|
||||||
.ok_or_else(|| AppError::Physics("terrain collider was rejected".to_owned()))?;
|
.ok_or_else(|| AppError::Physics("terrain collider was rejected".to_owned()))?;
|
||||||
scene.instances.clear();
|
let cart = Cart::new(&mut backend, heightmap, scene);
|
||||||
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 });
|
|
||||||
}
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
backend,
|
backend,
|
||||||
boxes,
|
cart,
|
||||||
step,
|
step,
|
||||||
pacer: Pacer::new(),
|
pacer: Pacer::new(),
|
||||||
total_steps: 0,
|
total_steps: 0,
|
||||||
|
|
@ -108,19 +70,31 @@ impl Simulation {
|
||||||
/// Diagnostics time each step individually, but only observe it: the number
|
/// 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
|
/// of steps, their order and the Rapier calls stay exactly the same, so the
|
||||||
/// resulting state hash does not depend on logging being enabled.
|
/// 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);
|
let frame = self.pacer.advance(self.step.nanos(), MAX_STEPS);
|
||||||
self.slowest_step = Duration::ZERO;
|
self.slowest_step = Duration::ZERO;
|
||||||
self.total_steps = self.total_steps.saturating_add(u64::from(frame.steps));
|
self.total_steps = self.total_steps.saturating_add(u64::from(frame.steps));
|
||||||
for _ in 0..frame.steps {
|
self.cart.drive(&mut self.backend, drive);
|
||||||
let step_start = Stopwatch::start();
|
self.run_steps(frame.steps);
|
||||||
self.backend.step(self.step);
|
self.cart.sync(&self.backend, scene);
|
||||||
self.slowest_step = self.slowest_step.max(step_start.elapsed());
|
|
||||||
}
|
|
||||||
self.sync(scene);
|
|
||||||
frame
|
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.
|
/// Simulated seconds represented by the steps that have actually run.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub(crate) fn sim_seconds(&self) -> f64 {
|
pub(crate) fn sim_seconds(&self) -> f64 {
|
||||||
|
|
@ -133,30 +107,28 @@ impl Simulation {
|
||||||
self.slowest_step
|
self.slowest_step
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Copies every body transform into its rendered instance.
|
/// The current chassis pose and wheel angles, used by the golden test.
|
||||||
fn sync(&self, scene: &mut Scene) {
|
#[allow(
|
||||||
for (instance, body) in scene.instances.iter_mut().zip(&self.boxes) {
|
dead_code,
|
||||||
let Some(transform) = self.backend.body_transform(body.id) else {
|
reason = "read by the golden test and by the future headless CLI"
|
||||||
continue;
|
)]
|
||||||
};
|
#[must_use]
|
||||||
instance.model = model(transform, BOX_SIZE as f32);
|
pub(crate) fn cart_pose(&self) -> Option<CartPose> {
|
||||||
instance.color = body.color;
|
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::pacing::{MAX_STEPS, steps_for};
|
||||||
|
use super::{Drive, Simulation};
|
||||||
|
|
||||||
const STEP_NS: u64 = 1_000_000;
|
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]
|
#[test]
|
||||||
fn no_time_means_no_steps() {
|
fn no_time_means_no_steps() {
|
||||||
assert_eq!(steps_for(0, STEP_NS, MAX_STEPS), 0);
|
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() {
|
fn a_zero_cap_runs_nothing() {
|
||||||
assert_eq!(steps_for(16_000_000, STEP_NS, 0), 0);
|
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}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
//! SI units, simulation time (integer ns), multi-rate scheduler, Fidelity, state snapshots, deterministic math
|
//! SI units, simulation time (integer ns), multi-rate scheduler, Fidelity, state snapshots, deterministic math, logging facade
|
||||||
pub mod fidelity;
|
pub mod fidelity;
|
||||||
pub mod id;
|
pub mod id;
|
||||||
|
pub mod log;
|
||||||
pub mod math;
|
pub mod math;
|
||||||
pub mod rng;
|
pub mod rng;
|
||||||
pub mod sched;
|
pub mod sched;
|
||||||
|
|
|
||||||
71
crates/core/src/log/macros.rs
Normal file
71
crates/core/src/log/macros.rs
Normal file
|
|
@ -0,0 +1,71 @@
|
||||||
|
//! Level macros for the log facade.
|
||||||
|
//!
|
||||||
|
//! Call shape: `info!("target", "message {}", value)`. The first argument is
|
||||||
|
//! the target, the rest is a `format!`-style template. Both the target and the
|
||||||
|
//! formatting arguments are evaluated only when the level is enabled and a
|
||||||
|
//! sink is installed, so a disabled macro costs one atomic check.
|
||||||
|
|
||||||
|
/// Logs at [`Level::Error`](crate::log::Level::Error).
|
||||||
|
///
|
||||||
|
/// Call shape: `error!("target", "message {}", value)`.
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! error {
|
||||||
|
($target:expr, $($arg:tt)+) => {{
|
||||||
|
let level = $crate::log::Level::Error;
|
||||||
|
if $crate::log::enabled(level) {
|
||||||
|
$crate::log::emit(level, $target, format_args!($($arg)+));
|
||||||
|
}
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Logs at [`Level::Warn`](crate::log::Level::Warn).
|
||||||
|
///
|
||||||
|
/// Call shape: `warn!("target", "message {}", value)`.
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! warn {
|
||||||
|
($target:expr, $($arg:tt)+) => {{
|
||||||
|
let level = $crate::log::Level::Warn;
|
||||||
|
if $crate::log::enabled(level) {
|
||||||
|
$crate::log::emit(level, $target, format_args!($($arg)+));
|
||||||
|
}
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Logs at [`Level::Info`](crate::log::Level::Info).
|
||||||
|
///
|
||||||
|
/// Call shape: `info!("target", "message {}", value)`.
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! info {
|
||||||
|
($target:expr, $($arg:tt)+) => {{
|
||||||
|
let level = $crate::log::Level::Info;
|
||||||
|
if $crate::log::enabled(level) {
|
||||||
|
$crate::log::emit(level, $target, format_args!($($arg)+));
|
||||||
|
}
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Logs at [`Level::Debug`](crate::log::Level::Debug).
|
||||||
|
///
|
||||||
|
/// Call shape: `debug!("target", "message {}", value)`.
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! debug {
|
||||||
|
($target:expr, $($arg:tt)+) => {{
|
||||||
|
let level = $crate::log::Level::Debug;
|
||||||
|
if $crate::log::enabled(level) {
|
||||||
|
$crate::log::emit(level, $target, format_args!($($arg)+));
|
||||||
|
}
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Logs at [`Level::Trace`](crate::log::Level::Trace).
|
||||||
|
///
|
||||||
|
/// Call shape: `trace!("target", "message {}", value)`.
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! trace {
|
||||||
|
($target:expr, $($arg:tt)+) => {{
|
||||||
|
let level = $crate::log::Level::Trace;
|
||||||
|
if $crate::log::enabled(level) {
|
||||||
|
$crate::log::emit(level, $target, format_args!($($arg)+));
|
||||||
|
}
|
||||||
|
}};
|
||||||
|
}
|
||||||
191
crates/core/src/log/mod.rs
Normal file
191
crates/core/src/log/mod.rs
Normal file
|
|
@ -0,0 +1,191 @@
|
||||||
|
//! Logging facade: five levels, borrowed records and one process-wide sink (D35).
|
||||||
|
//!
|
||||||
|
//! Library code writes diagnostics through the level macros:
|
||||||
|
//!
|
||||||
|
//! ```
|
||||||
|
//! use fabrilis_core::log::info;
|
||||||
|
//! info!("world", "boxes={} seed={}", 12, 7);
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! The first macro argument is the target, the rest is a `format!`-style
|
||||||
|
//! template. The application installs a [`LogSink`] with [`set_sink`] and picks
|
||||||
|
//! the most detailed level with [`set_level`]. Until a sink is installed every
|
||||||
|
//! macro is one disabled check: a disabled level neither evaluates nor formats
|
||||||
|
//! its arguments.
|
||||||
|
//!
|
||||||
|
//! A [`Record`] borrows its target and message, so the facade does not allocate;
|
||||||
|
//! the sink decides what to keep and when to write it.
|
||||||
|
//!
|
||||||
|
//! `log` and `tracing` are deliberately not used (D35): this facade has no
|
||||||
|
//! dependencies and no wall-clock time of its own.
|
||||||
|
|
||||||
|
mod macros;
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
|
|
||||||
|
pub use crate::{debug, error, info, trace, warn};
|
||||||
|
|
||||||
|
use std::fmt;
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
|
||||||
|
use std::sync::{Arc, RwLock};
|
||||||
|
|
||||||
|
/// How much detail a sink receives.
|
||||||
|
///
|
||||||
|
/// The variants are ordered from least to most detailed, so
|
||||||
|
/// `level <= max_level()` means the record passes the filter.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
|
||||||
|
#[repr(u8)]
|
||||||
|
pub enum Level {
|
||||||
|
/// Work cannot continue: a device or project failed to load.
|
||||||
|
Error,
|
||||||
|
/// Work continues with degraded behaviour.
|
||||||
|
Warn,
|
||||||
|
/// Lifecycle events, once per event.
|
||||||
|
#[default]
|
||||||
|
Info,
|
||||||
|
/// Summaries and important state changes.
|
||||||
|
Debug,
|
||||||
|
/// Per-frame or per-step detail for investigation only.
|
||||||
|
Trace,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Level {
|
||||||
|
/// Position in the filter, lowest first.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn rank(self) -> u8 {
|
||||||
|
self as u8
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Level for `rank`; unknown values fall back to the most detailed level.
|
||||||
|
const fn from_rank(rank: u8) -> Self {
|
||||||
|
match rank {
|
||||||
|
0 => Self::Error,
|
||||||
|
1 => Self::Warn,
|
||||||
|
2 => Self::Info,
|
||||||
|
3 => Self::Debug,
|
||||||
|
_ => Self::Trace,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for Level {
|
||||||
|
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One borrowed log message handed to a [`LogSink`].
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct Record<'a> {
|
||||||
|
/// Severity of the event.
|
||||||
|
pub level: Level,
|
||||||
|
/// Module or subsystem that reports the event.
|
||||||
|
pub target: &'a str,
|
||||||
|
/// Message, formatted only after the level check.
|
||||||
|
pub message: fmt::Arguments<'a>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Destination for log records: a file, stderr or a test collector.
|
||||||
|
///
|
||||||
|
/// The application installs one sink for the whole process. A sink must not
|
||||||
|
/// panic and should report its own write failures, because the facade has no
|
||||||
|
/// error channel.
|
||||||
|
pub trait LogSink: Send + Sync {
|
||||||
|
/// Receives one record that already passed the level filter.
|
||||||
|
fn log(&self, record: &Record<'_>);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Most detailed level that may reach the sink.
|
||||||
|
static MAX_LEVEL: AtomicU8 = AtomicU8::new(Level::Info as u8);
|
||||||
|
|
||||||
|
/// Fast check that a sink is installed, before taking the lock.
|
||||||
|
static SINK_INSTALLED: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
|
/// The installed sink; `None` keeps the facade silent.
|
||||||
|
static SINK: RwLock<Option<Arc<dyn LogSink>>> = RwLock::new(None);
|
||||||
|
|
||||||
|
/// Returns the most detailed level that is currently enabled.
|
||||||
|
#[must_use]
|
||||||
|
pub fn max_level() -> Level {
|
||||||
|
Level::from_rank(MAX_LEVEL.load(Ordering::Relaxed))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets the most detailed level that may reach the sink.
|
||||||
|
///
|
||||||
|
/// Records above this level are dropped before their arguments are formatted.
|
||||||
|
pub fn set_level(level: Level) {
|
||||||
|
MAX_LEVEL.store(level.rank(), Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Installs `sink`, replacing any previous one, and enables logging.
|
||||||
|
///
|
||||||
|
/// The sink stays installed until [`clear_sink`]; installing a new sink is
|
||||||
|
/// safe at any time.
|
||||||
|
pub fn set_sink(sink: Arc<dyn LogSink>) {
|
||||||
|
let mut slot = match SINK.write() {
|
||||||
|
Ok(slot) => slot,
|
||||||
|
Err(poisoned) => poisoned.into_inner(),
|
||||||
|
};
|
||||||
|
*slot = Some(sink);
|
||||||
|
SINK_INSTALLED.store(true, Ordering::Release);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes the installed sink and disables logging.
|
||||||
|
///
|
||||||
|
/// Mainly for shutdown and tests: normal applications install a sink once.
|
||||||
|
pub fn clear_sink() {
|
||||||
|
SINK_INSTALLED.store(false, Ordering::Release);
|
||||||
|
let mut slot = match SINK.write() {
|
||||||
|
Ok(slot) => slot,
|
||||||
|
Err(poisoned) => poisoned.into_inner(),
|
||||||
|
};
|
||||||
|
*slot = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a record at `level` would currently reach a sink.
|
||||||
|
///
|
||||||
|
/// Both the level filter and the installed sink are checked, so callers can
|
||||||
|
/// use this to skip expensive message construction.
|
||||||
|
#[must_use]
|
||||||
|
pub fn enabled(level: Level) -> bool {
|
||||||
|
level <= max_level() && SINK_INSTALLED.load(Ordering::Acquire)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends one record to the installed sink when the level is enabled.
|
||||||
|
///
|
||||||
|
/// The macros call this after their own [`enabled`] check, so they avoid
|
||||||
|
/// building `message` for a disabled level. Code that already has formatted
|
||||||
|
/// arguments may call it directly.
|
||||||
|
pub fn emit(level: Level, target: &str, message: fmt::Arguments<'_>) {
|
||||||
|
if !enabled(level) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let record = Record {
|
||||||
|
level,
|
||||||
|
target,
|
||||||
|
message,
|
||||||
|
};
|
||||||
|
if let Some(sink) = installed_sink() {
|
||||||
|
sink.log(&record);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Clones the installed sink without holding the lock while it logs.
|
||||||
|
fn installed_sink() -> Option<Arc<dyn LogSink>> {
|
||||||
|
if !SINK_INSTALLED.load(Ordering::Acquire) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let slot = match SINK.read() {
|
||||||
|
Ok(slot) => slot,
|
||||||
|
Err(poisoned) => poisoned.into_inner(),
|
||||||
|
};
|
||||||
|
slot.clone()
|
||||||
|
}
|
||||||
210
crates/core/src/log/tests.rs
Normal file
210
crates/core/src/log/tests.rs
Normal file
|
|
@ -0,0 +1,210 @@
|
||||||
|
//! Tests for level filtering, sink installation and lazy formatting.
|
||||||
|
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
use std::sync::{Arc, Mutex, MutexGuard};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::{debug, error, info, trace, warn};
|
||||||
|
|
||||||
|
/// Serializes tests that use the process-wide level and sink.
|
||||||
|
static GLOBAL: Mutex<()> = Mutex::new(());
|
||||||
|
|
||||||
|
/// One recorded call: level, target and already formatted message.
|
||||||
|
type Entry = (Level, String, String);
|
||||||
|
|
||||||
|
/// Collects records in memory for assertions.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Collector {
|
||||||
|
records: Mutex<Vec<Entry>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Collector {
|
||||||
|
fn snapshot(&self) -> Vec<Entry> {
|
||||||
|
match self.records.lock() {
|
||||||
|
Ok(records) => records.clone(),
|
||||||
|
Err(poisoned) => poisoned.into_inner().clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LogSink for Collector {
|
||||||
|
fn log(&self, record: &Record<'_>) {
|
||||||
|
let entry = (
|
||||||
|
record.level,
|
||||||
|
record.target.to_owned(),
|
||||||
|
record.message.to_string(),
|
||||||
|
);
|
||||||
|
match self.records.lock() {
|
||||||
|
Ok(mut records) => records.push(entry),
|
||||||
|
Err(poisoned) => poisoned.into_inner().push(entry),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Acquires the global test lock, recovering it after a failed test.
|
||||||
|
fn global_lock() -> MutexGuard<'static, ()> {
|
||||||
|
match GLOBAL.lock() {
|
||||||
|
Ok(guard) => guard,
|
||||||
|
Err(poisoned) => poisoned.into_inner(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn levels_are_ordered_from_error_to_trace_and_print_lowercase() {
|
||||||
|
assert!(Level::Error < Level::Warn);
|
||||||
|
assert!(Level::Warn < Level::Info);
|
||||||
|
assert!(Level::Info < Level::Debug);
|
||||||
|
assert!(Level::Debug < Level::Trace);
|
||||||
|
assert_eq!(Level::Error.to_string(), "error");
|
||||||
|
assert_eq!(Level::Warn.to_string(), "warn");
|
||||||
|
assert_eq!(Level::Info.to_string(), "info");
|
||||||
|
assert_eq!(Level::Debug.to_string(), "debug");
|
||||||
|
assert_eq!(Level::Trace.to_string(), "trace");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn enabled_follows_the_max_level_and_the_installed_sink() {
|
||||||
|
let _guard = global_lock();
|
||||||
|
let collector = Arc::new(Collector::default());
|
||||||
|
set_level(Level::Info);
|
||||||
|
set_sink(collector);
|
||||||
|
assert!(enabled(Level::Error));
|
||||||
|
assert!(enabled(Level::Warn));
|
||||||
|
assert!(enabled(Level::Info));
|
||||||
|
assert!(!enabled(Level::Debug));
|
||||||
|
assert!(!enabled(Level::Trace));
|
||||||
|
assert_eq!(max_level(), Level::Info);
|
||||||
|
set_level(Level::Trace);
|
||||||
|
assert_eq!(max_level(), Level::Trace);
|
||||||
|
assert!(enabled(Level::Trace));
|
||||||
|
clear_sink();
|
||||||
|
assert!(!enabled(Level::Error), "no sink means no logging");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_disabled_level_does_not_reach_the_sink() {
|
||||||
|
let _guard = global_lock();
|
||||||
|
let collector = Arc::new(Collector::default());
|
||||||
|
set_level(Level::Info);
|
||||||
|
set_sink(collector.clone());
|
||||||
|
debug!("test", "too detailed {}", 1);
|
||||||
|
trace!("test", "even more {}", 2);
|
||||||
|
info!("test", "kept {}", 3);
|
||||||
|
warn!("test", "also kept {}", 4);
|
||||||
|
assert_eq!(
|
||||||
|
collector.snapshot(),
|
||||||
|
vec![
|
||||||
|
(Level::Info, "test".to_owned(), "kept 3".to_owned()),
|
||||||
|
(Level::Warn, "test".to_owned(), "also kept 4".to_owned()),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
clear_sink();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_enabled_macro_passes_level_target_and_message() {
|
||||||
|
let _guard = global_lock();
|
||||||
|
let collector = Arc::new(Collector::default());
|
||||||
|
set_level(Level::Debug);
|
||||||
|
set_sink(collector.clone());
|
||||||
|
warn!("scene", "bodies={} mass={:.1}", 4, 2.5);
|
||||||
|
debug!("scene", "camera eye={:.2}", 1.25);
|
||||||
|
let records = collector.snapshot();
|
||||||
|
assert_eq!(records.len(), 2);
|
||||||
|
assert_eq!(
|
||||||
|
records.first(),
|
||||||
|
Some(&(
|
||||||
|
Level::Warn,
|
||||||
|
"scene".to_owned(),
|
||||||
|
"bodies=4 mass=2.5".to_owned()
|
||||||
|
))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
records.get(1),
|
||||||
|
Some(&(
|
||||||
|
Level::Debug,
|
||||||
|
"scene".to_owned(),
|
||||||
|
"camera eye=1.25".to_owned()
|
||||||
|
))
|
||||||
|
);
|
||||||
|
clear_sink();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_disabled_macro_does_not_evaluate_or_format_its_arguments() {
|
||||||
|
let _guard = global_lock();
|
||||||
|
let collector = Arc::new(Collector::default());
|
||||||
|
set_level(Level::Info);
|
||||||
|
set_sink(collector.clone());
|
||||||
|
let evaluated = AtomicUsize::new(0);
|
||||||
|
debug!("test", "value={}", {
|
||||||
|
evaluated.fetch_add(1, Ordering::Relaxed);
|
||||||
|
42
|
||||||
|
});
|
||||||
|
assert_eq!(
|
||||||
|
evaluated.load(Ordering::Relaxed),
|
||||||
|
0,
|
||||||
|
"disabled level ran the argument"
|
||||||
|
);
|
||||||
|
assert!(collector.snapshot().is_empty());
|
||||||
|
set_level(Level::Debug);
|
||||||
|
debug!("test", "value={}", {
|
||||||
|
evaluated.fetch_add(1, Ordering::Relaxed);
|
||||||
|
42
|
||||||
|
});
|
||||||
|
assert_eq!(evaluated.load(Ordering::Relaxed), 1);
|
||||||
|
assert_eq!(
|
||||||
|
collector.snapshot(),
|
||||||
|
vec![(Level::Debug, "test".to_owned(), "value=42".to_owned())]
|
||||||
|
);
|
||||||
|
clear_sink();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reinstalling_the_sink_replaces_it_without_panicking() {
|
||||||
|
let _guard = global_lock();
|
||||||
|
let first = Arc::new(Collector::default());
|
||||||
|
let second = Arc::new(Collector::default());
|
||||||
|
set_level(Level::Info);
|
||||||
|
set_sink(first.clone());
|
||||||
|
set_sink(second.clone());
|
||||||
|
info!("test", "second sink");
|
||||||
|
assert!(first.snapshot().is_empty());
|
||||||
|
assert_eq!(second.snapshot().len(), 1);
|
||||||
|
clear_sink();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn without_a_sink_nothing_is_enabled_and_nothing_panics() {
|
||||||
|
let _guard = global_lock();
|
||||||
|
clear_sink();
|
||||||
|
set_level(Level::Trace);
|
||||||
|
assert!(!enabled(Level::Error));
|
||||||
|
error!("test", "dropped {}", 1);
|
||||||
|
info!("test", "dropped {}", 2);
|
||||||
|
warn!("test", "dropped {}", 3);
|
||||||
|
assert!(!enabled(Level::Info));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_poisoned_sink_lock_is_recovered_without_a_panic() {
|
||||||
|
let _guard = global_lock();
|
||||||
|
clear_sink();
|
||||||
|
let poison = std::thread::spawn(|| {
|
||||||
|
let _guard = match SINK.write() {
|
||||||
|
Ok(guard) => guard,
|
||||||
|
Err(poisoned) => poisoned.into_inner(),
|
||||||
|
};
|
||||||
|
panic!("poison the sink lock on purpose");
|
||||||
|
});
|
||||||
|
assert!(poison.join().is_err(), "the helper thread panics");
|
||||||
|
let collector = Arc::new(Collector::default());
|
||||||
|
set_level(Level::Info);
|
||||||
|
set_sink(collector.clone());
|
||||||
|
info!("test", "recovered");
|
||||||
|
assert_eq!(
|
||||||
|
collector.snapshot(),
|
||||||
|
vec![(Level::Info, "test".to_owned(), "recovered".to_owned())]
|
||||||
|
);
|
||||||
|
clear_sink();
|
||||||
|
}
|
||||||
|
|
@ -91,42 +91,78 @@ macro_rules! quantity {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
quantity!(/// Length, m.
|
quantity!(
|
||||||
Meters);
|
/// Length, m.
|
||||||
quantity!(/// Mass, kg.
|
Meters
|
||||||
Kilograms);
|
);
|
||||||
quantity!(/// Time, s (for physics; the scheduler step is set in integer ns).
|
quantity!(
|
||||||
Seconds);
|
/// Mass, kg.
|
||||||
quantity!(/// Speed, m/s.
|
Kilograms
|
||||||
MetersPerSecond);
|
);
|
||||||
quantity!(/// Force, N.
|
quantity!(
|
||||||
Newtons);
|
/// Time, s (for physics; the scheduler step is set in integer ns).
|
||||||
quantity!(/// Pressure and material stress, Pa.
|
Seconds
|
||||||
Pascals);
|
);
|
||||||
quantity!(/// Energy, J.
|
quantity!(
|
||||||
Joules);
|
/// Speed, m/s.
|
||||||
quantity!(/// Power, W.
|
MetersPerSecond
|
||||||
Watts);
|
);
|
||||||
quantity!(/// Temperature, K.
|
quantity!(
|
||||||
Kelvin);
|
/// Force, N.
|
||||||
quantity!(/// Electric potential, V.
|
Newtons
|
||||||
Volts);
|
);
|
||||||
quantity!(/// Current, A.
|
quantity!(
|
||||||
Amps);
|
/// Pressure and material stress, Pa.
|
||||||
quantity!(/// Resistance, Ohm.
|
Pascals
|
||||||
Ohms);
|
);
|
||||||
quantity!(/// Angle, rad.
|
quantity!(
|
||||||
Radians);
|
/// Energy, J.
|
||||||
quantity!(/// Angular velocity, rad/s.
|
Joules
|
||||||
RadiansPerSecond);
|
);
|
||||||
quantity!(/// Acceleration, m/s².
|
quantity!(
|
||||||
MetersPerSecondSquared);
|
/// Power, W.
|
||||||
quantity!(/// Torque, N·m.
|
Watts
|
||||||
NewtonMeters);
|
);
|
||||||
quantity!(/// Volume, m³.
|
quantity!(
|
||||||
CubicMeters);
|
/// Temperature, K.
|
||||||
quantity!(/// Density, kg/m³.
|
Kelvin
|
||||||
KilogramsPerCubicMeter);
|
);
|
||||||
|
quantity!(
|
||||||
|
/// Electric potential, V.
|
||||||
|
Volts
|
||||||
|
);
|
||||||
|
quantity!(
|
||||||
|
/// Current, A.
|
||||||
|
Amps
|
||||||
|
);
|
||||||
|
quantity!(
|
||||||
|
/// Resistance, Ohm.
|
||||||
|
Ohms
|
||||||
|
);
|
||||||
|
quantity!(
|
||||||
|
/// Angle, rad.
|
||||||
|
Radians
|
||||||
|
);
|
||||||
|
quantity!(
|
||||||
|
/// Angular velocity, rad/s.
|
||||||
|
RadiansPerSecond
|
||||||
|
);
|
||||||
|
quantity!(
|
||||||
|
/// Acceleration, m/s².
|
||||||
|
MetersPerSecondSquared
|
||||||
|
);
|
||||||
|
quantity!(
|
||||||
|
/// Torque, N·m.
|
||||||
|
NewtonMeters
|
||||||
|
);
|
||||||
|
quantity!(
|
||||||
|
/// Volume, m³.
|
||||||
|
CubicMeters
|
||||||
|
);
|
||||||
|
quantity!(
|
||||||
|
/// Density, kg/m³.
|
||||||
|
KilogramsPerCubicMeter
|
||||||
|
);
|
||||||
|
|
||||||
impl Radians {
|
impl Radians {
|
||||||
/// Converts degrees to radians; degrees exist only at the UI and import boundary.
|
/// Converts degrees to radians; degrees exist only at the UI and import boundary.
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@
|
||||||
//! (docs/COORDINATES.md).
|
//! (docs/COORDINATES.md).
|
||||||
|
|
||||||
use fabrilis_core::time::SimDelta;
|
use fabrilis_core::time::SimDelta;
|
||||||
use fabrilis_core::units::{Kilograms, Radians};
|
use fabrilis_core::units::{Kilograms, Radians, RadiansPerSecond};
|
||||||
use fabrilis_core::vec::{Quat, Transform, Vec3};
|
use fabrilis_core::vec::{Quat, Transform, Vec3};
|
||||||
|
|
||||||
use crate::joints::{JointId, RevoluteDesc};
|
use crate::joints::{JointId, RevoluteDesc};
|
||||||
|
|
@ -132,6 +132,14 @@ pub trait PhysicsBackend {
|
||||||
/// ignored. See [`RapierBackend`](crate::rapier::RapierBackend) for the model.
|
/// ignored. See [`RapierBackend`](crate::rapier::RapierBackend) for the model.
|
||||||
fn set_motor_position(&mut self, joint: JointId, target: Radians, stiffness: f64, damping: f64);
|
fn set_motor_position(&mut self, joint: JointId, target: Radians, stiffness: f64, damping: f64);
|
||||||
|
|
||||||
|
/// Drives a joint at `target` angular velocity with a velocity motor.
|
||||||
|
///
|
||||||
|
/// Unlike [`set_motor_position`](Self::set_motor_position) the motor tracks a
|
||||||
|
/// speed instead of an angle, which is what wheels need. `factor` is the
|
||||||
|
/// motor's damping coefficient: a larger value follows the target more
|
||||||
|
/// tightly. Unknown joints are ignored.
|
||||||
|
fn set_motor_velocity(&mut self, joint: JointId, target: RadiansPerSecond, factor: f64);
|
||||||
|
|
||||||
/// Sets the world-frame torque for the next step, N·m; replaces the previous one.
|
/// 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.
|
/// A controller calls this every step; unknown bodies are ignored.
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
//! determinism caveats.
|
//! determinism caveats.
|
||||||
|
|
||||||
use fabrilis_core::time::SimDelta;
|
use fabrilis_core::time::SimDelta;
|
||||||
use fabrilis_core::units::{Kilograms, Radians};
|
use fabrilis_core::units::{Kilograms, Radians, RadiansPerSecond};
|
||||||
use fabrilis_core::vec::{Quat, Transform, Vec3};
|
use fabrilis_core::vec::{Quat, Transform, Vec3};
|
||||||
use rapier3d_f64::dynamics::{
|
use rapier3d_f64::dynamics::{
|
||||||
CCDSolver, ImpulseJointHandle, ImpulseJointSet, IntegrationParameters, IslandManager,
|
CCDSolver, ImpulseJointHandle, ImpulseJointSet, IntegrationParameters, IslandManager,
|
||||||
|
|
@ -159,6 +159,18 @@ impl PhysicsBackend for RapierBackend {
|
||||||
.set_motor_position(JointAxis::AngX, target.get(), stiffness, damping);
|
.set_motor_position(JointAxis::AngX, target.get(), stiffness, damping);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn set_motor_velocity(&mut self, joint: JointId, target: RadiansPerSecond, factor: 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_velocity(JointAxis::AngX, target.get(), factor);
|
||||||
|
}
|
||||||
|
|
||||||
fn apply_torque(&mut self, body: BodyId, torque: Vec3) {
|
fn apply_torque(&mut self, body: BodyId, torque: Vec3) {
|
||||||
let Some(handle) = self.body_handle(body) else {
|
let Some(handle) = self.body_handle(body) else {
|
||||||
return;
|
return;
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ use super::*;
|
||||||
use crate::backend::{BodyDesc, BodyId, PhysicsBackend, ShapeDesc, TrimeshDesc};
|
use crate::backend::{BodyDesc, BodyId, PhysicsBackend, ShapeDesc, TrimeshDesc};
|
||||||
use crate::joints::{JointId, RevoluteDesc};
|
use crate::joints::{JointId, RevoluteDesc};
|
||||||
use fabrilis_core::time::SimDelta;
|
use fabrilis_core::time::SimDelta;
|
||||||
use fabrilis_core::units::{Kilograms, Radians};
|
use fabrilis_core::units::{Kilograms, Radians, RadiansPerSecond};
|
||||||
use fabrilis_core::vec::{Quat, Vec3};
|
use fabrilis_core::vec::{Quat, Vec3};
|
||||||
|
|
||||||
fn step_at(hz: u64) -> SimDelta {
|
fn step_at(hz: u64) -> SimDelta {
|
||||||
|
|
@ -82,6 +82,92 @@ fn motor_reaches_target_angle() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A horizontal link hinged on Z at the origin, in a world without gravity.
|
||||||
|
fn build_velocity_world() -> (RapierBackend, BodyId, JointId) {
|
||||||
|
let mut world = RapierBackend::with_gravity(Vec3::ZERO);
|
||||||
|
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, link, joint)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn velocity_motor_spins_at_target_speed() {
|
||||||
|
let (mut world, _link, joint) = build_velocity_world();
|
||||||
|
world.set_motor_velocity(joint, RadiansPerSecond::new(2.0), 100.0);
|
||||||
|
let dt = step_at(1_000);
|
||||||
|
for _ in 0..500 {
|
||||||
|
world.step(dt);
|
||||||
|
}
|
||||||
|
let spun = world.joint_angle(joint).expect("the joint exists").get();
|
||||||
|
// Rapier's acceleration-based velocity motor needs a few dozen milliseconds
|
||||||
|
// to reach the target, so the first half second covers a little less than
|
||||||
|
// the ideal 2 rad/s * 0.5 s = 1 rad.
|
||||||
|
assert!(spun > 0.9 && spun <= 1.0, "angle = {spun}");
|
||||||
|
for _ in 0..500 {
|
||||||
|
world.step(dt);
|
||||||
|
}
|
||||||
|
let later = world.joint_angle(joint).expect("the joint exists").get();
|
||||||
|
let per_half_second = later - spun;
|
||||||
|
assert!(
|
||||||
|
(per_half_second - 1.0).abs() <= 0.01,
|
||||||
|
"angle per half second = {per_half_second}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn velocity_motor_stops_at_zero_target() {
|
||||||
|
let (mut world, _link, joint) = build_velocity_world();
|
||||||
|
world.set_motor_velocity(joint, RadiansPerSecond::new(2.0), 100.0);
|
||||||
|
let dt = step_at(1_000);
|
||||||
|
for _ in 0..500 {
|
||||||
|
world.step(dt);
|
||||||
|
}
|
||||||
|
let spun = world.joint_angle(joint).expect("the joint exists").get();
|
||||||
|
world.set_motor_velocity(joint, RadiansPerSecond::ZERO, 100.0);
|
||||||
|
for _ in 0..200 {
|
||||||
|
world.step(dt);
|
||||||
|
}
|
||||||
|
let stopped = world.joint_angle(joint).expect("the joint exists").get();
|
||||||
|
assert!(
|
||||||
|
(stopped - spun).abs() <= 0.1,
|
||||||
|
"angle ran on from {spun} to {stopped}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn velocity_motor_worlds_match_bitwise() {
|
||||||
|
let (mut first, _first_link, first_joint) = build_velocity_world();
|
||||||
|
let (mut second, _second_link, second_joint) = build_velocity_world();
|
||||||
|
first.set_motor_velocity(first_joint, RadiansPerSecond::new(2.0), 100.0);
|
||||||
|
second.set_motor_velocity(second_joint, RadiansPerSecond::new(2.0), 100.0);
|
||||||
|
let dt = step_at(1_000);
|
||||||
|
for _ in 0..500 {
|
||||||
|
first.step(dt);
|
||||||
|
second.step(dt);
|
||||||
|
}
|
||||||
|
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]
|
#[test]
|
||||||
fn identical_worlds_match_bitwise() {
|
fn identical_worlds_match_bitwise() {
|
||||||
let (mut first, first_body, first_joint) = build_motor_world();
|
let (mut first, first_body, first_joint) = build_motor_world();
|
||||||
|
|
@ -111,6 +197,7 @@ fn unknown_ids_return_none() {
|
||||||
assert!(world.body_transform(BodyId(u32::MAX)).is_none());
|
assert!(world.body_transform(BodyId(u32::MAX)).is_none());
|
||||||
assert!(world.joint_angle(JointId(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);
|
world.set_motor_position(JointId(7), Radians::new(1.0), 1.0, 1.0);
|
||||||
|
world.set_motor_velocity(JointId(7), RadiansPerSecond::new(1.0), 1.0);
|
||||||
assert!(world.body_transform(BodyId(7)).is_none());
|
assert!(world.body_transform(BodyId(7)).is_none());
|
||||||
assert!(world.joint_angle(JointId(7)).is_none());
|
assert!(world.joint_angle(JointId(7)).is_none());
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
//! Custom wgpu renderer: depth-tested terrain meshes, instanced boxes, one
|
//! Custom wgpu renderer: depth-tested terrain meshes, instanced boxes and
|
||||||
//! directional light.
|
//! wheels, one directional light.
|
||||||
//!
|
//!
|
||||||
//! The renderer is not part of the authoritative simulation: it may use `f32`
|
//! The renderer is not part of the authoritative simulation: it may use `f32`
|
||||||
//! and never reads wall-clock time. Headless use builds a [`Gpu`] and renders
|
//! and never reads wall-clock time. Headless use builds a [`Gpu`] and renders
|
||||||
|
|
|
||||||
|
|
@ -201,6 +201,7 @@ impl Renderer {
|
||||||
pass.set_bind_group(0, &self.pipelines.bind_group, &[]);
|
pass.set_bind_group(0, &self.pipelines.bind_group, &[]);
|
||||||
geometry.draw_mesh(&mut pass, &self.pipelines);
|
geometry.draw_mesh(&mut pass, &self.pipelines);
|
||||||
geometry.draw_boxes(&mut pass, &self.pipelines);
|
geometry.draw_boxes(&mut pass, &self.pipelines);
|
||||||
|
geometry.draw_wheels(&mut pass, &self.pipelines);
|
||||||
}
|
}
|
||||||
self.queue.submit([encoder.finish()]);
|
self.queue.submit([encoder.finish()]);
|
||||||
}
|
}
|
||||||
|
|
@ -225,8 +226,10 @@ impl Renderer {
|
||||||
mesh_vertices: upload_vertices(&self.device, scene),
|
mesh_vertices: upload_vertices(&self.device, scene),
|
||||||
mesh_indices: upload_indices(&self.device, scene),
|
mesh_indices: upload_indices(&self.device, scene),
|
||||||
mesh_index_count: scene.mesh.indices.len() as u32,
|
mesh_index_count: scene.mesh.indices.len() as u32,
|
||||||
boxes: upload_instances(&self.device, scene),
|
boxes: upload_instances(&self.device, "fabrilis box instances", &scene.instances),
|
||||||
instance_count: scene.instances.len() as u32,
|
instance_count: scene.instances.len() as u32,
|
||||||
|
wheels: upload_instances(&self.device, "fabrilis wheel instances", &scene.wheels),
|
||||||
|
wheel_count: scene.wheels.len() as u32,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -237,6 +240,8 @@ struct Geometry {
|
||||||
mesh_index_count: u32,
|
mesh_index_count: u32,
|
||||||
boxes: Option<wgpu::Buffer>,
|
boxes: Option<wgpu::Buffer>,
|
||||||
instance_count: u32,
|
instance_count: u32,
|
||||||
|
wheels: Option<wgpu::Buffer>,
|
||||||
|
wheel_count: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Geometry {
|
impl Geometry {
|
||||||
|
|
@ -259,6 +264,16 @@ impl Geometry {
|
||||||
pass.set_index_buffer(pipelines.cube_indices.slice(..), wgpu::IndexFormat::Uint32);
|
pass.set_index_buffer(pipelines.cube_indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||||
pass.draw_indexed(0..pipelines.cube_index_count, 0, 0..self.instance_count);
|
pass.draw_indexed(0..pipelines.cube_index_count, 0, 0..self.instance_count);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn draw_wheels(&self, pass: &mut wgpu::RenderPass<'_>, pipelines: &Pipelines) {
|
||||||
|
let Some(instances) = &self.wheels else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
pass.set_vertex_buffer(0, pipelines.wheel_vertices.slice(..));
|
||||||
|
pass.set_vertex_buffer(1, instances.slice(..));
|
||||||
|
pass.set_index_buffer(pipelines.wheel_indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||||
|
pass.draw_indexed(0..pipelines.wheel_index_count, 0, 0..self.wheel_count);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn upload_vertices(device: &wgpu::Device, scene: &Scene) -> Option<wgpu::Buffer> {
|
fn upload_vertices(device: &wgpu::Device, scene: &Scene) -> Option<wgpu::Buffer> {
|
||||||
|
|
@ -285,12 +300,15 @@ fn upload_indices(device: &wgpu::Device, scene: &Scene) -> Option<wgpu::Buffer>
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn upload_instances(device: &wgpu::Device, scene: &Scene) -> Option<wgpu::Buffer> {
|
fn upload_instances(
|
||||||
if scene.instances.is_empty() {
|
device: &wgpu::Device,
|
||||||
|
label: &str,
|
||||||
|
instances: &[crate::Instance],
|
||||||
|
) -> Option<wgpu::Buffer> {
|
||||||
|
if instances.is_empty() {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
let instances: Vec<pipeline::RawInstance> = scene
|
let raw: Vec<pipeline::RawInstance> = instances
|
||||||
.instances
|
|
||||||
.iter()
|
.iter()
|
||||||
.map(|instance| pipeline::RawInstance {
|
.map(|instance| pipeline::RawInstance {
|
||||||
model: instance.model,
|
model: instance.model,
|
||||||
|
|
@ -299,8 +317,8 @@ fn upload_instances(device: &wgpu::Device, scene: &Scene) -> Option<wgpu::Buffer
|
||||||
.collect();
|
.collect();
|
||||||
Some(pipeline::upload(
|
Some(pipeline::upload(
|
||||||
device,
|
device,
|
||||||
"fabrilis box instances",
|
label,
|
||||||
bytemuck::cast_slice(&instances),
|
bytemuck::cast_slice(&raw),
|
||||||
wgpu::BufferUsages::VERTEX,
|
wgpu::BufferUsages::VERTEX,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -83,6 +83,9 @@ pub(crate) struct Pipelines {
|
||||||
pub cube_vertices: wgpu::Buffer,
|
pub cube_vertices: wgpu::Buffer,
|
||||||
pub cube_indices: wgpu::Buffer,
|
pub cube_indices: wgpu::Buffer,
|
||||||
pub cube_index_count: u32,
|
pub cube_index_count: u32,
|
||||||
|
pub wheel_vertices: wgpu::Buffer,
|
||||||
|
pub wheel_indices: wgpu::Buffer,
|
||||||
|
pub wheel_index_count: u32,
|
||||||
pub terrain_instance: wgpu::Buffer,
|
pub terrain_instance: wgpu::Buffer,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -96,6 +99,7 @@ pub(crate) fn build(device: &wgpu::Device, format: wgpu::TextureFormat) -> Pipel
|
||||||
let (globals, bind_group) = create_globals(device, &layout);
|
let (globals, bind_group) = create_globals(device, &layout);
|
||||||
let pipeline = create_pipeline(device, format, &shader, &layout);
|
let pipeline = create_pipeline(device, format, &shader, &layout);
|
||||||
let (cube_vertices, cube_indices, cube_index_count) = cube_geometry(device);
|
let (cube_vertices, cube_indices, cube_index_count) = cube_geometry(device);
|
||||||
|
let (wheel_vertices, wheel_indices, wheel_index_count) = wheel_geometry(device);
|
||||||
let terrain_instance = upload(
|
let terrain_instance = upload(
|
||||||
device,
|
device,
|
||||||
"fabrilis terrain instance",
|
"fabrilis terrain instance",
|
||||||
|
|
@ -109,6 +113,9 @@ pub(crate) fn build(device: &wgpu::Device, format: wgpu::TextureFormat) -> Pipel
|
||||||
cube_vertices,
|
cube_vertices,
|
||||||
cube_indices,
|
cube_indices,
|
||||||
cube_index_count,
|
cube_index_count,
|
||||||
|
wheel_vertices,
|
||||||
|
wheel_indices,
|
||||||
|
wheel_index_count,
|
||||||
terrain_instance,
|
terrain_instance,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -177,6 +184,71 @@ fn cube_geometry(device: &wgpu::Device) -> (wgpu::Buffer, wgpu::Buffer, u32) {
|
||||||
(vertex_buffer, index_buffer, indices.len() as u32)
|
(vertex_buffer, index_buffer, indices.len() as u32)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Segments around the wheel cylinder; a 24-gon reads as round at wheel size.
|
||||||
|
const WHEEL_SEGMENTS: usize = 24;
|
||||||
|
|
||||||
|
/// A point on the unit wheel's rim: the circle lies in the XZ plane, radius 0.5.
|
||||||
|
fn rim_point(segment: usize) -> (f32, f32) {
|
||||||
|
let angle = fabrilis_core::math::TAU * (segment as f64) / (WHEEL_SEGMENTS as f64);
|
||||||
|
let (sin, cos) = fabrilis_core::math::sin_cos(angle);
|
||||||
|
(cos as f32 * 0.5, sin as f32 * 0.5)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Unit wheel: radius 0.5, height 1.0, axis along the local Y, closed with caps.
|
||||||
|
///
|
||||||
|
/// The instance matrix places, rotates and scales it, so the mesh is built once.
|
||||||
|
fn wheel_geometry(device: &wgpu::Device) -> (wgpu::Buffer, wgpu::Buffer, u32) {
|
||||||
|
let mut vertices: Vec<[f32; 3]> = Vec::with_capacity(WHEEL_SEGMENTS * 5 + 2);
|
||||||
|
let mut indices: Vec<u32> = Vec::with_capacity(WHEEL_SEGMENTS * 12);
|
||||||
|
let half_height = 0.5;
|
||||||
|
for segment in 0..WHEEL_SEGMENTS {
|
||||||
|
let (x0, z0) = rim_point(segment);
|
||||||
|
let (x1, z1) = rim_point(segment + 1);
|
||||||
|
let base = vertices.len() as u32;
|
||||||
|
vertices.extend([
|
||||||
|
[x0, -half_height, z0],
|
||||||
|
[x0, half_height, z0],
|
||||||
|
[x1, half_height, z1],
|
||||||
|
[x1, -half_height, z1],
|
||||||
|
]);
|
||||||
|
indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
|
||||||
|
}
|
||||||
|
let top_centre = vertices.len() as u32;
|
||||||
|
vertices.push([0.0, half_height, 0.0]);
|
||||||
|
for segment in 0..WHEEL_SEGMENTS {
|
||||||
|
let (x, z) = rim_point(segment);
|
||||||
|
vertices.push([x, half_height, z]);
|
||||||
|
}
|
||||||
|
let bottom_centre = vertices.len() as u32;
|
||||||
|
vertices.push([0.0, -half_height, 0.0]);
|
||||||
|
for segment in 0..WHEEL_SEGMENTS {
|
||||||
|
let (x, z) = rim_point(segment);
|
||||||
|
vertices.push([x, -half_height, z]);
|
||||||
|
}
|
||||||
|
for segment in 0..WHEEL_SEGMENTS {
|
||||||
|
let next = (segment + 1) % WHEEL_SEGMENTS;
|
||||||
|
let top = top_centre + 1 + segment as u32;
|
||||||
|
let top_next = top_centre + 1 + next as u32;
|
||||||
|
indices.extend_from_slice(&[top_centre, top_next, top]);
|
||||||
|
let bottom = bottom_centre + 1 + segment as u32;
|
||||||
|
let bottom_next = bottom_centre + 1 + next as u32;
|
||||||
|
indices.extend_from_slice(&[bottom_centre, bottom, bottom_next]);
|
||||||
|
}
|
||||||
|
let vertex_buffer = upload(
|
||||||
|
device,
|
||||||
|
"fabrilis wheel vertices",
|
||||||
|
bytemuck::cast_slice(&vertices),
|
||||||
|
wgpu::BufferUsages::VERTEX,
|
||||||
|
);
|
||||||
|
let index_buffer = upload(
|
||||||
|
device,
|
||||||
|
"fabrilis wheel indices",
|
||||||
|
bytemuck::cast_slice(&indices),
|
||||||
|
wgpu::BufferUsages::INDEX,
|
||||||
|
);
|
||||||
|
(vertex_buffer, index_buffer, indices.len() as u32)
|
||||||
|
}
|
||||||
|
|
||||||
fn create_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
|
fn create_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
|
||||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||||
label: Some("fabrilis globals layout"),
|
label: Some("fabrilis globals layout"),
|
||||||
|
|
|
||||||
|
|
@ -78,6 +78,29 @@ fn renders_terrain_and_box() {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn renders_a_wheel() {
|
||||||
|
let (_gpu, mut renderer) = setup((SIZE, SIZE));
|
||||||
|
let mut scene = Scene::new(MeshData::default());
|
||||||
|
scene.wheels.push(Instance::new(
|
||||||
|
[
|
||||||
|
[2.0, 0.0, 0.0, 0.0],
|
||||||
|
[0.0, 0.5, 0.0, 0.0],
|
||||||
|
[0.0, 0.0, 2.0, 0.0],
|
||||||
|
[0.0, 0.0, 0.0, 1.0],
|
||||||
|
],
|
||||||
|
[0.9, 0.7, 0.2, 1.0],
|
||||||
|
));
|
||||||
|
renderer.draw(&scene, &orbit_camera()).expect("draw");
|
||||||
|
let pixels = renderer.pixels().expect("pixels");
|
||||||
|
let corner = pixel_at(&pixels, (SIZE, SIZE), 2, 2);
|
||||||
|
let centre = pixel_at(&pixels, (SIZE, SIZE), SIZE / 2, SIZE / 2);
|
||||||
|
assert_ne!(
|
||||||
|
corner, centre,
|
||||||
|
"the wheel must cover the centre of the frame"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn resize_reallocates_the_pixel_buffer() {
|
fn resize_reallocates_the_pixel_buffer() {
|
||||||
let (_gpu, mut renderer) = setup((SIZE, SIZE));
|
let (_gpu, mut renderer) = setup((SIZE, SIZE));
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
//! Scene data handed to the renderer: one triangle mesh plus instanced boxes.
|
//! Scene data handed to the renderer: one triangle mesh plus instanced boxes
|
||||||
|
//! and wheels.
|
||||||
|
|
||||||
type Mat4 = [[f32; 4]; 4];
|
type Mat4 = [[f32; 4]; 4];
|
||||||
|
|
||||||
|
|
@ -65,6 +66,8 @@ pub struct Scene {
|
||||||
pub mesh_color: [f32; 4],
|
pub mesh_color: [f32; 4],
|
||||||
/// Boxes drawn with instancing.
|
/// Boxes drawn with instancing.
|
||||||
pub instances: Vec<Instance>,
|
pub instances: Vec<Instance>,
|
||||||
|
/// Wheels: instanced cylinders with the axis along their local Y.
|
||||||
|
pub wheels: Vec<Instance>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Scene {
|
impl Scene {
|
||||||
|
|
@ -75,6 +78,7 @@ impl Scene {
|
||||||
mesh,
|
mesh,
|
||||||
mesh_color: [0.34, 0.46, 0.29, 1.0],
|
mesh_color: [0.34, 0.46, 0.29, 1.0],
|
||||||
instances: Vec::new(),
|
instances: Vec::new(),
|
||||||
|
wheels: Vec::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
269
crates/worldgen/src/terrain/lod.rs
Normal file
269
crates/worldgen/src/terrain/lod.rs
Normal file
|
|
@ -0,0 +1,269 @@
|
||||||
|
//! Chunked level of detail for the render terrain.
|
||||||
|
//!
|
||||||
|
//! [`Heightmap::mesh_lod`] still returns one [`TerrainMesh`], but the map is cut
|
||||||
|
//! into square chunks and each chunk keeps only every `step`-th grid node. The
|
||||||
|
//! step is a power of two chosen by the distance from the camera to the chunk
|
||||||
|
//! centre, so geometry near the camera keeps full resolution while distant
|
||||||
|
//! chunks cost far fewer triangles. Vertical skirts around each chunk hide the
|
||||||
|
//! cracks between neighbours with different steps.
|
||||||
|
//!
|
||||||
|
//! The collider is not reduced: physics keeps the full-resolution
|
||||||
|
//! [`Heightmap::mesh`]. This is the first LOD step; a ring or clipmap can follow
|
||||||
|
//! later without changing this API.
|
||||||
|
|
||||||
|
use fabrilis_core::math;
|
||||||
|
use fabrilis_core::vec::Vec3;
|
||||||
|
|
||||||
|
use super::{Heightmap, TerrainMesh};
|
||||||
|
|
||||||
|
/// Tuning for [`Heightmap::mesh_lod`].
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||||
|
pub struct LodConfig {
|
||||||
|
/// Cells along one side of a chunk; `0` is treated as `1`.
|
||||||
|
pub chunk_cells: usize,
|
||||||
|
/// Largest node step between kept vertices; clamped to a power of two and
|
||||||
|
/// to the chunk size, and at least one.
|
||||||
|
pub max_step: usize,
|
||||||
|
/// Depth of the vertical skirts around every chunk, m; values below zero
|
||||||
|
/// are treated as zero and non-finite values as zero.
|
||||||
|
pub skirt_m: f64,
|
||||||
|
/// Distance from the camera at which the step doubles, m; values below one
|
||||||
|
/// are treated as one.
|
||||||
|
pub switch_m: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for LodConfig {
|
||||||
|
/// 16-cell chunks, at most eight-node steps, one-metre skirts and a level
|
||||||
|
/// every 18 m.
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
chunk_cells: 16,
|
||||||
|
max_step: 8,
|
||||||
|
skirt_m: 1.0,
|
||||||
|
switch_m: 18.0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One chunk of the LOD mesh: a node range in the height grid plus its step.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct LodChunk {
|
||||||
|
/// First node of the chunk along X and Y, in grid indices.
|
||||||
|
pub origin: [usize; 2],
|
||||||
|
/// Chunk size in cells along X and Y; the last chunk may be shorter.
|
||||||
|
pub cells: [usize; 2],
|
||||||
|
/// Kept-node step along both axes, a power of two.
|
||||||
|
pub step: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Heightmap {
|
||||||
|
/// The chunks [`Self::mesh_lod`] would build, in row-major order.
|
||||||
|
///
|
||||||
|
/// The chunk grid depends only on `chunk_cells` and the map size; the
|
||||||
|
/// camera position only changes each chunk's [`LodChunk::step`]. Useful for
|
||||||
|
/// diagnostics and tests.
|
||||||
|
#[must_use]
|
||||||
|
pub fn lod_chunks(&self, center: Vec3, config: LodConfig) -> Vec<LodChunk> {
|
||||||
|
let chunk_cells = config.chunk_cells.max(1);
|
||||||
|
let total = self.size().saturating_sub(1);
|
||||||
|
let mut chunks = Vec::new();
|
||||||
|
let mut y0 = 0;
|
||||||
|
while y0 < total {
|
||||||
|
let cells_y = chunk_cells.min(total - y0);
|
||||||
|
let mut x0 = 0;
|
||||||
|
while x0 < total {
|
||||||
|
let cells_x = chunk_cells.min(total - x0);
|
||||||
|
let origin = [x0, y0];
|
||||||
|
let cells = [cells_x, cells_y];
|
||||||
|
let step = self.chunk_step(center, config, origin, cells);
|
||||||
|
chunks.push(LodChunk {
|
||||||
|
origin,
|
||||||
|
cells,
|
||||||
|
step,
|
||||||
|
});
|
||||||
|
x0 = x0.saturating_add(chunk_cells);
|
||||||
|
}
|
||||||
|
y0 = y0.saturating_add(chunk_cells);
|
||||||
|
}
|
||||||
|
chunks
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A chunked LOD mesh for a camera at `center`; see [`LodConfig`].
|
||||||
|
///
|
||||||
|
/// The result is one [`TerrainMesh`] in world coordinates, wound
|
||||||
|
/// counter-clockwise from above like [`Self::mesh`]. Chunks near `center`
|
||||||
|
/// keep every node, farther chunks keep every second, fourth, ... node up to
|
||||||
|
/// `config.max_step`. Each chunk gets a vertical skirt `config.skirt_m` deep.
|
||||||
|
///
|
||||||
|
/// Parameters are clamped as documented on [`LodConfig`], so no input
|
||||||
|
/// panics, and two identical calls return bit-identical meshes.
|
||||||
|
#[must_use]
|
||||||
|
pub fn mesh_lod(&self, center: Vec3, config: LodConfig) -> TerrainMesh {
|
||||||
|
let skirt = if config.skirt_m.is_finite() {
|
||||||
|
config.skirt_m.max(0.0)
|
||||||
|
} else {
|
||||||
|
0.0
|
||||||
|
};
|
||||||
|
let mut mesh = TerrainMesh::default();
|
||||||
|
for chunk in self.lod_chunks(center, config) {
|
||||||
|
self.push_chunk(&mut mesh, &chunk, skirt);
|
||||||
|
}
|
||||||
|
mesh
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The power-of-two step for one chunk, from the camera distance.
|
||||||
|
fn chunk_step(
|
||||||
|
&self,
|
||||||
|
center: Vec3,
|
||||||
|
config: LodConfig,
|
||||||
|
origin: [usize; 2],
|
||||||
|
cells: [usize; 2],
|
||||||
|
) -> usize {
|
||||||
|
let spacing = self.spacing();
|
||||||
|
let half = self.extent() * 0.5;
|
||||||
|
let chunk_x = (origin[0] as f64 + cells[0] as f64 * 0.5) * spacing - half;
|
||||||
|
let chunk_y = (origin[1] as f64 + cells[1] as f64 * 0.5) * spacing - half;
|
||||||
|
let dx = center.x - chunk_x;
|
||||||
|
let dy = center.y - chunk_y;
|
||||||
|
let distance = math::sqrt(dx * dx + dy * dy);
|
||||||
|
let cap = power_of_two_floor(config.max_step.max(1))
|
||||||
|
.min(power_of_two_floor(cells[0].min(cells[1]).max(1)));
|
||||||
|
if !distance.is_finite() {
|
||||||
|
return cap;
|
||||||
|
}
|
||||||
|
let switch = if config.switch_m.is_finite() {
|
||||||
|
config.switch_m.max(1.0)
|
||||||
|
} else {
|
||||||
|
1.0
|
||||||
|
};
|
||||||
|
let mut step = 1;
|
||||||
|
while step < cap && distance >= switch * step as f64 {
|
||||||
|
step *= 2;
|
||||||
|
}
|
||||||
|
step
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Appends one chunk's surface and skirt to `mesh`.
|
||||||
|
fn push_chunk(&self, mesh: &mut TerrainMesh, chunk: &LodChunk, skirt: f64) {
|
||||||
|
let xs = node_line(chunk.origin[0], chunk.cells[0], chunk.step);
|
||||||
|
let ys = node_line(chunk.origin[1], chunk.cells[1], chunk.step);
|
||||||
|
let base = mesh.vertices.len();
|
||||||
|
let spacing = self.spacing();
|
||||||
|
let half = self.extent() * 0.5;
|
||||||
|
for &j in &ys {
|
||||||
|
let y = j as f64 * spacing - half;
|
||||||
|
for &i in &xs {
|
||||||
|
let x = i as f64 * spacing - half;
|
||||||
|
mesh.vertices.push(Vec3::new(x, y, self.node(i, j)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mesh.indices.extend(build_indices(xs.len(), ys.len(), base));
|
||||||
|
if skirt > 0.0 {
|
||||||
|
push_skirt(mesh, base, xs.len(), ys.len(), skirt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Largest power of two not above `value`, and at least one.
|
||||||
|
fn power_of_two_floor(value: usize) -> usize {
|
||||||
|
let mut result: usize = 1;
|
||||||
|
while result.saturating_mul(2) <= value {
|
||||||
|
result *= 2;
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Two counter-clockwise triangles per cell of a `columns × rows` grid.
|
||||||
|
///
|
||||||
|
/// Indices are shifted by `base`, so several grids can share one vertex buffer.
|
||||||
|
pub(super) fn build_indices(columns: usize, rows: usize, base: usize) -> Vec<[u32; 3]> {
|
||||||
|
let cells_x = columns.saturating_sub(1);
|
||||||
|
let cells_y = rows.saturating_sub(1);
|
||||||
|
let mut indices = Vec::with_capacity(2 * cells_x * cells_y);
|
||||||
|
let shift = vertex_index(base);
|
||||||
|
for j in 0..cells_y {
|
||||||
|
for i in 0..cells_x {
|
||||||
|
let bottom_left = (j * columns + i) as u32 + shift;
|
||||||
|
let bottom_right = bottom_left + 1;
|
||||||
|
let top_left = bottom_left + columns as u32;
|
||||||
|
let top_right = top_left + 1;
|
||||||
|
indices.push([bottom_left, bottom_right, top_right]);
|
||||||
|
indices.push([bottom_left, top_right, top_left]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
indices
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Grid nodes to keep along one chunk axis, always including the last node.
|
||||||
|
fn node_line(start: usize, cells: usize, step: usize) -> Vec<usize> {
|
||||||
|
let step = step.max(1);
|
||||||
|
let end = start + cells;
|
||||||
|
let mut line = Vec::with_capacity(cells / step + 2);
|
||||||
|
let mut index = start;
|
||||||
|
while index < end {
|
||||||
|
line.push(index);
|
||||||
|
index += step;
|
||||||
|
}
|
||||||
|
if line.last().copied() != Some(end) {
|
||||||
|
line.push(end);
|
||||||
|
}
|
||||||
|
line
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Perimeter top vertices of a `columns × rows` chunk, counter-clockwise in XY.
|
||||||
|
fn perimeter(columns: usize, rows: usize) -> Vec<usize> {
|
||||||
|
let mut ring = Vec::with_capacity(2 * (columns + rows));
|
||||||
|
ring.extend(0..columns);
|
||||||
|
ring.extend((1..rows).map(|row| row * columns + columns - 1));
|
||||||
|
ring.extend(
|
||||||
|
(0..columns - 1)
|
||||||
|
.rev()
|
||||||
|
.map(|column| (rows - 1) * columns + column),
|
||||||
|
);
|
||||||
|
ring.extend((1..rows - 1).rev().map(|row| row * columns));
|
||||||
|
ring
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wall vertex index; the grid is capped at `MAX_SIZE²` vertices, so `u32` holds it.
|
||||||
|
fn vertex_index(value: usize) -> u32 {
|
||||||
|
value as u32
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Appends a vertical skirt around the chunk surface that starts at `base`.
|
||||||
|
///
|
||||||
|
/// The ring is counter-clockwise, so `[top, bottom_next, top_next]` and
|
||||||
|
/// `[top, bottom, bottom_next]` face outwards. The walls start exactly at the
|
||||||
|
/// border nodes, so the top surface is not modified.
|
||||||
|
fn push_skirt(mesh: &mut TerrainMesh, base: usize, columns: usize, rows: usize, skirt: f64) {
|
||||||
|
if columns < 2 || rows < 2 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let ring = perimeter(columns, rows);
|
||||||
|
let bottom_base = mesh.vertices.len();
|
||||||
|
for &top in &ring {
|
||||||
|
let Some(vertex) = mesh.vertices.get(base + top).copied() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
mesh.vertices
|
||||||
|
.push(Vec3::new(vertex.x, vertex.y, vertex.z - skirt));
|
||||||
|
}
|
||||||
|
let count = ring.len();
|
||||||
|
for (edge, &top) in ring.iter().enumerate() {
|
||||||
|
let next = (edge + 1) % count;
|
||||||
|
let Some(&next_top) = ring.get(next) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let a_bottom = bottom_base + edge;
|
||||||
|
let b_bottom = bottom_base + next;
|
||||||
|
mesh.indices.push([
|
||||||
|
vertex_index(base + top),
|
||||||
|
vertex_index(b_bottom),
|
||||||
|
vertex_index(base + next_top),
|
||||||
|
]);
|
||||||
|
mesh.indices.push([
|
||||||
|
vertex_index(base + top),
|
||||||
|
vertex_index(a_bottom),
|
||||||
|
vertex_index(b_bottom),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -10,6 +10,10 @@ use fabrilis_core::vec::Vec3;
|
||||||
|
|
||||||
use crate::noise::{Noise, fbm};
|
use crate::noise::{Noise, fbm};
|
||||||
|
|
||||||
|
mod lod;
|
||||||
|
|
||||||
|
pub use lod::{LodChunk, LodConfig};
|
||||||
|
|
||||||
/// Smallest accepted grid resolution; two nodes still form one cell.
|
/// Smallest accepted grid resolution; two nodes still form one cell.
|
||||||
const MIN_SIZE: usize = 2;
|
const MIN_SIZE: usize = 2;
|
||||||
|
|
||||||
|
|
@ -259,7 +263,7 @@ impl Heightmap {
|
||||||
let step = step.max(1);
|
let step = step.max(1);
|
||||||
let nodes = (self.config.size - 1) / step + 1;
|
let nodes = (self.config.size - 1) / step + 1;
|
||||||
let vertices = self.build_vertices(nodes, step);
|
let vertices = self.build_vertices(nodes, step);
|
||||||
let indices = build_indices(nodes);
|
let indices = lod::build_indices(nodes, nodes, 0);
|
||||||
TerrainMesh { vertices, indices }
|
TerrainMesh { vertices, indices }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -318,24 +322,6 @@ fn neighbours(position: f64, last: f64) -> (f64, f64) {
|
||||||
((position - 1.0).max(0.0), (position + 1.0).min(last))
|
((position - 1.0).max(0.0), (position + 1.0).min(last))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Two counter-clockwise triangles per cell, joined into `u32` indices.
|
|
||||||
fn build_indices(nodes: usize) -> Vec<[u32; 3]> {
|
|
||||||
let cells = nodes.saturating_sub(1);
|
|
||||||
let mut indices = Vec::with_capacity(2 * cells * cells);
|
|
||||||
let row = nodes as u32;
|
|
||||||
for j in 0..cells {
|
|
||||||
for i in 0..cells {
|
|
||||||
let bottom_left = (j * nodes + i) as u32;
|
|
||||||
let bottom_right = bottom_left + 1;
|
|
||||||
let top_left = bottom_left + row;
|
|
||||||
let top_right = top_left + 1;
|
|
||||||
indices.push([bottom_left, bottom_right, top_right]);
|
|
||||||
indices.push([bottom_left, top_right, top_left]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
indices
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A triangle mesh of the terrain surface, ready for a renderer or a collider.
|
/// A triangle mesh of the terrain surface, ready for a renderer or a collider.
|
||||||
#[derive(Debug, Clone, Default, PartialEq)]
|
#[derive(Debug, Clone, Default, PartialEq)]
|
||||||
pub struct TerrainMesh {
|
pub struct TerrainMesh {
|
||||||
|
|
|
||||||
|
|
@ -328,3 +328,202 @@ fn errors_implement_display_and_error() {
|
||||||
let dynamic: &dyn std::error::Error = &error;
|
let dynamic: &dyn std::error::Error = &error;
|
||||||
assert_eq!(dynamic.to_string(), text);
|
assert_eq!(dynamic.to_string(), text);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The flat map used by the LOD tests: same 65 nodes over 100 m as the window,
|
||||||
|
/// so every node coordinate is binary-exact.
|
||||||
|
fn lod_map() -> Heightmap {
|
||||||
|
Heightmap::generate(TerrainConfig {
|
||||||
|
size: 65,
|
||||||
|
extent: 100.0,
|
||||||
|
height_scale: 0.0,
|
||||||
|
..TerrainConfig::default()
|
||||||
|
})
|
||||||
|
.expect("the LOD test config is valid")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lod_config() -> LodConfig {
|
||||||
|
LodConfig {
|
||||||
|
chunk_cells: 16,
|
||||||
|
max_step: 8,
|
||||||
|
skirt_m: 1.0,
|
||||||
|
switch_m: 18.0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The camera stands near the middle, off the grid centre.
|
||||||
|
fn lod_center() -> Vec3 {
|
||||||
|
Vec3::new(10.0, -16.0, 7.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The chunk that owns a cell; every cell belongs to exactly one chunk.
|
||||||
|
fn chunk_at(chunks: &[LodChunk], cell: [usize; 2]) -> &LodChunk {
|
||||||
|
chunks
|
||||||
|
.iter()
|
||||||
|
.find(|chunk| {
|
||||||
|
cell[0] >= chunk.origin[0]
|
||||||
|
&& cell[0] < chunk.origin[0] + chunk.cells[0]
|
||||||
|
&& cell[1] >= chunk.origin[1]
|
||||||
|
&& cell[1] < chunk.origin[1] + chunk.cells[1]
|
||||||
|
})
|
||||||
|
.expect("the cell belongs to a chunk")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lod_mesh_stays_inside_the_map_and_uses_flat_heights_and_skirts() {
|
||||||
|
let map = lod_map();
|
||||||
|
let config = lod_config();
|
||||||
|
let mesh = map.mesh_lod(lod_center(), config);
|
||||||
|
assert!(!mesh.vertices.is_empty());
|
||||||
|
let half = map.extent() * 0.5;
|
||||||
|
for vertex in &mesh.vertices {
|
||||||
|
assert!(vertex.x.is_finite() && vertex.y.is_finite() && vertex.z.is_finite());
|
||||||
|
assert!(vertex.x >= -half && vertex.x <= half);
|
||||||
|
assert!(vertex.y >= -half && vertex.y <= half);
|
||||||
|
assert!(vertex.z == 0.0 || vertex.z == -config.skirt_m);
|
||||||
|
}
|
||||||
|
assert!(mesh.vertices.iter().any(|vertex| vertex.z == 0.0));
|
||||||
|
assert!(
|
||||||
|
mesh.vertices
|
||||||
|
.iter()
|
||||||
|
.any(|vertex| vertex.z == -config.skirt_m)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lod_mesh_has_fewer_triangles_than_the_full_mesh() {
|
||||||
|
let map = lod_map();
|
||||||
|
let full = map.mesh();
|
||||||
|
let lod = map.mesh_lod(lod_center(), lod_config());
|
||||||
|
assert!(
|
||||||
|
lod.indices.len() < full.indices.len(),
|
||||||
|
"lod {} triangles, full {}",
|
||||||
|
lod.indices.len(),
|
||||||
|
full.indices.len()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lod_mesh_is_deterministic() {
|
||||||
|
let map = lod_map();
|
||||||
|
let first = map.mesh_lod(lod_center(), lod_config());
|
||||||
|
let second = map.mesh_lod(lod_center(), lod_config());
|
||||||
|
assert_eq!(first.vertices.len(), second.vertices.len());
|
||||||
|
assert_eq!(first.indices.len(), second.indices.len());
|
||||||
|
for (left, right) in first.vertices.iter().zip(&second.vertices) {
|
||||||
|
assert_eq!(left.x.to_bits(), right.x.to_bits());
|
||||||
|
assert_eq!(left.y.to_bits(), right.y.to_bits());
|
||||||
|
assert_eq!(left.z.to_bits(), right.z.to_bits());
|
||||||
|
}
|
||||||
|
assert_eq!(first.indices, second.indices);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lod_steps_grow_with_distance_from_the_camera() {
|
||||||
|
let map = lod_map();
|
||||||
|
let config = lod_config();
|
||||||
|
let chunks = map.lod_chunks(lod_center(), config);
|
||||||
|
for chunk in &chunks {
|
||||||
|
assert!(
|
||||||
|
chunk.step.is_power_of_two(),
|
||||||
|
"step {} is not a power of two",
|
||||||
|
chunk.step
|
||||||
|
);
|
||||||
|
assert!(chunk.step <= config.max_step);
|
||||||
|
assert!(chunk.step <= chunk.cells[0].min(chunk.cells[1]));
|
||||||
|
}
|
||||||
|
// The camera sits at grid (38.4, 21.8), in the chunk starting at (32, 16);
|
||||||
|
// the opposite corner is the farthest chunk.
|
||||||
|
let near = chunk_at(&chunks, [38, 21]);
|
||||||
|
let far = chunk_at(&chunks, [0, 0]);
|
||||||
|
assert_eq!(
|
||||||
|
near.step, 1,
|
||||||
|
"the chunk under the camera is full resolution"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
far.step > near.step,
|
||||||
|
"far step {} should exceed near step {}",
|
||||||
|
far.step,
|
||||||
|
near.step
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lod_chunks_cover_every_cell_exactly_once() {
|
||||||
|
let map = lod_map();
|
||||||
|
let config = lod_config();
|
||||||
|
let chunks = map.lod_chunks(lod_center(), config);
|
||||||
|
let cells = map.size() - 1;
|
||||||
|
let mut covered = vec![0u32; cells * cells];
|
||||||
|
for chunk in &chunks {
|
||||||
|
for j in chunk.origin[1]..chunk.origin[1] + chunk.cells[1] {
|
||||||
|
for i in chunk.origin[0]..chunk.origin[0] + chunk.cells[0] {
|
||||||
|
covered[j * cells + i] += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(covered.iter().all(|count| *count == 1));
|
||||||
|
assert_eq!(chunks.len(), 16, "four chunks per axis on a 64-cell map");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lod_skirts_surround_every_chunk() {
|
||||||
|
let map = lod_map();
|
||||||
|
let config = lod_config();
|
||||||
|
let chunks = map.lod_chunks(lod_center(), config);
|
||||||
|
let mesh = map.mesh_lod(lod_center(), config);
|
||||||
|
let expected: usize = chunks
|
||||||
|
.iter()
|
||||||
|
.map(|chunk| {
|
||||||
|
let columns = chunk.cells[0].div_ceil(chunk.step) + 1;
|
||||||
|
let rows = chunk.cells[1].div_ceil(chunk.step) + 1;
|
||||||
|
2 * (columns + rows) - 4
|
||||||
|
})
|
||||||
|
.sum();
|
||||||
|
let bottom = mesh
|
||||||
|
.vertices
|
||||||
|
.iter()
|
||||||
|
.filter(|vertex| vertex.z == -config.skirt_m)
|
||||||
|
.count();
|
||||||
|
assert_eq!(bottom, expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lod_triangles_face_up_or_are_vertical_walls() {
|
||||||
|
let map = lod_map();
|
||||||
|
let mesh = map.mesh_lod(lod_center(), lod_config());
|
||||||
|
let mut up = 0;
|
||||||
|
for triangle in &mesh.indices {
|
||||||
|
let area = triangle_z(&mesh.vertices, triangle);
|
||||||
|
assert!(area >= 0.0, "a triangle is wound downwards: {area}");
|
||||||
|
if area > 0.0 {
|
||||||
|
up += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(up > 0, "the surface has upward triangles");
|
||||||
|
assert!(up < mesh.indices.len(), "the walls are vertical");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn degenerate_lod_parameters_do_not_panic() {
|
||||||
|
let map = lod_map();
|
||||||
|
let config = LodConfig {
|
||||||
|
chunk_cells: 0,
|
||||||
|
max_step: 0,
|
||||||
|
skirt_m: -5.0,
|
||||||
|
switch_m: 0.0,
|
||||||
|
};
|
||||||
|
let mesh = map.mesh_lod(Vec3::new(f64::NAN, f64::INFINITY, 0.0), config);
|
||||||
|
assert!(!mesh.vertices.is_empty());
|
||||||
|
assert!(mesh.vertices.iter().all(|vertex| vertex.z == 0.0));
|
||||||
|
let tiny = Heightmap::generate(TerrainConfig {
|
||||||
|
size: 2,
|
||||||
|
extent: 10.0,
|
||||||
|
height_scale: 0.0,
|
||||||
|
..TerrainConfig::default()
|
||||||
|
})
|
||||||
|
.expect("a two-node map is valid");
|
||||||
|
for chunk in tiny.lod_chunks(Vec3::new(0.0, 0.0, 0.0), config) {
|
||||||
|
assert_eq!(chunk.step, 1);
|
||||||
|
}
|
||||||
|
assert!(!tiny.mesh_lod(Vec3::ZERO, config).indices.is_empty());
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -55,6 +55,29 @@
|
||||||
на подготовку снимка. Бюджет проверяется бенчмарком в автоматическом прогоне; выход за него — повод
|
на подготовку снимка. Бюджет проверяется бенчмарком в автоматическом прогоне; выход за него — повод
|
||||||
переходить на `ash` (D24) или упрощать World, но не менять шаг.
|
переходить на `ash` (D24) или упрощать World, но не менять шаг.
|
||||||
|
|
||||||
|
## Рельеф и LOD
|
||||||
|
`worldgen::terrain` строит высотную карту и один меш на её основе (D14). Первый шаг
|
||||||
|
LOD — chunked LOD без отдельного прохода рендера:
|
||||||
|
|
||||||
|
- карта режется на чанки по `LodConfig::chunk_cells` клеток, последний чанк короче;
|
||||||
|
- внутри чанка остаются каждый `step`-й узел, `step` — степень двойки не больше
|
||||||
|
`max_step` и размера чанка; шаг растёт с расстоянием от камеры до центра чанка
|
||||||
|
(`switch_m` на удвоение);
|
||||||
|
- по периметру каждого чанка идёт вертикальная юбка глубиной `skirt_m`, она
|
||||||
|
закрывает трещины между соседями с разным шагом и не меняет верхнюю поверхность;
|
||||||
|
- приложение хранит центр, от которого построен меш, и пересобирает его, когда
|
||||||
|
камера сместилась на `LOD_REBUILD_M` (4 м); между перестроениями кадр платит
|
||||||
|
только проверку расстояния.
|
||||||
|
|
||||||
|
Результат по-прежнему один `TerrainMesh` в сцене, поэтому рендер не менялся.
|
||||||
|
Физика работает на полном меше `heightmap.mesh()`: LOD облегчает только картинку
|
||||||
|
и не влияет на столкновения или детерминизм симуляции.
|
||||||
|
|
||||||
|
Это честно первый шаг: шаг выбирается по расстоянию до чанка, а не по экранной
|
||||||
|
ошибке, и границы чанков могут заметно переключаться при движении. Продолжение —
|
||||||
|
rings/clipmap с сеткой, сшитой без юбок, и выбором детализации по проекции ошибки
|
||||||
|
на экран.
|
||||||
|
|
||||||
## Адаптация под устройство
|
## Адаптация под устройство
|
||||||
`platform` определяет ядра (P/E), SIMD, RAM, GPU и кеширует профиль. Адаптируется
|
`platform` определяет ядра (P/E), SIMD, RAM, GPU и кеширует профиль. Адаптируется
|
||||||
только то, что не влияет на результат: число потоков, раскладка по ядрам, качество
|
только то, что не влияет на результат: число потоков, раскладка по ядрам, качество
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,28 @@
|
||||||
|
|
||||||
Правила для кода — в [CODE_RULES.md](CODE_RULES.md), раздел «Логирование».
|
Правила для кода — в [CODE_RULES.md](CODE_RULES.md), раздел «Логирование».
|
||||||
|
|
||||||
|
## Фасад `core::log`
|
||||||
|
|
||||||
|
Библиотеки пишут через `fabrilis_core::log`, а не через `println!` и не через
|
||||||
|
внешний `log`/`tracing` (D35):
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use fabrilis_core::log::{info, warn};
|
||||||
|
|
||||||
|
info!("world", "terrain seed={} size={}", seed, size);
|
||||||
|
warn!("physics", "solver degraded: iterations={}", iterations);
|
||||||
|
```
|
||||||
|
|
||||||
|
Первый аргумент макроса — target (подсистема), дальше обычный `format!`-шаблон.
|
||||||
|
Уровни: `error`, `warn`, `info`, `debug`, `trace`. Аргументы не вычисляются и не
|
||||||
|
форматируются, если уровень выключен или приёмник не установлен. `Record`
|
||||||
|
заимствует target и сообщение; аллокацию делает приёмник.
|
||||||
|
|
||||||
|
Приложение ставит приёмник один раз до стартового баннера:
|
||||||
|
`app` открывает dev-лог по `--log` (или `--dev`) и регистрирует `DevLogSink`.
|
||||||
|
`--dev` включает `trace`, обычный запуск — `info`. Без файла приёмника нет, и
|
||||||
|
фасад молчит, не создавая файлов.
|
||||||
|
|
||||||
## Оверлей
|
## Оверлей
|
||||||
|
|
||||||
Поверх кадра показывается панель (левый верхний угол выбран для M4d):
|
Поверх кадра показывается панель (левый верхний угол выбран для M4d):
|
||||||
|
|
@ -26,6 +48,10 @@
|
||||||
физики, авто-масштаб по максимуму, сетка и подписи 0 / max мс. Пики контактов
|
физики, авто-масштаб по максимуму, сетка и подписи 0 / max мс. Пики контактов
|
||||||
(переворот куба, удар) должны быть видны как узкие высокие всплески.
|
(переворот куба, удар) должны быть видны как узкие высокие всплески.
|
||||||
|
|
||||||
|
Заголовок окна с `RTF` обновляется не чаще раза в секунду: на Wayland каждый
|
||||||
|
`set_title` — это запрос композитору, и слать его на каждом кадре незачем. Формат
|
||||||
|
заголовка не меняется, «...» остаётся до первого измерения RTF.
|
||||||
|
|
||||||
## Флаги запуска
|
## Флаги запуска
|
||||||
|
|
||||||
| Флаг | Что делает |
|
| Флаг | Что делает |
|
||||||
|
|
@ -68,9 +94,26 @@ GPU в dev-логе, нет.
|
||||||
- созданные тела, коллайдеры, массы, стартовые позы;
|
- созданные тела, коллайдеры, массы, стартовые позы;
|
||||||
- параметры камеры и изменения управления (без покадрового шума);
|
- параметры камеры и изменения управления (без покадрового шума);
|
||||||
- раз в секунду — сводку метрик;
|
- раз в секунду — сводку метрик;
|
||||||
- каждый пик: номер кадра, время кадра, время физики, причина (`contact`/`resize`/`render`);
|
- каждый пик: номер кадра, время кадра и физического шага, время фаз `render_ms`,
|
||||||
|
`overlay_ms`, `title_ms`, стоимость чтения `/proc` `metrics_us`, число шагов
|
||||||
|
(`steps`) и причину (`frame`/`physics`/`frame+physics`);
|
||||||
- ошибки wgpu/Rapier с контекстом.
|
- ошибки wgpu/Rapier с контекстом.
|
||||||
|
|
||||||
|
Строка пика выглядит так:
|
||||||
|
|
||||||
|
```text
|
||||||
|
frame=4517 frame_ms=1873.22 physics_step_ms=0.124 render_ms=1.29 overlay_ms=0.05 title_ms=0.01 metrics_us=99 steps=50 trigger=frame
|
||||||
|
```
|
||||||
|
|
||||||
|
Поля позволяют сразу отделить виновника. `render_ms` включает блокирующий захват
|
||||||
|
surface, поэтому в ровном режиме он близок к одному интервалу vsync (~13 мс при
|
||||||
|
75 Гц). Если `frame_ms` заметно больше суммы фаз, а `render_ms` остаётся в норме,
|
||||||
|
кадр задержался вне приложения: оно ждало callback композитора (пропуск vsync,
|
||||||
|
внешняя нагрузка). Если растёт `physics_step_ms` — виновата симуляция, если
|
||||||
|
`overlay_ms` — сборка панели, `metrics_us` — чтение `/proc` (обычно ~0.1 мс, то
|
||||||
|
есть шум). Большой `render_ms` вместе с большим `frame_ms` — блокировка на
|
||||||
|
захвате поверхности или в драйвере GPU.
|
||||||
|
|
||||||
Пик логируется отдельной строкой, поэтому «лаг в момент переворота» можно найти в
|
Пик логируется отдельной строкой, поэтому «лаг в момент переворота» можно найти в
|
||||||
логе, а не только на графике.
|
логе, а не только на графике.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -37,6 +37,9 @@
|
||||||
|
|
||||||
Название: Fabrilis (лат. fabrilis, «относящийся к мастеру, ремесленнику»). Автор: loki.
|
Название: Fabrilis (лат. fabrilis, «относящийся к мастеру, ремесленнику»). Автор: loki.
|
||||||
|
|
||||||
Статус: готовы M0 (скелет, правила) и M1 (ядро: единицы, время, математика,
|
Статус: готовы M0 (скелет, правила), M1 (ядро: единицы, время, математика,
|
||||||
планировщик, Fidelity, снимки). Дальше M2 — один шарнир: своя векторная
|
планировщик, Fidelity, снимки), M2 (векторы, RNG, шарнир с мотором, датчики,
|
||||||
математика, seeded RNG, минимальная физика с мотором и датчиками.
|
PD-контур), M3 (импорт STL/OBJ, массы и инерция, материалы, RON-сцены,
|
||||||
|
blob-store) и M4 (рельеф и chunked LOD, wgpu-рендер, тележка на шарнирах,
|
||||||
|
оверлей и логи). Дальше M5 — эталонный паук: конструкция, приводы, контакт стоп
|
||||||
|
с землёй и устойчивость.
|
||||||
|
|
|
||||||
18
docs/UI.md
18
docs/UI.md
|
|
@ -33,6 +33,24 @@ UI-фреймворк и не библиотека для чужих прогр
|
||||||
Виджеты вводятся по одному и только под конкретную задачу редактора. Зоопарк
|
Виджеты вводятся по одному и только под конкретную задачу редактора. Зоопарк
|
||||||
«на будущее» запрещён (KISS).
|
«на будущее» запрещён (KISS).
|
||||||
|
|
||||||
|
## Управление (M4)
|
||||||
|
|
||||||
|
В окне одна сцена: тележка на террейне. Ввод задаёт только цель моторов на
|
||||||
|
границе кадра и не меняет шаг симуляции.
|
||||||
|
|
||||||
|
| Ввод | Действие |
|
||||||
|
|---|---|
|
||||||
|
| `W` / `S` | газ вперёд / назад (тележка) |
|
||||||
|
| `A` / `D` | поворот влево / вправо (тележка) |
|
||||||
|
| Стрелки | камера: вперёд/назад, влево/вправо |
|
||||||
|
| `Q` / `E` | камера вниз / вверх |
|
||||||
|
| `Shift` | ускорить камеру |
|
||||||
|
| ЛКМ + мышь | обзор камерой |
|
||||||
|
| `Escape` | выход |
|
||||||
|
|
||||||
|
Когда клавиши отпущены, цель моторов — ноль: тележка тормозит, а не катится
|
||||||
|
по инерции.
|
||||||
|
|
||||||
## Текст
|
## Текст
|
||||||
|
|
||||||
- Сейчас: `fontdue` только растеризует глифы, раскладку строк и переносы делаем сами.
|
- Сейчас: `fontdue` только растеризует глифы, раскладку строк и переносы делаем сами.
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,3 @@
|
||||||
[toolchain]
|
[toolchain]
|
||||||
channel = "1.99.1"
|
channel = "1.100.0"
|
||||||
components = ["rustfmt", "clippy"]
|
components = ["rustfmt", "clippy"]
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue