bevy_sprite 0.18.1

Provides sprite functionality for Bevy Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
use crate::{Anchor, Sprite};
use bevy_asset::Assets;
use bevy_camera::primitives::Aabb;
use bevy_camera::visibility::{
    self, NoFrustumCulling, RenderLayers, Visibility, VisibilityClass, VisibleEntities,
};
use bevy_camera::Camera;
use bevy_color::Color;
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::entity::EntityHashSet;
use bevy_ecs::{
    change_detection::{DetectChanges, Ref},
    component::Component,
    entity::Entity,
    prelude::ReflectComponent,
    query::{Changed, Without},
    system::{Commands, Local, Query, Res, ResMut},
};
use bevy_image::prelude::*;
use bevy_math::{FloatOrd, Vec2, Vec3};
use bevy_reflect::{prelude::ReflectDefault, Reflect};
use bevy_text::{
    ComputedTextBlock, CosmicFontSystem, Font, FontAtlasSet, FontHinting, LineBreak, LineHeight,
    SwashCache, TextBounds, TextColor, TextError, TextFont, TextLayout, TextLayoutInfo,
    TextPipeline, TextReader, TextRoot, TextSpanAccess, TextWriter,
};
use bevy_transform::components::Transform;
use core::any::TypeId;

/// The top-level 2D text component.
///
/// Adding `Text2d` to an entity will pull in required components for setting up 2d text.
/// [Example usage.](https://github.com/bevyengine/bevy/blob/latest/examples/2d/text2d.rs)
///
/// The string in this component is the first 'text span' in a hierarchy of text spans that are collected into
/// a [`ComputedTextBlock`]. See `TextSpan` for the component used by children of entities with [`Text2d`].
///
/// With `Text2d` the `justify` field of [`TextLayout`] only affects the internal alignment of a block of text and not its
/// relative position, which is controlled by the [`Anchor`] component.
/// This means that for a block of text consisting of only one line that doesn't wrap, the `justify` field will have no effect.
///
///
/// ```
/// # use bevy_asset::Handle;
/// # use bevy_color::Color;
/// # use bevy_color::palettes::basic::BLUE;
/// # use bevy_ecs::world::World;
/// # use bevy_text::{Font, Justify, TextLayout, TextFont, TextColor, TextSpan};
/// # use bevy_sprite::Text2d;
/// #
/// # let font_handle: Handle<Font> = Default::default();
/// # let mut world = World::default();
/// #
/// // Basic usage.
/// world.spawn(Text2d::new("hello world!"));
///
/// // With non-default style.
/// world.spawn((
///     Text2d::new("hello world!"),
///     TextFont {
///         font: font_handle.clone().into(),
///         font_size: 60.0,
///         ..Default::default()
///     },
///     TextColor(BLUE.into()),
/// ));
///
/// // With text justification.
/// world.spawn((
///     Text2d::new("hello world\nand bevy!"),
///     TextLayout::new_with_justify(Justify::Center)
/// ));
///
/// // With spans
/// world.spawn(Text2d::new("hello ")).with_children(|parent| {
///     parent.spawn(TextSpan::new("world"));
///     parent.spawn((TextSpan::new("!"), TextColor(BLUE.into())));
/// });
/// ```
#[derive(Component, Clone, Debug, Default, Deref, DerefMut, Reflect)]
#[reflect(Component, Default, Debug, Clone)]
#[require(
    TextLayout,
    TextFont,
    TextColor,
    LineHeight,
    TextBounds,
    Anchor,
    Visibility,
    VisibilityClass,
    Transform,
    // Disable hinting as `Text2d` text is not always pixel-aligned
    FontHinting::Disabled
)]
#[component(on_add = visibility::add_visibility_class::<Sprite>)]
pub struct Text2d(pub String);

impl Text2d {
    /// Makes a new 2d text component.
    pub fn new(text: impl Into<String>) -> Self {
        Self(text.into())
    }
}

impl TextRoot for Text2d {}

impl TextSpanAccess for Text2d {
    fn read_span(&self) -> &str {
        self.as_str()
    }
    fn write_span(&mut self) -> &mut String {
        &mut *self
    }
}

