Skip to main content

many_text2d/
many_text2d.rs

1//! Renders a lot of `Text2d`s
2
3use std::ops::RangeInclusive;
4
5use bevy::{
6    camera::visibility::NoFrustumCulling,
7    diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin},
8    prelude::*,
9    text::FontAtlasSet,
10    window::{PresentMode, WindowResolution},
11    winit::WinitSettings,
12};
13
14use argh::FromArgs;
15use chacha20::ChaCha8Rng;
16use rand::{
17    seq::{IndexedRandom, IteratorRandom},
18    RngExt, SeedableRng,
19};
20
21const CAMERA_SPEED: f32 = 1000.0;
22
23// Some code points for valid glyphs in `FiraSans-Bold.ttf`
24const CODE_POINT_RANGES: [RangeInclusive<u32>; 5] = [
25    0x20..=0x7e,
26    0xa0..=0x17e,
27    0x180..=0x2b2,
28    0x3f0..=0x479,
29    0x48a..=0x52f,
30];
31
32#[derive(FromArgs, Resource)]
33/// `many_text2d` stress test
34struct Args {
35    /// whether to use many different glyphs to increase the amount of font atlas textures used.
36    #[argh(switch)]
37    many_glyphs: bool,
38
39    /// whether to use many different font sizes to increase the amount of font atlas textures used.
40    #[argh(switch)]
41    many_font_sizes: bool,
42
43    /// whether to force the text to recompute every frame by triggering change detection.
44    #[argh(switch)]
45    recompute: bool,
46
47    /// whether to enable TrueType hinting.
48    #[argh(switch)]
49    hinting: bool,
50
51    /// whether to disable all frustum culling.
52    #[argh(switch)]
53    no_frustum_culling: bool,
54
55    /// whether the text should use `Justify::Center`.
56    #[argh(switch)]
57    center: bool,
58}
59
60#[derive(Resource)]
61struct FontHandle(Handle<Font>);
62impl FromWorld for FontHandle {
63    fn from_world(world: &mut World) -> Self {
64        Self(world.load_asset("fonts/FiraSans-Bold.ttf"))
65    }
66}
67
68fn main() {
69    // `from_env` panics on the web
70    #[cfg(not(target_arch = "wasm32"))]
71    let args: Args = argh::from_env();
72    #[cfg(target_arch = "wasm32")]
73    let args = Args::from_args(&[], &[]).unwrap();
74
75    let mut app = App::new();
76
77    app.add_plugins((
78        FrameTimeDiagnosticsPlugin::default(),
79        LogDiagnosticsPlugin::default(),
80        DefaultPlugins.set(WindowPlugin {
81            primary_window: Some(Window {
82                present_mode: PresentMode::AutoNoVsync,
83                resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0),
84                ..default()
85            }),
86            ..default()
87        }),
88    ))
89    .insert_resource(WinitSettings::continuous())
90    .init_resource::<FontHandle>()
91    .add_systems(Startup, setup)
92    .add_systems(Update, (move_camera, print_counts));
93
94    if args.recompute {
95        app.add_systems(Update, recompute);
96    }
97
98    app.insert_resource(args).run();
99}
100
101#[derive(Deref, DerefMut)]
102struct PrintingTimer(Timer);
103
104impl Default for PrintingTimer {
105    fn default() -> Self {
106        Self(Timer::from_seconds(1.0, TimerMode::Repeating))
107    }
108}
109
110fn setup(mut commands: Commands, font: Res<FontHandle>, args: Res<Args>) {
111    warn!(include_str!("warning_string.txt"));
112
113    let mut rng = ChaCha8Rng::seed_from_u64(42);
114
115    let tile_size = Vec2::splat(64.0);
116    let map_size = Vec2::splat(640.0);
117
118    let half_x = (map_size.x / 4.0) as i32;
119    let half_y = (map_size.y / 4.0) as i32;
120
121    // Spawns the camera
122
123    commands.spawn(Camera2d);
124
125    // Builds and spawns the `Text2d`s, distributing them in a way that ensures a
126    // good distribution of on-screen and off-screen entities.
127    let hinting = if args.hinting {
128        FontHinting::Enabled
129    } else {
130        FontHinting::Disabled
131    };
132    let mut text2ds = vec![];
133    for y in -half_y..half_y {
134        for x in -half_x..half_x {
135            let position = Vec2::new(x as f32, y as f32);
136            let translation = (position * tile_size).extend(rng.random::<f32>());
137            let rotation = Quat::from_rotation_z(rng.random::<f32>());
138            let scale = Vec3::splat(rng.random::<f32>() * 2.0);
139            let color = Hsla::hsl(rng.random_range(0.0..360.0), 0.8, 0.8);
140
141            text2ds.push((
142                Text2d(random_text(&mut rng, &args)),
143                random_text_font(&mut rng, &args, font.0.clone()),
144                TextColor(color.into()),
145                TextLayout::justify(if args.center {
146                    Justify::Center
147                } else {
148                    Justify::Left
149                }),
150                hinting,
151                Transform {
152                    translation,
153                    rotation,
154                    scale,
155                },
156            ));
157        }
158    }
159
160    if args.no_frustum_culling {
161        let bundles = text2ds.into_iter().map(|bundle| (bundle, NoFrustumCulling));
162        commands.spawn_batch(bundles);
163    } else {
164        commands.spawn_batch(text2ds);
165    }
166}
167
168// System for rotating and translating the camera
169fn move_camera(time: Res<Time>, mut camera_query: Query<&mut Transform, With<Camera>>) {
170    let Ok(mut camera_transform) = camera_query.single_mut() else {
171        return;
172    };
173    camera_transform.rotate_z(time.delta_secs() * 0.5);
174    *camera_transform =
175        *camera_transform * Transform::from_translation(Vec3::X * CAMERA_SPEED * time.delta_secs());
176}
177
178// System for printing the number of texts on every tick of the timer
179fn print_counts(
180    time: Res<Time>,
181    mut timer: Local<PrintingTimer>,
182    texts: Query<&ViewVisibility, With<Text2d>>,
183    font_atlas_set: Res<FontAtlasSet>,
184    images: Res<Assets<Image>>,
185) {
186    timer.tick(time.delta());
187    if !timer.just_finished() {
188        return;
189    }
190
191    let num_atlases = font_atlas_set
192        .iter()
193        // Removed this filter for now as the keys no longer include the AssetIds
194        //        .filter(|(key, _)| key.0 == font_id)
195        .map(|(_, atlases)| atlases.len())
196        .sum::<usize>();
197
198    let visible_texts = texts.iter().filter(|visibility| visibility.get()).count();
199
200    info!(
201        "Texts: {} Visible: {} Atlases: {} Bytes: {}",
202        texts.iter().count(),
203        visible_texts,
204        num_atlases,
205        font_atlas_set.total_bytes(images.as_ref())
206    );
207}
208
209fn random_text_font(rng: &mut ChaCha8Rng, args: &Args, font: Handle<Font>) -> TextFont {
210    let font_size = FontSize::Px(if args.many_font_sizes {
211        *[10.0, 20.0, 30.0, 40.0, 50.0, 60.0].choose(rng).unwrap()
212    } else {
213        60.0
214    });
215
216    TextFont {
217        font_size,
218        font: font.into(),
219        ..default()
220    }
221}
222
223fn random_text(rng: &mut ChaCha8Rng, args: &Args) -> String {
224    if !args.many_glyphs {
225        return "Bevy".to_string();
226    }
227
228    CODE_POINT_RANGES
229        .choose(rng)
230        .unwrap()
231        .clone()
232        .sample(rng, 4)
233        .into_iter()
234        .map(|cp| char::from_u32(cp).unwrap())
235        .collect::<String>()
236}
237
238fn recompute(mut query: Query<&mut Text2d>) {
239    for mut text2d in &mut query {
240        text2d.set_changed();
241    }
242}