docs/bevy/examples/dev_tools/fps_overlay.rs 3.4 K · 103 lines · raw · history

1 //! Showcase how to use and configure FPS overlay.
2
3 use bevy::{
4 dev_tools::fps_overlay::{FpsOverlayConfig, FpsOverlayPlugin, FrameTimeGraphConfig},
5 prelude::*,
6 text::FontSmoothing,
7 };
8
9 struct OverlayColor;
10
11 impl OverlayColor {
12 const RED: Color = Color::srgb(1.0, 0.0, 0.0);
13 const GREEN: Color = Color::srgb(0.0, 1.0, 0.0);
14 }
15
16 fn main() {
17 App::new()
18 .add_plugins((
19 DefaultPlugins,
20 FpsOverlayPlugin {
21 config: FpsOverlayConfig {
22 text_config: TextFont {
23 // Here we define size of our overlay
24 font_size: FontSize::Px(42.0),
25 // If we want, we can use a custom font
26 font: default(),
27 // We could also disable font smoothing,
28 font_smoothing: FontSmoothing::default(),
29 ..default()
30 },
31 // We can also change color of the overlay
32 text_color: OverlayColor::GREEN,
33 // We can also set the refresh interval for the FPS counter
34 refresh_interval: core::time::Duration::from_millis(100),
35 enabled: true,
36 frame_time_graph_config: FrameTimeGraphConfig {
37 enabled: true,
38 // The minimum acceptable fps
39 min_fps: 30.0,
40 // The target fps
41 target_fps: 144.0,
42 },
43 },
44 },
45 ))
46 .add_systems(Startup, setup)
47 .add_systems(Update, customize_config)
48 .run();
49 }
50
51 fn setup(mut commands: Commands) {
52 // We need to spawn a camera (2d or 3d) to see the overlay
53 commands.spawn(Camera2d);
54
55 // Instruction text
56
57 commands.spawn((
58 Text::new(concat!(
59 "Press 1 to toggle the overlay color.\n",
60 "Press 2 to decrease the overlay size.\n",
61 "Press 3 to increase the overlay size.\n",
62 "Press 4 to toggle the text visibility.\n",
63 "Press 5 to toggle the frame time graph."
64 )),
65 Node {
66 position_type: PositionType::Absolute,
67 bottom: px(12),
68 left: px(12),
69 ..default()
70 },
71 ));
72 }
73
74 fn customize_config(input: Res<ButtonInput<KeyCode>>, mut overlay: ResMut<FpsOverlayConfig>) {
75 if input.just_pressed(KeyCode::Digit1) {
76 // Changing resource will affect overlay
77 if overlay.text_color == OverlayColor::GREEN {
78 overlay.text_color = OverlayColor::RED;
79 } else {
80 overlay.text_color = OverlayColor::GREEN;
81 }
82 }
83
84 // The font size only adjustable when using `Px` units
85 if let FontSize::Px(mut px_font_size) = overlay.text_config.font_size {
86 if input.just_pressed(KeyCode::Digit2) {
87 px_font_size = (px_font_size - 2.).max(2.);
88 }
89 if input.just_pressed(KeyCode::Digit3) {
90 px_font_size += 2.;
91 }
92 if FontSize::Px(px_font_size) != overlay.text_config.font_size {
93 overlay.text_config.font_size = FontSize::Px(px_font_size);
94 }
95 }
96
97 if input.just_pressed(KeyCode::Digit4) {
98 overlay.enabled = !overlay.enabled;
99 }
100 if input.just_released(KeyCode::Digit5) {
101 overlay.frame_time_graph_config.enabled = !overlay.frame_time_graph_config.enabled;
102 }
103 }