Text 2d alignment fix (#17365)

# Objective

`Text2d` ignores `TextBounds` when calculating the offset for text
aligment.
On main a text entity positioned in the center of the window with center
justification and 600px horizontal text bounds isn't centered like it
should be but shifted off to the right:
<img width="305" alt="hellox"
src="https://github.com/user-attachments/assets/8896c6f0-1b9f-4633-9c12-1de6eff5f3e1"
/>
(second example in the testing section below)

Fixes #14266

I already had a PR in review for this (#14270) but it used post layout
adjustment (which we want to avoid) and ignored `TextBounds`.

## Solution

* If `TextBounds` are present for an axis, use them instead of the size
of the computed text layout size to calculate the offset.
* Adjust the vertical offset of text so it's top is aligned with the top
of the texts bounding rect (when present).

## Testing

```
use bevy::prelude::*;
use bevy::color::palettes;
use bevy::sprite::Anchor;
use bevy::text::TextBounds;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}

fn example(commands: &mut Commands, dest: Vec3, justify: JustifyText) {
    commands.spawn((
        Sprite {
            color: palettes::css::YELLOW.into(),
            custom_size: Some(10. * Vec2::ONE),
            anchor: Anchor::Center,
            ..Default::default()
        },
        Transform::from_translation(dest),
    ));

    for a in [
        Anchor::TopLeft,
        Anchor::TopRight,
        Anchor::BottomRight,
        Anchor::BottomLeft,
    ] {
        commands.spawn((
            Text2d(format!("L R\n{:?}\n{:?}", a, justify)),
            TextFont {
                font_size: 14.0,
                ..default()
            },
            TextLayout {
                justify,
                ..Default::default()
            },
            TextBounds::new(300., 75.),
            Transform::from_translation(dest + Vec3::Z),
            a,
        ));
    }
}

fn setup(mut commands: Commands) {
    commands.spawn(Camera2d::default());

    for (i, j) in [
        JustifyText::Left,
        JustifyText::Right,
        JustifyText::Center,
        JustifyText::Justified,
    ]
    .into_iter()
    .enumerate()
    {
        example(&mut commands, (300. - 150. * i as f32) * Vec3::Y, j);
    }

    commands.spawn(Sprite {
        color: palettes::css::YELLOW.into(),
        custom_size: Some(10. * Vec2::ONE),
        anchor: Anchor::Center,
        ..Default::default()
    });
}
```

<img width="566" alt="cap"
src="https://github.com/user-attachments/assets/e6a98fa5-80b2-4380-a9b7-155bb49635b8"
/>

This probably looks really confusing but it should make sense if you
imagine each block of text surrounded by a 300x75 rectangle that is
anchored to the center of the yellow square.

# 

```
use bevy::prelude::*;
use bevy::sprite::Anchor;
use bevy::text::TextBounds;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}

fn setup(mut commands: Commands) {
    commands.spawn(Camera2d::default());

    commands.spawn((
        Text2d::new("hello"),
        TextFont {
            font_size: 60.0,
            ..default()
        },
        TextLayout::new_with_justify(JustifyText::Center),
        TextBounds::new(600., 200.),
        Anchor::Center,
    ));
}
```

<img width="338" alt="hello"
src="https://github.com/user-attachments/assets/e5e89364-afda-4baa-aca8-df4cdacbb4ed"
/>

The text being above the center is intended. When `TextBounds` are
present, the text block's offset is calculated using its `TextBounds`
not the layout size returned by cosmic-text.

# 

Probably we should add a vertical alignment setting for Text2d. Didn't
do it here as this is intended for a 0.15.2 release.
This commit is contained in:
ickshonpe 2025-01-20 20:54:32 +00:00 committed by GitHub
parent a99674ab86
commit 3f99a3e8cd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 62 additions and 36 deletions

View File

@ -138,6 +138,7 @@ pub fn extract_text2d_sprite(
&ViewVisibility,
&ComputedTextBlock,
&TextLayoutInfo,
&TextBounds,
&Anchor,
&GlobalTransform,
)>,
@ -156,6 +157,7 @@ pub fn extract_text2d_sprite(
view_visibility,
computed_block,
text_layout_info,
text_bounds,
anchor,
global_transform,
) in text2d_query.iter()
@ -164,11 +166,14 @@ pub fn extract_text2d_sprite(
continue;
}
let text_anchor = -(anchor.as_vec() + 0.5);
let alignment_translation = text_layout_info.size * text_anchor;
let transform = *global_transform
* GlobalTransform::from_translation(alignment_translation.extend(0.))
* scaling;
let size = Vec2::new(
text_bounds.width.unwrap_or(text_layout_info.size.x),
text_bounds.height.unwrap_or(text_layout_info.size.y),
);
let bottom_left =
-(anchor.as_vec() + 0.5) * size + (size.y - text_layout_info.size.y) * Vec2::Y;
let transform =
*global_transform * GlobalTransform::from_translation(bottom_left.extend(0.)) * scaling;
let mut color = LinearRgba::WHITE;
let mut current_span = usize::MAX;
for PositionedGlyph {
@ -319,16 +324,27 @@ pub fn scale_value(value: f32, factor: f32) -> f32 {
pub fn calculate_bounds_text2d(
mut commands: Commands,
mut text_to_update_aabb: Query<
(Entity, &TextLayoutInfo, &Anchor, Option<&mut Aabb>),
(
Entity,
&TextLayoutInfo,
&Anchor,
&TextBounds,
Option<&mut Aabb>,
),
(Changed<TextLayoutInfo>, Without<NoFrustumCulling>),
>,
) {
for (entity, layout_info, anchor, aabb) in &mut text_to_update_aabb {
// `Anchor::as_vec` gives us an offset relative to the text2d bounds, by negating it and scaling
// by the logical size we compensate the transform offset in local space to get the center.
let center = (-anchor.as_vec() * layout_info.size).extend(0.0).into();
// Distance in local space from the center to the x and y limits of the text2d bounds.
let half_extents = (layout_info.size / 2.0).extend(0.0).into();
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 center = (-anchor.as_vec() * size + (size.y - layout_info.size.y) * Vec2::Y)
.extend(0.)
.into();
let half_extents = (0.5 * layout_info.size).extend(0.0).into();
if let Some(mut aabb) = aabb {
*aabb = Aabb {
center,

View File

@ -119,30 +119,40 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
Transform::from_translation(Vec3::new(-400.0, -250.0, 0.0)),
));
for (text_anchor, color) in [
(Anchor::TopLeft, Color::Srgba(RED)),
(Anchor::TopRight, Color::Srgba(LIME)),
(Anchor::BottomRight, Color::Srgba(BLUE)),
(Anchor::BottomLeft, Color::Srgba(YELLOW)),
] {
commands
.spawn((
Text2d::new(" Anchor".to_string()),
slightly_smaller_text_font.clone(),
Transform::from_translation(250. * Vec3::Y),
text_anchor,
))
.with_child((
TextSpan("::".to_string()),
slightly_smaller_text_font.clone(),
TextColor(LIGHT_GREY.into()),
))
.with_child((
TextSpan(format!("{text_anchor:?} ")),
slightly_smaller_text_font.clone(),
TextColor(color),
));
}
commands
.spawn((
Sprite {
color: Color::Srgba(LIGHT_CYAN),
custom_size: Some(Vec2::new(10., 10.)),
..Default::default()
},
Transform::from_translation(250. * Vec3::Y),
))
.with_children(|commands| {
for (text_anchor, color) in [
(Anchor::TopLeft, Color::Srgba(RED)),
(Anchor::TopRight, Color::Srgba(LIME)),
(Anchor::BottomRight, Color::Srgba(BLUE)),
(Anchor::BottomLeft, Color::Srgba(YELLOW)),
] {
commands
.spawn((
Text2d::new(" Anchor".to_string()),
slightly_smaller_text_font.clone(),
text_anchor,
))
.with_child((
TextSpan("::".to_string()),
slightly_smaller_text_font.clone(),
TextColor(LIGHT_GREY.into()),
))
.with_child((
TextSpan(format!("{text_anchor:?} ")),
slightly_smaller_text_font.clone(),
TextColor(color),
));
}
});
}
fn animate_translation(