impl From<&str> for Text2d {
    fn from(value: &str) -> Self {
        Self(String::from(value))
    }
}

impl From<String> for Text2d {
    fn from(value: String) -> Self {
        Self(value)
    }
}

/// 2d alias for [`TextReader`].
pub type Text2dReader<'w, 's> = TextReader<'w, 's, Text2d>;

/// 2d alias for [`TextWriter`].
pub type Text2dWriter<'w, 's> = TextWriter<'w, 's, Text2d>;

/// Adds a shadow behind `Text2d` text
///
/// Use `TextShadow` for text drawn with `bevy_ui`
#[derive(Component, Copy, Clone, Debug, PartialEq, Reflect)]
#[reflect(Component, Default, Debug, Clone, PartialEq)]
pub struct Text2dShadow {
    /// Shadow displacement
    /// With a value of zero the shadow will be hidden directly behind the text
    pub offset: Vec2,
    /// Color of the shadow
    pub color: Color,
}

impl Default for Text2dShadow {
    fn default() -> Self {
        Self {
            offset: Vec2::new(4., -4.),
            color: Color::BLACK,
        }
    }
}

/// Updates the layout and size information whenever the text or style is changed.
/// This information is computed by the [`TextPipeline`] on insertion, then stored.
///
/// ## World Resources
///
/// [`ResMut<Assets<Image>>`](Assets<Image>) -- This system only adds new [`Image`] assets.
/// It does not modify or observe existing ones.
pub fn update_text2d_layout(
    mut target_scale_factors: Local<Vec<(f32, RenderLayers)>>,
    // Text2d entities from the previous frame which need to be reprocessed, usually because the font hadn't loaded yet.
    mut reprocess_queue: Local<EntityHashSet>,
    mut textures: ResMut<Assets<Image>>,
    fonts: Res<Assets<Font>>,
    camera_query: Query<(&Camera, &VisibleEntities, Option<&RenderLayers>)>,
    mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>,
    mut font_atlas_set: ResMut<FontAtlasSet>,
    mut text_pipeline: ResMut<TextPipeline>,
    mut text_query: Query<(
        Entity,
        Option<&RenderLayers>,
        Ref<TextLayout>,
        Ref<TextBounds>,
        &mut TextLayoutInfo,
        &mut ComputedTextBlock,
        Ref<FontHinting>,
    )>,
    text_font_query: Query<&TextFont>,
    mut text_reader: Text2dReader,
    mut font_system: ResMut<CosmicFontSystem>,
    mut swash_cache: ResMut<SwashCache>,
) {
    target_scale_factors.clear();
    target_scale_factors.extend(
        camera_query
            .iter()
            .filter(|(_, visible_entities, _)| {
                !visible_entities.get(TypeId::of::<Sprite>()).is_empty()
            })
            .filter_map(|(camera, _, maybe_camera_mask)| {
                camera.target_scaling_factor().map(|scale_factor| {
                    (scale_factor, maybe_camera_mask.cloned().unwrap_or_default())
                })
            }),
    );

    let mut previous_scale_factor = 0.;
    let mut previous_mask = &RenderLayers::none();

    for (entity, maybe_entity_mask, block, bounds, mut text_layout_info, mut computed, hinting) in
        &mut text_query
    {
        let entity_mask = maybe_entity_mask.unwrap_or_default();

        let scale_factor = if entity_mask == previous_mask && 0. < previous_scale_factor {
            previous_scale_factor
        } else {
            // `Text2d` only supports generating a single text layout per Text2d entity. If a `Text2d` entity has multiple
            // render targets with different scale factors, then we use the maximum of the scale factors.
            let Some((scale_factor, mask)) = target_scale_factors
                .iter()
                .filter(|(_, camera_mask)| camera_mask.intersects(entity_mask))
                .max_by_key(|(scale_factor, _)| FloatOrd(*scale_factor))
            else {
                continue;
            };
            previous_scale_factor = *scale_factor;
            previous_mask = mask;
            *scale_factor
        };

        let text_changed = scale_factor != text_layout_info.scale_factor
            || block.is_changed()
            || hinting.is_changed()
            || computed.needs_rerender()
            || (!reprocess_queue.is_empty() && reprocess_queue.remove(&entity));

        if !(text_changed || bounds.is_changed()) {
            continue;
        }

        let text_bounds = TextBounds {
            width: if block.linebreak == LineBreak::NoWrap {
                None
            } else {
                bounds.width.map(|width| width * scale_factor)
            },
            height: bounds.height.map(|height| height * scale_factor),
        };

        if text_changed {
            match text_pipeline.update_buffer(
                &fonts,
                text_reader.iter(entity),
                block.linebreak,
                block.justify,
                text_bounds,
                scale_factor as f64,
                &mut computed,
                &mut font_system,
                *hinting,
            ) {
                Err(TextError::NoSuchFont) => {
                    // There was an error processing the text layout.
                    // Add this entity to the queue and reprocess it in the following frame
                    reprocess_queue.insert(entity);
                    continue;
                }
                Err(
                    e @ (TextError::FailedToAddGlyph(_)
                    | TextError::FailedToGetGlyphImage(_)
                    | TextError::MissingAtlasLayout
                    | TextError::MissingAtlasTexture
                    | TextError::InconsistentAtlasState),
                ) => {
                    panic!("Fatal error when processing text: {e}.");
                }
                Ok(()) => {}
            }
        }

        match text_pipeline.update_text_layout_info(
            &mut text_layout_info,
            text_font_query,
            scale_factor as f64,
            &mut font_atlas_set,
            &mut texture_atlases,
            &mut textures,
            &mut computed,
            &mut font_system,
            &mut swash_cache,
            text_bounds,
            block.justify,
        ) {
            Err(TextError::NoSuchFont) => {
                // There was an error processing the text layout.
                // Add this entity to the queue and reprocess it in the following frame.
                reprocess_queue.insert(entity);
                continue;
            }
            Err(
                e @ (TextError::FailedToAddGlyph(_)
                | TextError::FailedToGetGlyphImage(_)
                | TextError::MissingAtlasLayout
                | TextError::MissingAtlasTexture
                | TextError::InconsistentAtlasState),
            ) => {
                panic!("Fatal error when processing text: {e}.");
            }
            Ok(()) => {
                text_layout_info.scale_factor = scale_factor;
                text_layout_info.size *= scale_factor.recip();
            }
        }
    }
}

