Add design persistence, world rendering, metrics overlay and logs
M3: STL/OBJ import with mesh validation, mass/COM/inertia, material database, RON scene with content-addressed blobs and v0->v1 migration. M4: deterministic heightmap terrain, trimesh colliders, wgpu renderer with instancing and depth, winit app with 1 kHz physics, fly camera, on-screen metrics overlay and per-frame CSV/dev logs. Docs: UI, logging, network and headless CLI plans.
This commit is contained in:
parent
878d144b77
commit
190ef9cc4b
111 changed files with 14801 additions and 63 deletions
141
crates/app/src/runtime/metrics/csv.rs
Normal file
141
crates/app/src/runtime/metrics/csv.rs
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
//! Per-frame metrics CSV writer and the spike rule shared with the dev log.
|
||||
//!
|
||||
//! The writer is a passive observer: it reads values that the overlay already
|
||||
//! computed and never calls into physics or the renderer.
|
||||
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::{self, Write};
|
||||
use std::path::Path;
|
||||
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use super::Stats;
|
||||
|
||||
/// The one header line, in the documented column order.
|
||||
pub(crate) const HEADER: &str = "unix_s,t_s,frame,fps,tps,frame_ms,frame_max_ms,physics_ms,physics_max_ms,render_ms,rtf,cpu_pct,load1,rss_mb,spike";
|
||||
|
||||
/// A frame longer than this is a spike, milliseconds.
|
||||
const FRAME_BUDGET_MS: f32 = 20.0;
|
||||
|
||||
/// A single physics step longer than this is a spike, milliseconds.
|
||||
const STEP_BUDGET_MS: f32 = 1.0;
|
||||
|
||||
/// At most one flush per this interval while logging, seconds.
|
||||
const FLUSH_INTERVAL_SECONDS: u64 = 1;
|
||||
|
||||
/// One row of the metrics CSV.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Row<'a> {
|
||||
/// Wall-clock seconds at the start of the frame.
|
||||
pub(crate) unix_s: f64,
|
||||
/// Simulated seconds before this frame was drawn.
|
||||
pub(crate) t_s: f64,
|
||||
/// Number of the rendered frame, starting at one.
|
||||
pub(crate) frame: u64,
|
||||
/// The same rolling values the overlay shows.
|
||||
pub(crate) stats: &'a Stats,
|
||||
/// Whether the frame or one of its physics steps blew its budget.
|
||||
pub(crate) spike: bool,
|
||||
}
|
||||
|
||||
/// Formats a row exactly as the header orders it.
|
||||
pub(crate) fn format_row(row: &Row<'_>) -> String {
|
||||
let stats = row.stats;
|
||||
format!(
|
||||
"{:.3},{:.3},{},{:.1},{:.1},{:.2},{:.2},{:.2},{:.2},{:.2},{:.2},{:.1},{:.2},{:.1},{}",
|
||||
row.unix_s,
|
||||
row.t_s,
|
||||
row.frame,
|
||||
stats.fps,
|
||||
stats.tps,
|
||||
stats.frame_avg_ms,
|
||||
stats.frame_max_ms,
|
||||
stats.physics_avg_ms,
|
||||
stats.physics_max_ms,
|
||||
stats.render_avg_ms,
|
||||
stats.rtf,
|
||||
stats.cpu_percent,
|
||||
stats.load_1m,
|
||||
stats.rss_mb,
|
||||
u8::from(row.spike),
|
||||
)
|
||||
}
|
||||
|
||||
/// Why a frame counts as a spike, or `None` when it fits the budget.
|
||||
pub(crate) fn spike_reason(frame_ms: f32, slowest_step_ms: f32) -> Option<&'static str> {
|
||||
match (frame_ms > FRAME_BUDGET_MS, slowest_step_ms > STEP_BUDGET_MS) {
|
||||
(true, true) => Some("frame+physics"),
|
||||
(true, false) => Some("frame"),
|
||||
(false, true) => Some("physics"),
|
||||
(false, false) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Wall-clock seconds since the Unix epoch.
|
||||
#[allow(
|
||||
clippy::disallowed_methods,
|
||||
reason = "the metrics CSV stamps the frame start with wall-clock time"
|
||||
)]
|
||||
pub(crate) fn unix_now() -> f64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0.0, |elapsed| elapsed.as_secs_f64())
|
||||
}
|
||||
|
||||
/// An open metrics CSV file.
|
||||
pub(crate) struct CsvLog {
|
||||
file: File,
|
||||
last_flush: Instant,
|
||||
}
|
||||
|
||||
impl CsvLog {
|
||||
/// Opens the file, truncating it unless `append` is set. The header is
|
||||
/// written when the file starts empty, so an appended file keeps one.
|
||||
#[allow(
|
||||
clippy::disallowed_methods,
|
||||
reason = "the metrics writer throttles flushes with wall-clock time"
|
||||
)]
|
||||
pub(crate) fn open(path: &Path, append: bool) -> io::Result<Self> {
|
||||
let has_rows = append && fs::metadata(path).is_ok_and(|meta| meta.len() > 0);
|
||||
let mut file = OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
.append(append)
|
||||
.truncate(!append)
|
||||
.open(path)?;
|
||||
if !has_rows {
|
||||
file.write_all(HEADER.as_bytes())?;
|
||||
file.write_all(b"\n")?;
|
||||
}
|
||||
Ok(Self {
|
||||
file,
|
||||
last_flush: Instant::now(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Writes one row and flushes at most once per second.
|
||||
pub(crate) fn record(&mut self, row: &Row<'_>) -> io::Result<()> {
|
||||
writeln!(self.file, "{}", format_row(row))?;
|
||||
if self.last_flush.elapsed().as_secs() >= FLUSH_INTERVAL_SECONDS {
|
||||
self.flush()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pushes buffered rows to disk and restarts the flush interval.
|
||||
#[allow(
|
||||
clippy::disallowed_methods,
|
||||
reason = "the metrics writer throttles flushes with wall-clock time"
|
||||
)]
|
||||
pub(crate) fn flush(&mut self) -> io::Result<()> {
|
||||
self.file.flush()?;
|
||||
self.last_flush = Instant::now();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for CsvLog {
|
||||
fn drop(&mut self) {
|
||||
// The final flush is best effort: dropping must not abort the process.
|
||||
let _ = self.file.flush();
|
||||
}
|
||||
}
|
||||
237
crates/app/src/runtime/metrics/mod.rs
Normal file
237
crates/app/src/runtime/metrics/mod.rs
Normal file
|
|
@ -0,0 +1,237 @@
|
|||
//! Rolling frame, physics, render and process metrics for the debug overlay.
|
||||
//!
|
||||
//! Wall-clock reads live here: the rest of the application only measures phases
|
||||
//! through [`Stopwatch`] and never looks at the system clock itself.
|
||||
|
||||
mod csv;
|
||||
mod panel;
|
||||
mod proc;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use self::proc::ProcSample;
|
||||
|
||||
pub(crate) use csv::{CsvLog, Row, spike_reason, unix_now};
|
||||
|
||||
/// Length of the rolling statistics window, seconds.
|
||||
const WINDOW_SECONDS: f32 = 1.0;
|
||||
|
||||
/// Frames kept for the graph.
|
||||
const HISTORY: usize = 180;
|
||||
/// Linux `USER_HZ`: `/proc` CPU ticks per second.
|
||||
const TICKS_PER_SECOND: f32 = 100.0;
|
||||
/// Physics and render work of one frame, as measured by the caller.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub(crate) struct FrameWork {
|
||||
pub(crate) physics: Duration,
|
||||
pub(crate) render: Duration,
|
||||
pub(crate) steps: u32,
|
||||
}
|
||||
|
||||
/// One frame in the rolling statistics window.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct Sample {
|
||||
at: f32,
|
||||
frame_ms: f32,
|
||||
physics_ms: f32,
|
||||
render_ms: f32,
|
||||
steps: u32,
|
||||
cpu_ticks: u32,
|
||||
}
|
||||
|
||||
/// Aggregates over the last second, rebuilt after every frame.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub(crate) struct Stats {
|
||||
pub(crate) fps: f32,
|
||||
pub(crate) tps: f32,
|
||||
pub(crate) frame_avg_ms: f32,
|
||||
pub(crate) frame_max_ms: f32,
|
||||
pub(crate) physics_avg_ms: f32,
|
||||
pub(crate) physics_max_ms: f32,
|
||||
pub(crate) render_avg_ms: f32,
|
||||
pub(crate) cpu_percent: f32,
|
||||
pub(crate) load_1m: f32,
|
||||
pub(crate) rss_mb: f32,
|
||||
pub(crate) rtf: f32,
|
||||
}
|
||||
|
||||
/// Wall-clock measurement of one phase of a frame.
|
||||
pub(crate) struct Stopwatch {
|
||||
start: Instant,
|
||||
}
|
||||
|
||||
impl Stopwatch {
|
||||
/// Starts a phase measurement.
|
||||
#[allow(
|
||||
clippy::disallowed_methods,
|
||||
reason = "the diagnostics overlay is the one place that measures wall time"
|
||||
)]
|
||||
pub(crate) fn start() -> Self {
|
||||
Self {
|
||||
start: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The time spent since [`Stopwatch::start`].
|
||||
pub(crate) fn elapsed(self) -> Duration {
|
||||
self.start.elapsed()
|
||||
}
|
||||
}
|
||||
|
||||
/// The rolling window behind the diagnostics panel.
|
||||
pub(crate) struct Metrics {
|
||||
last: Instant,
|
||||
clock: f32,
|
||||
window: VecDeque<Sample>,
|
||||
history: VecDeque<[f32; 2]>,
|
||||
last_ticks: Option<u64>,
|
||||
rtf: Option<f32>,
|
||||
primed: bool,
|
||||
stats: Stats,
|
||||
}
|
||||
|
||||
impl Default for Metrics {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Metrics {
|
||||
/// Starts the frame clock.
|
||||
#[allow(
|
||||
clippy::disallowed_methods,
|
||||
reason = "the diagnostics overlay is the one place that measures wall time"
|
||||
)]
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
last: Instant::now(),
|
||||
clock: 0.0,
|
||||
window: VecDeque::with_capacity(HISTORY),
|
||||
history: VecDeque::with_capacity(HISTORY),
|
||||
last_ticks: None,
|
||||
rtf: None,
|
||||
primed: false,
|
||||
stats: Stats::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Wall time since the previous call, that is the previous frame's duration.
|
||||
#[allow(
|
||||
clippy::disallowed_methods,
|
||||
reason = "the diagnostics overlay is the one place that measures wall time"
|
||||
)]
|
||||
pub(crate) fn frame_time(&mut self) -> Duration {
|
||||
let now = Instant::now();
|
||||
let elapsed = now.duration_since(self.last);
|
||||
self.last = now;
|
||||
elapsed
|
||||
}
|
||||
|
||||
/// Keeps the latest simulation-to-wall ratio reported by the pacer.
|
||||
pub(crate) fn set_rtf(&mut self, rtf: Option<f32>) {
|
||||
if rtf.is_some() {
|
||||
self.rtf = rtf;
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds one frame to the rolling window and refreshes the aggregates.
|
||||
///
|
||||
/// The first frame is warm-up: it measures window setup and pipeline
|
||||
/// compilation, not a steady-state frame, and would dominate the graph.
|
||||
/// Returns `false` for that frame, so observers can skip it as well.
|
||||
pub(crate) fn record(&mut self, frame: Duration, work: FrameWork) -> bool {
|
||||
if !self.primed {
|
||||
self.primed = true;
|
||||
return false;
|
||||
}
|
||||
let frame_ms = frame.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;
|
||||
self.clock += frame.as_secs_f32();
|
||||
let sample: ProcSample = proc::sample();
|
||||
let cpu_ticks = match (sample.ticks, self.last_ticks) {
|
||||
(Some(now), Some(before)) => u32::try_from(now.saturating_sub(before)).unwrap_or(0),
|
||||
_ => 0,
|
||||
};
|
||||
self.last_ticks = sample.ticks.or(self.last_ticks);
|
||||
self.window.push_back(Sample {
|
||||
at: self.clock,
|
||||
frame_ms,
|
||||
physics_ms,
|
||||
render_ms,
|
||||
steps: work.steps,
|
||||
cpu_ticks,
|
||||
});
|
||||
self.trim();
|
||||
self.stats = self.aggregate(sample);
|
||||
self.history.push_back([frame_ms, physics_ms]);
|
||||
if self.history.len() > HISTORY {
|
||||
self.history.pop_front();
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The latest rolling values, as shown in the overlay.
|
||||
pub(crate) fn stats(&self) -> Stats {
|
||||
self.stats
|
||||
}
|
||||
|
||||
/// Drops samples that fell out of the statistics window.
|
||||
fn trim(&mut self) {
|
||||
while self.window.len() > 1 {
|
||||
let span = self
|
||||
.window
|
||||
.front()
|
||||
.map_or(0.0, |sample| self.clock - sample.at);
|
||||
if span <= WINDOW_SECONDS {
|
||||
break;
|
||||
}
|
||||
self.window.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds the window into one-shot averages and maxima.
|
||||
fn aggregate(&self, sample: ProcSample) -> Stats {
|
||||
let mut stats = Stats {
|
||||
load_1m: sample.load_1m,
|
||||
rss_mb: sample.rss_mb,
|
||||
rtf: self.rtf.unwrap_or(0.0),
|
||||
..Stats::default()
|
||||
};
|
||||
let Some(first) = self.window.front() else {
|
||||
return stats;
|
||||
};
|
||||
let span = (self.clock - first.at).max(0.0);
|
||||
let count = self.window.len().saturating_sub(1) as f32;
|
||||
let mut frame_sum = 0.0;
|
||||
let mut physics_sum = 0.0;
|
||||
let mut render_sum = 0.0;
|
||||
let mut steps = 0;
|
||||
let mut ticks = 0_u32;
|
||||
for sample in &self.window {
|
||||
frame_sum += sample.frame_ms;
|
||||
physics_sum += sample.physics_ms;
|
||||
render_sum += sample.render_ms;
|
||||
steps += sample.steps;
|
||||
ticks = ticks.saturating_add(sample.cpu_ticks);
|
||||
stats.frame_max_ms = stats.frame_max_ms.max(sample.frame_ms);
|
||||
stats.physics_max_ms = stats.physics_max_ms.max(sample.physics_ms);
|
||||
}
|
||||
let frames = self.window.len() as f32;
|
||||
if span > 0.0 {
|
||||
stats.fps = count / span;
|
||||
stats.tps = steps as f32 / span;
|
||||
stats.cpu_percent = ticks as f32 / span / TICKS_PER_SECOND * 100.0;
|
||||
}
|
||||
if frames > 0.0 {
|
||||
stats.frame_avg_ms = frame_sum / frames;
|
||||
stats.physics_avg_ms = physics_sum / frames;
|
||||
stats.render_avg_ms = render_sum / frames;
|
||||
}
|
||||
stats
|
||||
}
|
||||
}
|
||||
153
crates/app/src/runtime/metrics/panel.rs
Normal file
153
crates/app/src/runtime/metrics/panel.rs
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
//! Panel layout for the diagnostics overlay: one text line per metric and a
|
||||
//! scrolling frame-time graph.
|
||||
|
||||
use fabrilis_render::{Overlay, OverlayLine, OverlayRect, OverlayText};
|
||||
|
||||
use super::{HISTORY, Metrics};
|
||||
|
||||
const PANEL_X: f32 = 12.0;
|
||||
const PANEL_Y: f32 = 12.0;
|
||||
const PANEL_WIDTH: f32 = 300.0;
|
||||
const PADDING: f32 = 10.0;
|
||||
const FONT_SIZE: f32 = 14.0;
|
||||
const LABEL_SIZE: f32 = 11.0;
|
||||
const LINE_HEIGHT: f32 = 17.0;
|
||||
const GRAPH_WIDTH: f32 = 280.0;
|
||||
const GRAPH_HEIGHT: f32 = 90.0;
|
||||
const GRAPH_LABEL_SPACE: f32 = 14.0;
|
||||
const PANEL_COLOR: [f32; 4] = [0.03, 0.04, 0.05, 0.82];
|
||||
const GRAPH_COLOR: [f32; 4] = [0.0, 0.0, 0.0, 0.45];
|
||||
const TEXT_COLOR: [f32; 4] = [0.90, 0.93, 0.96, 1.0];
|
||||
const DIM_COLOR: [f32; 4] = [0.55, 0.60, 0.66, 1.0];
|
||||
const GRID_COLOR: [f32; 4] = [1.0, 1.0, 1.0, 0.14];
|
||||
const FRAME_COLOR: [f32; 4] = [0.35, 0.95, 0.55, 1.0];
|
||||
const FRAME_FILL: [f32; 4] = [0.35, 0.95, 0.55, 0.18];
|
||||
const PHYSICS_COLOR: [f32; 4] = [1.0, 0.70, 0.25, 1.0];
|
||||
|
||||
impl Metrics {
|
||||
/// Draws the diagnostics panel and its graph into `overlay`.
|
||||
pub(crate) fn draw_panel(&self, overlay: &mut Overlay) {
|
||||
let lines = self.lines();
|
||||
let graph_top = PANEL_Y + PADDING + LINE_HEIGHT * lines.len() as f32 + GRAPH_LABEL_SPACE;
|
||||
let height = graph_top - PANEL_Y + GRAPH_LABEL_SPACE + GRAPH_HEIGHT + PADDING;
|
||||
overlay.push_rect(OverlayRect::new(
|
||||
PANEL_X,
|
||||
PANEL_Y,
|
||||
PANEL_WIDTH,
|
||||
height,
|
||||
PANEL_COLOR,
|
||||
));
|
||||
let mut y = PANEL_Y + PADDING;
|
||||
for line in &lines {
|
||||
overlay.push_text(OverlayText::new(
|
||||
PANEL_X + PADDING,
|
||||
y,
|
||||
FONT_SIZE,
|
||||
TEXT_COLOR,
|
||||
line.as_str(),
|
||||
));
|
||||
y += LINE_HEIGHT;
|
||||
}
|
||||
self.draw_graph(overlay, [PANEL_X + PADDING, graph_top]);
|
||||
}
|
||||
|
||||
/// One text line per metric.
|
||||
fn lines(&self) -> Vec<String> {
|
||||
let stats = self.stats;
|
||||
vec![
|
||||
format!("FPS {:>6.1}", stats.fps),
|
||||
format!("TPS {:>6.1}", stats.tps),
|
||||
format!(
|
||||
"frame {:>6.2} avg {:>6.2} max",
|
||||
stats.frame_avg_ms, stats.frame_max_ms
|
||||
),
|
||||
format!(
|
||||
"phys {:>6.2} avg {:>6.2} max",
|
||||
stats.physics_avg_ms, stats.physics_max_ms
|
||||
),
|
||||
format!("render {:>6.2} avg", stats.render_avg_ms),
|
||||
format!("rtf {:>5.2}", stats.rtf),
|
||||
format!("cpu {:>5.1} %", stats.cpu_percent),
|
||||
format!("load {:>5.2}", stats.load_1m),
|
||||
format!("rss {:>6.1} MB", stats.rss_mb),
|
||||
]
|
||||
}
|
||||
|
||||
/// Frame and physics series with a shared auto-scaled axis.
|
||||
fn draw_graph(&self, overlay: &mut Overlay, origin: [f32; 2]) {
|
||||
let [x, y] = origin;
|
||||
let max = self
|
||||
.history
|
||||
.iter()
|
||||
.map(|point| point[0].max(point[1]))
|
||||
.fold(1.0_f32, f32::max);
|
||||
overlay.push_rect(OverlayRect::new(
|
||||
x,
|
||||
y,
|
||||
GRAPH_WIDTH,
|
||||
GRAPH_HEIGHT,
|
||||
GRAPH_COLOR,
|
||||
));
|
||||
overlay.push_text(OverlayText::new(
|
||||
x,
|
||||
y - GRAPH_LABEL_SPACE + 3.0,
|
||||
LABEL_SIZE,
|
||||
DIM_COLOR,
|
||||
format!("{max:.1} ms max"),
|
||||
));
|
||||
overlay.push_text(OverlayText::new(
|
||||
x + GRAPH_WIDTH - 30.0,
|
||||
y + GRAPH_HEIGHT - LABEL_SIZE - 2.0,
|
||||
LABEL_SIZE,
|
||||
DIM_COLOR,
|
||||
"0 ms",
|
||||
));
|
||||
for step in 0..=4 {
|
||||
let line_y = y + GRAPH_HEIGHT * step as f32 / 4.0;
|
||||
overlay.push_line(OverlayLine::new(
|
||||
[x, line_y],
|
||||
[x + GRAPH_WIDTH, line_y],
|
||||
1.0,
|
||||
GRID_COLOR,
|
||||
));
|
||||
}
|
||||
self.draw_series(overlay, origin, max);
|
||||
}
|
||||
|
||||
/// Area fill and polyline for both series, newest point on the right edge.
|
||||
fn draw_series(&self, overlay: &mut Overlay, origin: [f32; 2], max: f32) {
|
||||
let [x, y] = origin;
|
||||
let count = self.history.len();
|
||||
if count == 0 {
|
||||
return;
|
||||
}
|
||||
let step = GRAPH_WIDTH / (HISTORY - 1) as f32;
|
||||
let mut previous_frame: Option<[f32; 2]> = None;
|
||||
let mut previous_physics: Option<[f32; 2]> = None;
|
||||
for (index, point) in self.history.iter().enumerate() {
|
||||
let px = x + GRAPH_WIDTH - step * (count - 1 - index) as f32;
|
||||
let frame = y + GRAPH_HEIGHT - travel(point[0], max);
|
||||
let physics = y + GRAPH_HEIGHT - travel(point[1], max);
|
||||
overlay.push_rect(OverlayRect::new(
|
||||
px,
|
||||
frame,
|
||||
step.max(1.0),
|
||||
(y + GRAPH_HEIGHT - frame).max(0.0),
|
||||
FRAME_FILL,
|
||||
));
|
||||
if let Some(last) = previous_frame {
|
||||
overlay.push_line(OverlayLine::new(last, [px, frame], 1.5, FRAME_COLOR));
|
||||
}
|
||||
if let Some(last) = previous_physics {
|
||||
overlay.push_line(OverlayLine::new(last, [px, physics], 1.2, PHYSICS_COLOR));
|
||||
}
|
||||
previous_frame = Some([px, frame]);
|
||||
previous_physics = Some([px, physics]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A non-negative value scaled into graph pixels against the axis maximum.
|
||||
fn travel(value: f32, max: f32) -> f32 {
|
||||
(value / max).clamp(0.0, 1.0) * GRAPH_HEIGHT
|
||||
}
|
||||
63
crates/app/src/runtime/metrics/proc.rs
Normal file
63
crates/app/src/runtime/metrics/proc.rs
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
//! Process counters read from `/proc`, with neutral fallbacks elsewhere.
|
||||
//!
|
||||
//! Every parser is pure: it takes the text of a `/proc` file and returns
|
||||
//! `None` for malformed input instead of panicking.
|
||||
|
||||
/// One read of the process-wide counters.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default)]
|
||||
pub(crate) struct ProcSample {
|
||||
/// User plus system CPU time of the process, in clock ticks.
|
||||
pub(crate) ticks: Option<u64>,
|
||||
/// One-minute load average, or zero when unavailable.
|
||||
pub(crate) load_1m: f32,
|
||||
/// Resident set size in mebibytes, or zero when unavailable.
|
||||
pub(crate) rss_mb: f32,
|
||||
}
|
||||
|
||||
/// Reads the counters once; a missing `/proc` leaves the fields at zero.
|
||||
pub(crate) fn sample() -> ProcSample {
|
||||
ProcSample {
|
||||
ticks: read("/proc/self/stat").and_then(|text| parse_stat(&text)),
|
||||
load_1m: read("/proc/loadavg")
|
||||
.and_then(|text| parse_loadavg(&text))
|
||||
.unwrap_or(0.0),
|
||||
rss_mb: read("/proc/self/status")
|
||||
.and_then(|text| parse_rss_mb(&text))
|
||||
.unwrap_or(0.0),
|
||||
}
|
||||
}
|
||||
|
||||
fn read(path: &str) -> Option<String> {
|
||||
std::fs::read_to_string(path).ok()
|
||||
}
|
||||
|
||||
/// `utime + stime` from a `/proc/<pid>/stat` line.
|
||||
///
|
||||
/// The command name is in parentheses and may contain spaces, so parsing starts
|
||||
/// after the last closing parenthesis.
|
||||
pub(crate) fn parse_stat(text: &str) -> Option<u64> {
|
||||
let close = text.rfind(')')?;
|
||||
let rest = text.get(close + 1..)?;
|
||||
// `rest` starts at field 3 (state); utime and stime are fields 14 and 15.
|
||||
let mut fields = rest.split_whitespace();
|
||||
let utime = fields.nth(11)?;
|
||||
let stime = fields.next()?;
|
||||
let user = utime.parse::<u64>().ok()?;
|
||||
let system = stime.parse::<u64>().ok()?;
|
||||
Some(user.saturating_add(system))
|
||||
}
|
||||
|
||||
/// The one-minute load average from a `/proc/loadavg` line.
|
||||
pub(crate) fn parse_loadavg(text: &str) -> Option<f32> {
|
||||
let value = text.split_whitespace().next()?.parse::<f32>().ok()?;
|
||||
(value.is_finite() && value >= 0.0).then_some(value)
|
||||
}
|
||||
|
||||
/// `VmRSS` from a `/proc/<pid>/status` file, converted from kB to MiB.
|
||||
pub(crate) fn parse_rss_mb(text: &str) -> Option<f32> {
|
||||
let line = text
|
||||
.lines()
|
||||
.find(|line| line.trim_start().starts_with("VmRSS:"))?;
|
||||
let kilobytes = line.split_whitespace().nth(1)?.parse::<f32>().ok()?;
|
||||
(kilobytes.is_finite() && kilobytes >= 0.0).then_some(kilobytes / 1024.0)
|
||||
}
|
||||
247
crates/app/src/runtime/metrics/tests.rs
Normal file
247
crates/app/src/runtime/metrics/tests.rs
Normal file
|
|
@ -0,0 +1,247 @@
|
|||
//! Tests for the `/proc` parsers, the rolling metrics window and the CSV log.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use fabrilis_render::Overlay;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A temp directory that removes itself when the test ends.
|
||||
struct TempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempDir {
|
||||
fn new(name: &str) -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let id = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"fabrilis-metrics-{name}-{}-{id}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir_all(&path).expect("temp directory");
|
||||
Self { path }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
const STAT: &str = "1234 (a) b c) S 1 2 3 4 5 6 7 8 9 10 120 34 0 0 20 0 1 0 1000 0 0";
|
||||
|
||||
#[test]
|
||||
fn stat_ticks_sum_user_and_system_time() {
|
||||
assert_eq!(proc::parse_stat(STAT), Some(154));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stat_tolerates_parentheses_in_the_command() {
|
||||
assert_eq!(
|
||||
proc::parse_stat("9 (x)y) R 1 2 3 4 5 6 7 8 9 10 5 7 0"),
|
||||
Some(12)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_stat_returns_none() {
|
||||
assert_eq!(proc::parse_stat(""), None);
|
||||
assert_eq!(proc::parse_stat("1234 (bash"), None);
|
||||
assert_eq!(proc::parse_stat("1234 (bash) S 1 2 3"), None);
|
||||
assert_eq!(
|
||||
proc::parse_stat("1234 (bash) S a b c d e f g h i j x y"),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loadavg_reads_the_first_field() {
|
||||
assert_eq!(
|
||||
proc::parse_loadavg("0.52 0.48 0.45 2/512 12345"),
|
||||
Some(0.52)
|
||||
);
|
||||
assert_eq!(proc::parse_loadavg(""), None);
|
||||
assert_eq!(proc::parse_loadavg("not a number"), None);
|
||||
assert_eq!(proc::parse_loadavg("-1.0 0.0 0.0"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_reads_vmrss_in_mebibytes() {
|
||||
let text = "Name:\tcat\nState:\tR (running)\nVmRSS:\t 15360 kB\nThreads:\t4\n";
|
||||
assert_eq!(proc::parse_rss_mb(text), Some(15.0));
|
||||
assert_eq!(proc::parse_rss_mb("Name:\tcat\n"), None);
|
||||
assert_eq!(proc::parse_rss_mb("VmRSS:\tgarbage kB\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spike_becomes_the_window_maximum() {
|
||||
let mut metrics = Metrics::default();
|
||||
metrics.record(Duration::from_millis(500), FrameWork::default());
|
||||
metrics.record(
|
||||
Duration::from_millis(16),
|
||||
FrameWork {
|
||||
physics: Duration::from_millis(1),
|
||||
render: Duration::from_millis(2),
|
||||
steps: 16,
|
||||
},
|
||||
);
|
||||
metrics.record(
|
||||
Duration::from_millis(90),
|
||||
FrameWork {
|
||||
physics: Duration::from_millis(12),
|
||||
render: Duration::from_millis(2),
|
||||
steps: 18,
|
||||
},
|
||||
);
|
||||
let stats = metrics.stats;
|
||||
assert!(
|
||||
(stats.frame_max_ms - 90.0).abs() < 0.5,
|
||||
"frame max {}",
|
||||
stats.frame_max_ms
|
||||
);
|
||||
assert!(
|
||||
(stats.physics_max_ms - 12.0).abs() < 0.5,
|
||||
"physics max {}",
|
||||
stats.physics_max_ms
|
||||
);
|
||||
assert!(
|
||||
(stats.frame_avg_ms - 53.0).abs() < 0.5,
|
||||
"frame average {}",
|
||||
stats.frame_avg_ms
|
||||
);
|
||||
assert!(stats.tps > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_panel_draws_text_rectangles_and_lines() {
|
||||
let mut metrics = Metrics::default();
|
||||
for _ in 0..4 {
|
||||
metrics.record(Duration::from_millis(16), FrameWork::default());
|
||||
}
|
||||
let mut overlay = Overlay::new();
|
||||
metrics.draw_panel(&mut overlay);
|
||||
assert!(overlay.texts.len() >= 9, "one line per metric plus labels");
|
||||
assert!(!overlay.rects.is_empty(), "panel and graph background");
|
||||
assert!(!overlay.lines.is_empty(), "grid and series");
|
||||
assert!(
|
||||
overlay
|
||||
.texts
|
||||
.iter()
|
||||
.any(|text| text.text.starts_with("FPS")),
|
||||
"the panel starts with the frame rate"
|
||||
);
|
||||
assert!(
|
||||
overlay.texts.iter().any(|text| text.text.contains("max")),
|
||||
"the graph labels its maximum"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_graph_keeps_only_the_recent_frames() {
|
||||
let mut metrics = Metrics::default();
|
||||
for _ in 0..(HISTORY + 25) {
|
||||
metrics.record(Duration::from_millis(5), FrameWork::default());
|
||||
}
|
||||
assert_eq!(metrics.history.len(), HISTORY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_holds_about_one_second() {
|
||||
let mut metrics = Metrics::default();
|
||||
for _ in 0..200 {
|
||||
metrics.record(Duration::from_millis(10), FrameWork::default());
|
||||
}
|
||||
assert!(
|
||||
metrics.window.len() <= 101,
|
||||
"the window keeps {} samples",
|
||||
metrics.window.len()
|
||||
);
|
||||
assert!(metrics.window.len() > 10, "the window is not empty");
|
||||
}
|
||||
|
||||
fn sample_stats() -> Stats {
|
||||
Stats {
|
||||
fps: 60.0,
|
||||
tps: 999.5,
|
||||
frame_avg_ms: 16.25,
|
||||
frame_max_ms: 20.5,
|
||||
physics_avg_ms: 0.5,
|
||||
physics_max_ms: 1.25,
|
||||
render_avg_ms: 2.0,
|
||||
rtf: 1.0,
|
||||
cpu_percent: 12.5,
|
||||
load_1m: 0.75,
|
||||
rss_mb: 312.5,
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_row(stats: &Stats, frame: u64, spike: bool) -> Row<'_> {
|
||||
Row {
|
||||
unix_s: 1_700_000_000.125,
|
||||
t_s: 4.25,
|
||||
frame,
|
||||
stats,
|
||||
spike,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_csv_header_and_one_row_match_the_documented_columns() {
|
||||
let stats = sample_stats();
|
||||
let row = sample_row(&stats, 42, true);
|
||||
assert_eq!(
|
||||
csv::HEADER,
|
||||
"unix_s,t_s,frame,fps,tps,frame_ms,frame_max_ms,physics_ms,physics_max_ms,render_ms,rtf,cpu_pct,load1,rss_mb,spike"
|
||||
);
|
||||
assert_eq!(
|
||||
csv::format_row(&row),
|
||||
"1700000000.125,4.250,42,60.0,999.5,16.25,20.50,0.50,1.25,2.00,1.00,12.5,0.75,312.5,1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spike_needs_a_slow_frame_or_a_slow_step() {
|
||||
assert_eq!(spike_reason(20.0, 1.0), None);
|
||||
assert_eq!(spike_reason(20.01, 1.0), Some("frame"));
|
||||
assert_eq!(spike_reason(10.0, 1.01), Some("physics"));
|
||||
assert_eq!(spike_reason(30.0, 2.0), Some("frame+physics"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_csv_truncates_unless_append_is_set() {
|
||||
let dir = TempDir::new("csv");
|
||||
let path = dir.path.join("metrics.csv");
|
||||
let stats = sample_stats();
|
||||
{
|
||||
let mut log = CsvLog::open(&path, false).expect("create the CSV");
|
||||
log.record(&sample_row(&stats, 1, false))
|
||||
.expect("first row");
|
||||
log.flush().expect("flush");
|
||||
}
|
||||
{
|
||||
let mut log = CsvLog::open(&path, true).expect("append to the CSV");
|
||||
log.record(&sample_row(&stats, 2, true))
|
||||
.expect("second row");
|
||||
log.flush().expect("flush");
|
||||
}
|
||||
let text = std::fs::read_to_string(&path).expect("read the CSV");
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
assert_eq!(lines.len(), 3, "one header and two rows");
|
||||
assert_eq!(lines[0], csv::HEADER, "the header is written once");
|
||||
assert!(lines[1].starts_with("1700000000.125,4.250,1,"));
|
||||
assert!(lines[1].ends_with(",0"));
|
||||
assert!(lines[2].ends_with(",1"));
|
||||
{
|
||||
let mut log = CsvLog::open(&path, false).expect("truncate the CSV");
|
||||
log.record(&sample_row(&stats, 3, false))
|
||||
.expect("fresh row");
|
||||
log.flush().expect("flush");
|
||||
}
|
||||
let text = std::fs::read_to_string(&path).expect("read the CSV");
|
||||
assert_eq!(text.lines().count(), 2, "header and one fresh row");
|
||||
assert!(text.lines().nth(1).is_some_and(|line| line.contains(",3,")));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue