use bevy_ecs::system::Resource;
use bevy_log::warn;
use bevy_utils::{Duration, Instant, StableHashMap, Uuid};
use std::{borrow::Cow, collections::VecDeque};
use crate::MAX_DIAGNOSTIC_NAME_WIDTH;
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, PartialOrd, Ord)]
pub struct DiagnosticId(pub Uuid);
impl DiagnosticId {
pub const fn from_u128(value: u128) -> Self {
DiagnosticId(Uuid::from_u128(value))
}
}
impl Default for DiagnosticId {
fn default() -> Self {
DiagnosticId(Uuid::new_v4())
}
}
#[derive(Debug)]
pub struct DiagnosticMeasurement {
pub time: Instant,
pub value: f64,
}
#[derive(Debug)]
pub struct Diagnostic {
pub id: DiagnosticId,
pub name: Cow<'static, str>,
pub suffix: Cow<'static, str>,
history: VecDeque<DiagnosticMeasurement>,
sum: f64,
ema: f64,
ema_smoothing_factor: f64,
max_history_length: usize,
pub is_enabled: bool,
}
impl Diagnostic {
pub fn add_measurement(&mut self, value: f64) {
let time = Instant::now();
if let Some(previous) = self.measurement() {
let delta = (time - previous.time).as_secs_f64();
let alpha = (delta / self.ema_smoothing_factor).clamp(0.0, 1.0);
self.ema += alpha * (value - self.ema);
} else {
self.ema = value;
}
if self.max_history_length > 1 {
if self.history.len() == self.max_history_length {
if let Some(removed_diagnostic) = self.history.pop_front() {
self.sum -= removed_diagnostic.value;
}
}
self.sum += value;
} else {
self.history.clear();
self.sum = value;
}
self.history
.push_back(DiagnosticMeasurement { time, value });
}
pub fn new(
id: DiagnosticId,
name: impl Into<Cow<'static, str>>,
max_history_length: usize,
) -> Diagnostic {
let name = name.into();
if name.chars().count() > MAX_DIAGNOSTIC_NAME_WIDTH {
warn!(
"Diagnostic {:?} has name longer than {} characters, and so might overflow in the LogDiagnosticsPlugin\
Consider using a shorter name.",
name, MAX_DIAGNOSTIC_NAME_WIDTH
);
}
Diagnostic {
id,
name,
suffix: Cow::Borrowed(""),
history: VecDeque::with_capacity(max_history_length),
max_history_length,
sum: 0.0,
ema: 0.0,
ema_smoothing_factor: 2.0 / 21.0,
is_enabled: true,
}
}
#[must_use]
pub fn with_suffix(mut self, suffix: impl Into<Cow<'static, str>>) -> Self {
self.suffix = suffix.into();
self
}
#[must_use]
pub fn with_smoothing_factor(mut self, smoothing_factor: f64) -> Self {
self.ema_smoothing_factor = smoothing_factor;
self
}
#[inline]
pub fn measurement(&self) -> Option<&DiagnosticMeasurement> {
self.history.back()
}
pub fn value(&self) -> Option<f64> {
self.measurement().map(|measurement| measurement.value)
}
pub fn average(&self) -> Option<f64> {
if !self.history.is_empty() {
Some(self.sum / self.history.len() as f64)
} else {
None
}
}
pub fn smoothed(&self) -> Option<f64> {
if !self.history.is_empty() {
Some(self.ema)
} else {
None
}
}
pub fn history_len(&self) -> usize {
self.history.len()
}
pub fn duration(&self) -> Option<Duration> {
if self.history.len() < 2 {
return None;
}
if let Some(newest) = self.history.back() {
if let Some(oldest) = self.history.front() {
return Some(newest.time.duration_since(oldest.time));
}
}
None
}
pub fn get_max_history_length(&self) -> usize {
self.max_history_length
}
pub fn values(&self) -> impl Iterator<Item = &f64> {
self.history.iter().map(|x| &x.value)
}
pub fn measurements(&self) -> impl Iterator<Item = &DiagnosticMeasurement> {
self.history.iter()
}
pub fn clear_history(&mut self) {
self.history.clear();
}
}
#[derive(Debug, Default, Resource)]
pub struct Diagnostics {
diagnostics: StableHashMap<DiagnosticId, Diagnostic>,
}
impl Diagnostics {
pub fn add(&mut self, diagnostic: Diagnostic) {
self.diagnostics.insert(diagnostic.id, diagnostic);
}
pub fn get(&self, id: DiagnosticId) -> Option<&Diagnostic> {
self.diagnostics.get(&id)
}
pub fn get_mut(&mut self, id: DiagnosticId) -> Option<&mut Diagnostic> {
self.diagnostics.get_mut(&id)
}
pub fn get_measurement(&self, id: DiagnosticId) -> Option<&DiagnosticMeasurement> {
self.diagnostics
.get(&id)
.filter(|diagnostic| diagnostic.is_enabled)
.and_then(|diagnostic| diagnostic.measurement())
}
pub fn add_measurement<F>(&mut self, id: DiagnosticId, value: F)
where
F: FnOnce() -> f64,
{
if let Some(diagnostic) = self
.diagnostics
.get_mut(&id)
.filter(|diagnostic| diagnostic.is_enabled)
{
diagnostic.add_measurement(value());
}
}
pub fn iter(&self) -> impl Iterator<Item = &Diagnostic> {
self.diagnostics.values()
}
}