bevy_diagnostic/
frame_time_diagnostics_plugin.rs1use crate::{
2 Diagnostic, DiagnosticPath, Diagnostics, FrameCount, RegisterDiagnostic,
3 DEFAULT_MAX_HISTORY_LENGTH,
4};
5use bevy_app::prelude::*;
6use bevy_ecs::prelude::*;
7use bevy_time::{Real, Time};
8
9pub struct FrameTimeDiagnosticsPlugin {
15 pub max_history_length: usize,
17 pub smoothing_factor: f64,
19}
20
21impl Default for FrameTimeDiagnosticsPlugin {
22 fn default() -> Self {
23 Self::new(DEFAULT_MAX_HISTORY_LENGTH)
24 }
25}
26
27impl FrameTimeDiagnosticsPlugin {
28 pub fn new(max_history_length: usize) -> Self {
31 Self {
32 max_history_length,
33 smoothing_factor: 2.0 / (max_history_length as f64 + 1.0),
34 }
35 }
36}
37
38impl Plugin for FrameTimeDiagnosticsPlugin {
39 fn build(&self, app: &mut App) {
40 app.register_diagnostic(
41 Diagnostic::new(Self::FRAME_TIME)
42 .with_suffix("ms")
43 .with_max_history_length(self.max_history_length)
44 .with_smoothing_factor(self.smoothing_factor),
45 )
46 .register_diagnostic(
47 Diagnostic::new(Self::FPS)
48 .with_max_history_length(self.max_history_length)
49 .with_smoothing_factor(self.smoothing_factor),
50 )
51 .register_diagnostic(
54 Diagnostic::new(Self::FRAME_COUNT)
55 .with_smoothing_factor(0.0)
56 .with_max_history_length(0),
57 )
58 .add_systems(Update, Self::diagnostic_system);
59 }
60}
61
62impl FrameTimeDiagnosticsPlugin {
63 pub const FPS: DiagnosticPath = DiagnosticPath::const_new("fps");
65
66 pub const FRAME_COUNT: DiagnosticPath = DiagnosticPath::const_new("frame_count");
68
69 pub const FRAME_TIME: DiagnosticPath = DiagnosticPath::const_new("frame_time");
71
72 pub fn diagnostic_system(
74 mut diagnostics: Diagnostics,
75 time: Res<Time<Real>>,
76 frame_count: Res<FrameCount>,
77 ) {
78 diagnostics.add_measurement(&Self::FRAME_COUNT, || frame_count.0 as f64);
79
80 let delta_seconds = time.delta_secs_f64();
81 if delta_seconds == 0.0 {
82 return;
83 }
84
85 diagnostics.add_measurement(&Self::FRAME_TIME, || delta_seconds * 1000.0);
86
87 diagnostics.add_measurement(&Self::FPS, || 1.0 / delta_seconds);
88 }
89}