use crate::{
BreakLineOn, Font, FontAtlasSets, PositionedGlyph, Text, TextError, TextLayoutInfo,
TextPipeline, TextSettings, YAxisOrientation,
};
use bevy_asset::Assets;
use bevy_color::LinearRgba;
use bevy_ecs::{
bundle::Bundle,
change_detection::{DetectChanges, Ref},
component::Component,
entity::Entity,
event::EventReader,
prelude::With,
query::{Changed, Without},
reflect::ReflectComponent,
system::{Commands, Local, Query, Res, ResMut},
};
use bevy_math::Vec2;
use bevy_reflect::Reflect;
use bevy_render::{
primitives::Aabb,
texture::Image,
view::{InheritedVisibility, NoFrustumCulling, ViewVisibility, Visibility},
Extract,
};
use bevy_sprite::{Anchor, ExtractedSprite, ExtractedSprites, SpriteSource, TextureAtlasLayout};
use bevy_transform::prelude::{GlobalTransform, Transform};
use bevy_utils::HashSet;
use bevy_window::{PrimaryWindow, Window, WindowScaleFactorChanged};
#[derive(Component, Copy, Clone, Debug, Reflect)]
#[reflect(Component)]
pub struct Text2dBounds {
pub size: Vec2,
}
impl Default for Text2dBounds {
#[inline]
fn default() -> Self {
Self::UNBOUNDED
}
}
impl Text2dBounds {
pub const UNBOUNDED: Self = Self {
size: Vec2::splat(f32::INFINITY),
};
}
#[derive(Bundle, Clone, Debug, Default)]
pub struct Text2dBundle {
pub text: Text,
pub text_anchor: Anchor,
pub text_2d_bounds: Text2dBounds,
pub transform: Transform,
pub global_transform: GlobalTransform,
pub visibility: Visibility,
pub inherited_visibility: InheritedVisibility,
pub view_visibility: ViewVisibility,
pub text_layout_info: TextLayoutInfo,
pub sprite_source: SpriteSource,
}
pub fn extract_text2d_sprite(
mut commands: Commands,
mut extracted_sprites: ResMut<ExtractedSprites>,
texture_atlases: Extract<Res<Assets<TextureAtlasLayout>>>,
windows: Extract<Query<&Window, With<PrimaryWindow>>>,
text2d_query: Extract<
Query<(
Entity,
&ViewVisibility,
&Text,
&TextLayoutInfo,
&Anchor,
&GlobalTransform,
)>,
>,
) {
let scale_factor = windows
.get_single()
.map(|window| window.resolution.scale_factor())
.unwrap_or(1.0);
let scaling = GlobalTransform::from_scale(Vec2::splat(scale_factor.recip()).extend(1.));
for (original_entity, view_visibility, text, text_layout_info, anchor, global_transform) in
text2d_query.iter()
{
if !view_visibility.get() {
continue;
}
let text_anchor = -(anchor.as_vec() + 0.5);
let alignment_translation = text_layout_info.logical_size * text_anchor;
let transform = *global_transform
* GlobalTransform::from_translation(alignment_translation.extend(0.))
* scaling;
let mut color = LinearRgba::WHITE;
let mut current_section = usize::MAX;
for PositionedGlyph {
position,
atlas_info,
section_index,
..
} in &text_layout_info.glyphs
{
if *section_index != current_section {
color = LinearRgba::from(text.sections[*section_index].style.color);
current_section = *section_index;
}
let atlas = texture_atlases.get(&atlas_info.texture_atlas).unwrap();
let entity = commands.spawn_empty().id();
extracted_sprites.sprites.insert(
entity,
ExtractedSprite {
transform: transform * GlobalTransform::from_translation(position.extend(0.)),
color,
rect: Some(atlas.textures[atlas_info.glyph_index].as_rect()),
custom_size: None,
image_handle_id: atlas_info.texture.id(),
flip_x: false,
flip_y: false,
anchor: Anchor::Center.as_vec(),
original_entity: Some(original_entity),
},
);
}
}
}
#[allow(clippy::too_many_arguments)]
pub fn update_text2d_layout(
mut queue: Local<HashSet<Entity>>,
mut textures: ResMut<Assets<Image>>,
fonts: Res<Assets<Font>>,
text_settings: Res<TextSettings>,
windows: Query<&Window, With<PrimaryWindow>>,
mut scale_factor_changed: EventReader<WindowScaleFactorChanged>,
mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>,
mut font_atlas_sets: ResMut<FontAtlasSets>,
mut text_pipeline: ResMut<TextPipeline>,
mut text_query: Query<(Entity, Ref<Text>, Ref<Text2dBounds>, &mut TextLayoutInfo)>,
) {
let factor_changed = scale_factor_changed.read().last().is_some();
let scale_factor = windows
.get_single()
.map(|window| window.resolution.scale_factor())
.unwrap_or(1.0);
let inverse_scale_factor = scale_factor.recip();
for (entity, text, bounds, mut text_layout_info) in &mut text_query {
if factor_changed || text.is_changed() || bounds.is_changed() || queue.remove(&entity) {
let text_bounds = Vec2::new(
if text.linebreak_behavior == BreakLineOn::NoWrap {
f32::INFINITY
} else {
scale_value(bounds.size.x, scale_factor)
},
scale_value(bounds.size.y, scale_factor),
);
match text_pipeline.queue_text(
&fonts,
&text.sections,
scale_factor,
text.justify,
text.linebreak_behavior,
text_bounds,
&mut font_atlas_sets,
&mut texture_atlases,
&mut textures,
text_settings.as_ref(),
YAxisOrientation::BottomToTop,
) {
Err(TextError::NoSuchFont) => {
queue.insert(entity);
}
Err(e @ TextError::FailedToAddGlyph(_)) => {
panic!("Fatal error when processing text: {e}.");
}
Ok(mut info) => {
info.logical_size.x = scale_value(info.logical_size.x, inverse_scale_factor);
info.logical_size.y = scale_value(info.logical_size.y, inverse_scale_factor);
*text_layout_info = info;
}
}
}
}
}
pub fn scale_value(value: f32, factor: f32) -> f32 {
value * factor
}
pub fn calculate_bounds_text2d(
mut commands: Commands,
mut text_to_update_aabb: Query<
(Entity, &TextLayoutInfo, &Anchor, Option<&mut Aabb>),
(Changed<TextLayoutInfo>, Without<NoFrustumCulling>),
>,
) {
for (entity, layout_info, anchor, aabb) in &mut text_to_update_aabb {
let center = (-anchor.as_vec() * layout_info.logical_size)
.extend(0.0)
.into();
let half_extents = (layout_info.logical_size / 2.0).extend(0.0).into();
if let Some(mut aabb) = aabb {
*aabb = Aabb {
center,
half_extents,
};
} else {
commands.entity(entity).try_insert(Aabb {
center,
half_extents,
});
}
}
}
#[cfg(test)]
mod tests {
use bevy_app::{App, Update};
use bevy_asset::{load_internal_binary_asset, Handle};
use bevy_ecs::{event::Events, schedule::IntoSystemConfigs};
use bevy_utils::default;
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::<TextSettings>()
.init_resource::<FontAtlasSets>()
.init_resource::<Events<WindowScaleFactorChanged>>()
.insert_resource(TextPipeline::default())
.add_systems(
Update,
(
update_text2d_layout,
calculate_bounds_text2d.after(update_text2d_layout),
),
);
load_internal_binary_asset!(
app,
Handle::default(),
"FiraMono-subset.ttf",
|bytes: &[u8], _path: String| { Font::try_from_bytes(bytes.to_vec()).unwrap() }
);
let entity = app
.world_mut()
.spawn((Text2dBundle {
text: Text::from_section(FIRST_TEXT, default()),
..default()
},))
.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>());
app.update();
let aabb = app
.world()
.get_entity(entity)
.expect("Could not find entity")
.get::<Aabb>()
.expect("Text should have an AABB");
assert_eq!(aabb.center.z, 0.0);
assert_eq!(aabb.half_extents.z, 0.0);
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();
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::<Text>()
.expect("Missing Text on entity") = Text::from_section(SECOND_TEXT, default());
app.update();
let second_aabb = *app
.world()
.get_entity(entity)
.expect("Could not find entity")
.get::<Aabb>()
.expect("Could not find second AABB");
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);
}
}