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

198 lines
6.2 KiB
Rust

//! This example illustrates how to create a context menu that changes the clear color
use bevy::{
color::palettes::basic,
ecs::{relationship::RelatedSpawner, spawn::SpawnWith},
prelude::*,
};
use std::fmt::Debug;
/// event opening a new context menu at position `pos`
#[derive(Event)]
struct OpenContextMenu {
pos: Vec2,
}
/// event will be sent to close currently open context menus
#[derive(Event)]
struct CloseContextMenus;
/// marker component identifying root of a context menu
#[derive(Component)]
struct ContextMenu;
/// context menu item data storing what background color `Srgba` it activates
#[derive(Component)]
struct ContextMenuItem(Srgba);
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_observer(on_trigger_menu)
.add_observer(on_trigger_close_menus)
.add_observer(text_color_on_hover::<Out>(basic::WHITE.into()))
.add_observer(text_color_on_hover::<Over>(basic::RED.into()))
.run();
}
/// helper function to reduce code duplication when generating almost identical observers for the hover text color change effect
fn text_color_on_hover<T: Debug + Clone + Reflect>(
color: Color,
) -> impl FnMut(On<Pointer<T>>, Query<&mut TextColor>, Query<&Children>) {
move |mut event: On<Pointer<T>>,
mut text_color: Query<&mut TextColor>,
children: Query<&Children>| {
let Ok(children) = children.get(event.original_event_target()) else {
return;
};
event.propagate(false);
// find the text among children and change its color
for child in children.iter() {
if let Ok(mut col) = text_color.get_mut(child) {
col.0 = color;
}
}
}
}
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
commands.spawn(background_and_button()).observe(
// any click bubbling up here should lead to closing any open menu
|_: On<Pointer<Press>>, mut commands: Commands| {
commands.trigger(CloseContextMenus);
},
);
}
fn on_trigger_close_menus(
_event: On<CloseContextMenus>,
mut commands: Commands,
menus: Query<Entity, With<ContextMenu>>,
) {
for e in menus.iter() {
commands.entity(e).despawn();
}
}
fn on_trigger_menu(event: On<OpenContextMenu>, mut commands: Commands) {
commands.trigger(CloseContextMenus);
let pos = event.pos;
debug!("open context menu at: {pos}");
commands
.spawn((
Name::new("context menu"),
ContextMenu,
Node {
position_type: PositionType::Absolute,
left: px(pos.x),
top: px(pos.y),
flex_direction: FlexDirection::Column,
border_radius: BorderRadius::all(px(4)),
..default()
},
BorderColor::all(Color::BLACK),
BackgroundColor(Color::linear_rgb(0.1, 0.1, 0.1)),
children![
context_item("fuchsia", basic::FUCHSIA),
context_item("gray", basic::GRAY),
context_item("maroon", basic::MAROON),
context_item("purple", basic::PURPLE),
context_item("teal", basic::TEAL),
],
))
.observe(
|event: On<Pointer<Press>>,
menu_items: Query<&ContextMenuItem>,
mut clear_col: ResMut<ClearColor>,
mut commands: Commands| {
let target = event.original_event_target();
if let Ok(item) = menu_items.get(target) {
clear_col.0 = item.0.into();
commands.trigger(CloseContextMenus);
}
},
);
}
fn context_item(text: &str, col: Srgba) -> impl Bundle {
(
Name::new(format!("item-{text}")),
ContextMenuItem(col),
Button,
Node {
padding: UiRect::all(px(5)),
..default()
},
children![(
Pickable::IGNORE,
Text::new(text),
TextFont {
font_size: FontSize::Px(24.0),
..default()
},
TextColor(Color::WHITE),
)],
)
}
fn background_and_button() -> impl Bundle {
(
Name::new("background"),
Node {
width: percent(100),
height: percent(100),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
ZIndex(-10),
Children::spawn(SpawnWith(|parent: &mut RelatedSpawner<ChildOf>| {
parent
.spawn((
Name::new("button"),
Button,
Node {
width: px(250),
height: px(65),
border: UiRect::all(px(5)),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
border_radius: BorderRadius::MAX,
..default()
},
BorderColor::all(Color::BLACK),
BackgroundColor(Color::BLACK),
children![(
Pickable::IGNORE,
Text::new("Context Menu"),
TextFont {
font_size: FontSize::Px(28.0),
..default()
},
TextColor(Color::WHITE),
TextShadow::default(),
)],
))
.observe(|mut event: On<Pointer<Press>>, mut commands: Commands| {
// by default this event would bubble up further leading to the `CloseContextMenus`
// event being triggered and undoing the opening of one here right away.
event.propagate(false);
debug!("click: {}", event.pointer_location.position);
commands.trigger(OpenContextMenu {
pos: event.pointer_location.position,
});
});
})),
)
}