many_animated_sprites/
many_animated_sprites.rs

1//! Renders a lot of animated sprites to allow performance testing.
2//!
3//! This example sets up many animated sprites in different sizes, rotations, and scales in the world.
4//! It also moves the camera over them to see how well frustum culling works.
5
6use std::time::Duration;
7
8use bevy::{
9    diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin},
10    prelude::*,
11    window::{PresentMode, WindowResolution},
12    winit::WinitSettings,
13};
14
15use rand::Rng;
16
17const CAMERA_SPEED: f32 = 1000.0;
18
19fn main() {
20    App::new()
21        // Since this is also used as a benchmark, we want it to display performance data.
22        .add_plugins((
23            LogDiagnosticsPlugin::default(),
24            FrameTimeDiagnosticsPlugin::default(),
25            DefaultPlugins.set(WindowPlugin {
26                primary_window: Some(Window {
27                    present_mode: PresentMode::AutoNoVsync,
28                    resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0),
29                    ..default()
30                }),
31                ..default()
32            }),
33        ))
34        .insert_resource(WinitSettings::continuous())
35        .add_systems(Startup, setup)
36        .add_systems(
37            Update,
38            (
39                animate_sprite,
40                print_sprite_count,
41                move_camera.after(print_sprite_count),
42            ),
43        )
44        .run();
45}
46
47fn setup(
48    mut commands: Commands,
49    assets: Res<AssetServer>,
50    mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>,
51) {
52    warn!(include_str!("warning_string.txt"));
53
54    let mut rng = rand::rng();
55
56    let tile_size = Vec2::splat(64.0);
57    let map_size = Vec2::splat(320.0);
58
59    let half_x = (map_size.x / 2.0) as i32;
60    let half_y = (map_size.y / 2.0) as i32;
61
62    let texture_handle = assets.load("textures/rpg/chars/gabe/gabe-idle-run.png");
63    let texture_atlas = TextureAtlasLayout::from_grid(UVec2::splat(24), 7, 1, None, None);
64    let texture_atlas_handle = texture_atlases.add(texture_atlas);
65
66    // Spawns the camera
67
68    commands.spawn(Camera2d);
69
70    // Builds and spawns the sprites
71    for y in -half_y..half_y {
72        for x in -half_x..half_x {
73            let position = Vec2::new(x as f32, y as f32);
74            let translation = (position * tile_size).extend(rng.random::<f32>());
75            let rotation = Quat::from_rotation_z(rng.random::<f32>());
76            let scale = Vec3::splat(rng.random::<f32>() * 2.0);
77            let mut timer = Timer::from_seconds(0.1, TimerMode::Repeating);
78            timer.set_elapsed(Duration::from_secs_f32(rng.random::<f32>()));
79
80            commands.spawn((
81                Sprite {
82                    image: texture_handle.clone(),
83                    texture_atlas: Some(TextureAtlas::from(texture_atlas_handle.clone())),
84                    custom_size: Some(tile_size),
85                    ..default()
86                },
87                Transform {
88                    translation,
89                    rotation,
90                    scale,
91                },
92                AnimationTimer(timer),
93            ));
94        }
95    }
96}
97
98// System for rotating and translating the camera
99fn move_camera(time: Res<Time>, mut camera_transform: Single<&mut Transform, With<Camera>>) {
100    camera_transform.rotate(Quat::from_rotation_z(time.delta_secs() * 0.5));
101    **camera_transform = **camera_transform
102        * Transform::from_translation(Vec3::X * CAMERA_SPEED * time.delta_secs());
103}
104
105#[derive(Component, Deref, DerefMut)]
106struct AnimationTimer(Timer);
107
108fn animate_sprite(
109    time: Res<Time>,
110    texture_atlases: Res<Assets<TextureAtlasLayout>>,
111    mut query: Query<(&mut AnimationTimer, &mut Sprite)>,
112) {
113    for (mut timer, mut sprite) in query.iter_mut() {
114        timer.tick(time.delta());
115        if timer.just_finished() {
116            let Some(atlas) = &mut sprite.texture_atlas else {
117                continue;
118            };
119            let texture_atlas = texture_atlases.get(&atlas.layout).unwrap();
120            atlas.index = (atlas.index + 1) % texture_atlas.textures.len();
121        }
122    }
123}
124
125#[derive(Deref, DerefMut)]
126struct PrintingTimer(Timer);
127
128impl Default for PrintingTimer {
129    fn default() -> Self {
130        Self(Timer::from_seconds(1.0, TimerMode::Repeating))
131    }
132}
133
134// System for printing the number of sprites on every tick of the timer
135fn print_sprite_count(time: Res<Time>, mut timer: Local<PrintingTimer>, sprites: Query<&Sprite>) {
136    timer.tick(time.delta());
137
138    if timer.just_finished() {
139        info!("Sprites: {}", sprites.iter().count());
140    }
141}