/// System calculating and inserting an [`Aabb`] component to entities with some
/// [`TextLayoutInfo`] and [`Anchor`] components, and without a [`NoFrustumCulling`] component.
///
/// Used in system set [`VisibilitySystems::CalculateBounds`](bevy_camera::visibility::VisibilitySystems::CalculateBounds).
pub fn calculate_bounds_text2d(
    mut commands: Commands,
    mut text_to_update_aabb: Query<
        (
            Entity,
            &TextLayoutInfo,
            &Anchor,
            &TextBounds,
            Option<&mut Aabb>,
        ),
        (Changed<TextLayoutInfo>, Without<NoFrustumCulling>),
    >,
) {
    for (entity, layout_info, anchor, text_bounds, aabb) in &mut text_to_update_aabb {
        let size = Vec2::new(
            text_bounds.width.unwrap_or(layout_info.size.x),
            text_bounds.height.unwrap_or(layout_info.size.y),
        );

        let x1 = (Anchor::TOP_LEFT.0.x - anchor.as_vec().x) * size.x;
        let x2 = (Anchor::TOP_LEFT.0.x - anchor.as_vec().x + 1.) * size.x;
        let y1 = (Anchor::TOP_LEFT.0.y - anchor.as_vec().y - 1.) * size.y;
        let y2 = (Anchor::TOP_LEFT.0.y - anchor.as_vec().y) * size.y;
        let new_aabb = Aabb::from_min_max(Vec3::new(x1, y1, 0.), Vec3::new(x2, y2, 0.));

        if let Some(mut aabb) = aabb {
            *aabb = new_aabb;
        } else {
            commands.entity(entity).try_insert(new_aabb);
        }
    }
}

