Files
ickshonpe 6ca4769128 Minimal responsive FontSize support (#22614)
# Objective

Add responsive font sizes supporting rem and viewport units to
`bevy_text` with minimal changes to the APIs and systems.

## Solution

Introduce a new `FontSize` enum:

```rust
pub enum FontSize {
    /// Font Size in logical pixels.
    Px(f32),
    /// Font size as a percentage of the viewport width.
    Vw(f32),
    /// Font size as a percentage of the viewport height.
    Vh(f32),
    /// Font size as a percentage of the smaller of the viewport width and height.
    VMin(f32),
    /// Font size as a percentage of the larger of the viewport width and height.
    VMax(f32),
    /// Font Size relative to the value of the `RemSize` resource.
    Rem(f32),
}
```

This replaces the `f32` value of `TextFont`'s `font_size` field.

The viewport variants work the same way as their respective `Val`
counterparts.

`Rem` values are multiplied by the value of the `RemSize` resource
(which newtypes an `f32`).

`FontSize` provides an `eval` method that takes a logical viewport size
and rem base size and returns an `f32` logical font size. The resolved
logical font size is then written into the `Attributes` passed to Cosmic
Text by `TextPipeline::update_buffer`.

Any text implementation using `bevy_text` must now provide viewport and
rem base values when calling `TextPipeline::update_buffer` or
`create_measure`.

`Text2d` uses the size of the primary window to resolve viewport values
(or `Vec2::splat(1000)` if no primary window is found). This is a
deliberate compromise, a single `Text2d` can be rendered to multiple
viewports using `RenderLayers`, so it's difficult to find a rule for
which viewport size should be chosen.

### Change detection 

`ComputedTextBlock` has two new fields: `uses_viewport_sizes` and
`uses_rem_sizes`, which are set to true in `TextPipeline::update_buffer`
iff any text section in the block uses viewport or rem font sizes,
respectively.

The `ComputedTextBlock::needs_rerender` method has been modified to take
take two bool parameters:
```rust
    pub fn needs_rerender(
        &self,
        is_viewport_size_changed: bool,
        is_rem_size_changed: bool,
    ) -> bool {
        self.needs_rerender
            || (is_viewport_size_changed && self.uses_viewport_sizes)
            || (is_rem_size_changed && self.uses_rem_sizes)
    }
 ```
This ensures that text reupdates will also be scheduled if one of the text section's uses a viewport font size and the local viewport size changed, or if one of the text section's uses a rem font size and the rem size changed.

#### Limitations

There are some limitations because we don't have any sort of font style inheritance yet:

* "rem" units aren't proper rem units, and just based on the value of a resource. 
* "em" units are resolved based on inherited font size, so can't be implemented without inheritance support.

#### Notes

* This PR is quite small and not very technical. Reviewers don't need to be especially familiar with `bevy_text`. Most of the changes are to the examples.

* We could consider using `Val` instead of `FontSize`, then we could use `Val`'s constructor functions which would be much nicer, but some variants might not have sensible interpretations in both UI and Text2d contexts. Also we'd have to make `Val` accessible to `bevy_text`.

## Testing

The changes to the text systems are relatively trivial and easy to understand.  I already added a minor change to the `text` example to use `Vh` font size for the "hello bevy" text in the bottom right corner. If you change the size of the window, you should see the text change size in response. The text initially flickers before it updates because of some unrelated asset/image changes that mean that font textures aren't ready until the frame after the text update that changes the font size.

Most of the example migrations were automated using regular expressions, and there are bound to be mistakes in those changes. It's infeasible to check every single example thoroughly, but it's early enough in the release cycle that I don't think we should be too worried if a few bugs slip in.

---------

Co-authored-by: Kevin Chen <chen.kevin.f@gmail.com>
2026-02-02 22:52:33 +00:00

300 lines
14 KiB
Rust

//! Simple example demonstrating linear gradients.
use bevy::color::palettes::css::BLUE;
use bevy::color::palettes::css::GREEN;
use bevy::color::palettes::css::INDIGO;
use bevy::color::palettes::css::LIME;
use bevy::color::palettes::css::ORANGE;
use bevy::color::palettes::css::RED;
use bevy::color::palettes::css::VIOLET;
use bevy::color::palettes::css::YELLOW;
use bevy::prelude::*;
use bevy::ui::ColorStop;
use std::f32::consts::TAU;
#[derive(Component)]
struct CurrentColorSpaceLabel;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_systems(Update, update)
.run();
}
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
commands
.spawn(Node {
flex_direction: FlexDirection::Column,
row_gap: px(20),
margin: UiRect::all(px(20)),
..Default::default()
})
.with_children(|commands| {
for (b, stops) in [
(
4.,
vec![
ColorStop::new(Color::WHITE, percent(15)),
ColorStop::new(Color::BLACK, percent(85)),
],
),
(4., vec![RED.into(), BLUE.into(), LIME.into()]),
(
0.,
vec![
RED.into(),
ColorStop::new(RED, percent(100. / 7.)),
ColorStop::new(ORANGE, percent(100. / 7.)),
ColorStop::new(ORANGE, percent(200. / 7.)),
ColorStop::new(YELLOW, percent(200. / 7.)),
ColorStop::new(YELLOW, percent(300. / 7.)),
ColorStop::new(GREEN, percent(300. / 7.)),
ColorStop::new(GREEN, percent(400. / 7.)),
ColorStop::new(BLUE, percent(400. / 7.)),
ColorStop::new(BLUE, percent(500. / 7.)),
ColorStop::new(INDIGO, percent(500. / 7.)),
ColorStop::new(INDIGO, percent(600. / 7.)),
ColorStop::new(VIOLET, percent(600. / 7.)),
VIOLET.into(),
],
),
] {
commands.spawn(Node::default()).with_children(|commands| {
commands
.spawn(Node {
flex_direction: FlexDirection::Column,
row_gap: px(5),
..Default::default()
})
.with_children(|commands| {
for (w, h) in [(70., 70.), (35., 70.), (70., 35.)] {
commands
.spawn(Node {
column_gap: px(10),
..Default::default()
})
.with_children(|commands| {
for angle in (0..8).map(|i| i as f32 * TAU / 8.) {
commands.spawn((
Node {
width: px(w),
height: px(h),
border: UiRect::all(px(b)),
border_radius: BorderRadius::all(px(20)),
..default()
},
BackgroundGradient::from(LinearGradient {
angle,
stops: stops.clone(),
..default()
}),
BorderGradient::from(LinearGradient {
angle: 3. * TAU / 8.,
stops: vec![
YELLOW.into(),
Color::WHITE.into(),
ORANGE.into(),
],
..default()
}),
));
}
});
}
});
commands.spawn(Node::default()).with_children(|commands| {
commands.spawn((
Node {
aspect_ratio: Some(1.),
height: percent(100),
border: UiRect::all(px(b)),
margin: UiRect::left(px(20)),
border_radius: BorderRadius::all(px(20)),
..default()
},
BackgroundGradient::from(LinearGradient {
angle: 0.,
stops: stops.clone(),
..default()
}),
BorderGradient::from(LinearGradient {
angle: 3. * TAU / 8.,
stops: vec![YELLOW.into(), Color::WHITE.into(), ORANGE.into()],
..default()
}),
AnimateMarker,
));
commands.spawn((
Node {
aspect_ratio: Some(1.),
height: percent(100),
border: UiRect::all(px(b)),
margin: UiRect::left(px(20)),
border_radius: BorderRadius::all(px(20)),
..default()
},
BackgroundGradient::from(RadialGradient {
stops: stops.clone(),
shape: RadialGradientShape::ClosestSide,
position: UiPosition::CENTER,
..default()
}),
BorderGradient::from(LinearGradient {
angle: 3. * TAU / 8.,
stops: vec![YELLOW.into(), Color::WHITE.into(), ORANGE.into()],
..default()
}),
AnimateMarker,
));
commands.spawn((
Node {
aspect_ratio: Some(1.),
height: percent(100),
border: UiRect::all(px(b)),
margin: UiRect::left(px(20)),
border_radius: BorderRadius::all(px(20)),
..default()
},
BackgroundGradient::from(ConicGradient {
start: 0.,
stops: stops
.iter()
.map(|stop| AngularColorStop::auto(stop.color))
.collect(),
position: UiPosition::CENTER,
..default()
}),
BorderGradient::from(LinearGradient {
angle: 3. * TAU / 8.,
stops: vec![YELLOW.into(), Color::WHITE.into(), ORANGE.into()],
..default()
}),
AnimateMarker,
));
});
});
}
let button = commands.spawn((
Button,
Node {
border: UiRect::all(px(2)),
padding: UiRect::axes(px(8), px(4)),
// horizontally center child text
justify_content: JustifyContent::Center,
// vertically center child text
align_items: AlignItems::Center,
border_radius: BorderRadius::MAX,
..default()
},
BorderColor::all(Color::WHITE),
BackgroundColor(Color::BLACK),
children![(
Text::new("next color space"),
TextColor(Color::srgb(0.9, 0.9, 0.9)),
TextShadow::default(),
)]
)).observe(
|_event: On<Pointer<Over>>, mut border_query: Query<&mut BorderColor, With<Button>>| {
*border_query.single_mut().unwrap() = BorderColor::all(RED);
})
.observe(
|_event: On<Pointer<Out>>, mut border_query: Query<&mut BorderColor, With<Button>>| {
*border_query.single_mut().unwrap() = BorderColor::all(Color::WHITE);
})
.observe(
|_event: On<Pointer<Click>>,
mut gradients_query: Query<&mut BackgroundGradient>,
mut label_query: Query<
&mut Text,
With<CurrentColorSpaceLabel>,
>| {
let mut current_space = InterpolationColorSpace::default();
for mut gradients in gradients_query.iter_mut() {
for gradient in gradients.0.iter_mut() {
let space = match gradient {
Gradient::Linear(linear_gradient) => {
&mut linear_gradient.color_space
}
Gradient::Radial(radial_gradient) => {
&mut radial_gradient.color_space
}
Gradient::Conic(conic_gradient) => {
&mut conic_gradient.color_space
}
};
*space = match *space {
InterpolationColorSpace::Oklaba => {
InterpolationColorSpace::Oklcha
}
InterpolationColorSpace::Oklcha => {
InterpolationColorSpace::OklchaLong
}
InterpolationColorSpace::OklchaLong => {
InterpolationColorSpace::Srgba
}
InterpolationColorSpace::Srgba => {
InterpolationColorSpace::LinearRgba
}
InterpolationColorSpace::LinearRgba => {
InterpolationColorSpace::Hsla
}
InterpolationColorSpace::Hsla => {
InterpolationColorSpace::HslaLong
}
InterpolationColorSpace::HslaLong => {
InterpolationColorSpace::Hsva
}
InterpolationColorSpace::Hsva => {
InterpolationColorSpace::HsvaLong
}
InterpolationColorSpace::HsvaLong => {
InterpolationColorSpace::Oklaba
}
};
current_space = *space;
}
}
for mut label in label_query.iter_mut() {
label.0 = format!("{current_space:?}");
}
}
).id();
commands.spawn(
Node {
flex_direction: FlexDirection::Column,
row_gap: px(10),
align_items: AlignItems::Center,
..Default::default()
}
).with_children(|commands| {
commands.spawn((Text::new(format!("{:?}", InterpolationColorSpace::default())), TextFont { font_size: FontSize::Px(25.), ..default() }, CurrentColorSpaceLabel));
})
.add_child(button);
});
}
#[derive(Component)]
struct AnimateMarker;
fn update(time: Res<Time>, mut query: Query<&mut BackgroundGradient, With<AnimateMarker>>) {
for mut gradients in query.iter_mut() {
for gradient in gradients.0.iter_mut() {
if let Gradient::Linear(LinearGradient { angle, .. }) = gradient {
*angle += 0.5 * time.delta_secs();
}
}
}
}