#[cfg(test)]
mod tests {

    use bevy_app::{App, Update};
    use bevy_asset::{load_internal_binary_asset, Handle};
    use bevy_camera::{ComputedCameraValues, RenderTargetInfo};
    use bevy_ecs::schedule::IntoScheduleConfigs;
    use bevy_math::UVec2;
    use bevy_text::{detect_text_needs_rerender, TextIterScratch};

    use super::*;

    const FIRST_TEXT: &str = "Sample text.";
    const SECOND_TEXT: &str = "Another, longer sample text.";

    fn setup() -> (App, Entity) {
        let mut app = App::new();
        app.init_resource::<Assets<Font>>()
            .init_resource::<Assets<Image>>()
            .init_resource::<Assets<TextureAtlasLayout>>()
            .init_resource::<FontAtlasSet>()
            .init_resource::<TextPipeline>()
            .init_resource::<CosmicFontSystem>()
            .init_resource::<SwashCache>()
            .init_resource::<TextIterScratch>()
            .add_systems(
                Update,
                (
                    detect_text_needs_rerender::<Text2d>,
                    update_text2d_layout,
                    calculate_bounds_text2d,
                )
                    .chain(),
            );

        let mut visible_entities = VisibleEntities::default();
        visible_entities.push(Entity::PLACEHOLDER, TypeId::of::<Sprite>());

        app.world_mut().spawn((
            Camera {
                computed: ComputedCameraValues {
                    target_info: Some(RenderTargetInfo {
                        physical_size: UVec2::splat(1000),
                        scale_factor: 1.,
                    }),
                    ..Default::default()
                },
                ..Default::default()
            },
            visible_entities,
        ));

        // A font is needed to ensure the text is laid out with an actual size.
        load_internal_binary_asset!(
            app,
            Handle::default(),
            "../../bevy_text/src/FiraMono-subset.ttf",
            |bytes: &[u8], _path: String| { Font::try_from_bytes(bytes.to_vec()).unwrap() }
        );

        let entity = app.world_mut().spawn(Text2d::new(FIRST_TEXT)).id();

        (app, entity)
    }

    #[test]
    fn calculate_bounds_text2d_create_aabb() {
        let (mut app, entity) = setup();

        assert!(!app
            .world()
            .get_entity(entity)
            .expect("Could not find entity")
            .contains::<Aabb>());

        // Creates the AABB after text layouting.
        app.update();

        let aabb = app
            .world()
            .get_entity(entity)
            .expect("Could not find entity")
            .get::<Aabb>()
            .expect("Text should have an AABB");

        // Text2D AABB does not have a depth.
        assert_eq!(aabb.center.z, 0.0);
        assert_eq!(aabb.half_extents.z, 0.0);

        // AABB has an actual size.
        assert!(aabb.half_extents.x > 0.0 && aabb.half_extents.y > 0.0);
    }

    #[test]
    fn calculate_bounds_text2d_update_aabb() {
        let (mut app, entity) = setup();

        // Creates the initial AABB after text layouting.
        app.update();

        let first_aabb = *app
            .world()
            .get_entity(entity)
            .expect("Could not find entity")
            .get::<Aabb>()
            .expect("Could not find initial AABB");

        let mut entity_ref = app
            .world_mut()
            .get_entity_mut(entity)
            .expect("Could not find entity");
        *entity_ref
            .get_mut::<Text2d>()
            .expect("Missing Text2d on entity") = Text2d::new(SECOND_TEXT);

        // Recomputes the AABB.
        app.update();

        let second_aabb = *app
            .world()
            .get_entity(entity)
            .expect("Could not find entity")
            .get::<Aabb>()
            .expect("Could not find second AABB");

        // Check that the height is the same, but the width is greater.
        approx::assert_abs_diff_eq!(first_aabb.half_extents.y, second_aabb.half_extents.y);
        assert!(FIRST_TEXT.len() < SECOND_TEXT.len());
        assert!(first_aabb.half_extents.x < second_aabb.half_extents.x);
    }
}