voxel-framework 0.13.2

A reusable voxel engine framework built on Bevy
Documentation
//! Shared font selection for the built-in UI plugins.

use bevy::prelude::*;

/// Fonts used by the text that the built-in UI plugins draw.
///
/// [`LoadingScreenPlugin`](crate::ui::LoadingScreenPlugin),
/// [`VoxelHudPlugin`](crate::ui::VoxelHudPlugin), `HotbarContentPlugin` and
/// `PickupNotificationPlugin` (the last two with the `items` feature) each
/// initialize this resource with [`Default`] when the game has not inserted
/// one, and never replace one that is already there. The default holds two
/// default handles, which select the engine default font: with no font
/// configured every text is drawn exactly as before this resource existed.
///
/// | Field     | Used by                                                        |
/// |-----------|----------------------------------------------------------------|
/// | `display` | Loading screen title                                           |
/// | `text`    | Retained HUD text, hotbar item name, symbols and counts, pickup notification lines |
///
/// One retained HUD element can use another font through
/// [`HudElementDefinition::font`](crate::ui::HudElementDefinition::font),
/// which takes precedence over `text`.
///
/// The pause menu is not affected: it keeps its own fonts in
/// [`PauseMenuConfig`](crate::ui::PauseMenuConfig), because it falls back to
/// the embedded NotoSans font instead of the engine default. The debug overlay
/// always uses the engine default font.
///
/// # Changing fonts at runtime
///
/// A change to this resource is applied to the text that is already on
/// screen, not only to text spawned later: the loading screen title, the
/// hotbar text and the visible pickup notifications are updated in
/// `PostUpdate` of the frame in which the resource changed, and the retained
/// HUD in its next [`HudSystemSet::Render`](crate::ui::HudSystemSet::Render)
/// pass. A game can therefore insert the resource from a `Startup` system or
/// after its fonts finished loading, without ordering that system against the
/// plugins.
///
/// The framework only stores the handles. Loading the font assets, and keeping
/// them alive, is up to the game.
///
/// The struct is `#[non_exhaustive]`: build it with [`UiFonts::new`] or
/// [`UiFonts::uniform`], or change the fields of [`UiFonts::default`].
///
/// # Example
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::prelude::*;
///
/// fn load_fonts(mut commands: Commands, asset_server: Res<AssetServer>) {
///     commands.insert_resource(UiFonts::new(
///         asset_server.load("fonts/Display.ttf"),
///         asset_server.load("fonts/Text.ttf"),
///     ));
/// }
///
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .add_plugins(UiPlugin)
///     .add_systems(Startup, load_fonts)
///     .run();
/// ```
#[derive(Resource, Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct UiFonts {
    /// Font of titles and other large, short text.
    pub display: Handle<Font>,
    /// Font of labels, numbers and other running text.
    pub text: Handle<Font>,
}

impl UiFonts {
    /// Creates the resource with a font for titles and a font for running text.
    pub fn new(display: Handle<Font>, text: Handle<Font>) -> Self {
        Self { display, text }
    }

    /// Creates the resource with the same font for titles and running text.
    pub fn uniform(font: Handle<Font>) -> Self {
        Self {
            display: font.clone(),
            text: font,
        }
    }
}

/// Which [`UiFonts`] field a framework-owned text entity follows.
///
/// Text carrying this component gets its font replaced whenever [`UiFonts`]
/// changes.
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum UiFontRole {
    /// Follows [`UiFonts::display`].
    Display,
    /// Follows [`UiFonts::text`].
    #[cfg_attr(not(any(test, feature = "items")), allow(dead_code))]
    Text,
}

impl UiFontRole {
    /// Font of this role, or the engine default when the game runs the
    /// spawning system without a plugin that initializes [`UiFonts`].
    pub(crate) fn font(self, fonts: Option<&UiFonts>) -> Handle<Font> {
        match (self, fonts) {
            (_, None) => Handle::default(),
            (Self::Display, Some(fonts)) => fonts.display.clone(),
            (Self::Text, Some(fonts)) => fonts.text.clone(),
        }
    }
}

/// Applies a changed [`UiFonts`] to the text that is already spawned.
fn apply_ui_fonts(fonts: Res<UiFonts>, mut texts: Query<(&UiFontRole, &mut TextFont)>) {
    if !fonts.is_changed() {
        return;
    }
    for (role, mut text_font) in &mut texts {
        let font = role.font(Some(&fonts));
        if text_font.font != font {
            text_font.font = font;
        }
    }
}

/// Internal plugin shared by the UI plugins that tag text with [`UiFontRole`].
struct UiFontsPlugin;

impl Plugin for UiFontsPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<UiFonts>().add_systems(
            PostUpdate,
            apply_ui_fonts.before(bevy::ui::UiSystems::Prepare),
        );
    }
}

/// Initializes [`UiFonts`] and its runtime update once per app, whichever UI
/// plugins are added.
pub(crate) fn register_ui_fonts(app: &mut App) {
    if !app.is_plugin_added::<UiFontsPlugin>() {
        app.add_plugins(UiFontsPlugin);
    }
}

/// Distinct placeholder handles for headless tests; no font asset is loaded.
#[cfg(test)]
pub(crate) mod test_fonts {
    use bevy::asset::uuid_handle;
    use bevy::prelude::*;

    pub(crate) fn display() -> Handle<Font> {
        uuid_handle!("6f1c2f0e-5a0b-4f0e-9d53-0d5d3c3f7a01")
    }

    pub(crate) fn text() -> Handle<Font> {
        uuid_handle!("6f1c2f0e-5a0b-4f0e-9d53-0d5d3c3f7a02")
    }

    pub(crate) fn other() -> Handle<Font> {
        uuid_handle!("6f1c2f0e-5a0b-4f0e-9d53-0d5d3c3f7a03")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Component)]
    struct Untagged;

    #[test]
    fn default_fonts_are_the_engine_default_handles() {
        let fonts = UiFonts::default();
        assert_eq!(fonts.display, Handle::<Font>::default());
        assert_eq!(fonts.text, Handle::<Font>::default());
        assert_ne!(test_fonts::display(), Handle::<Font>::default());
        assert_ne!(test_fonts::display(), test_fonts::text());
    }

    #[test]
    fn uniform_uses_one_font_for_both_roles() {
        let fonts = UiFonts::uniform(test_fonts::other());
        assert_eq!(fonts.display, test_fonts::other());
        assert_eq!(fonts.text, test_fonts::other());
    }

    #[test]
    fn role_without_the_resource_is_the_engine_default_font() {
        assert_eq!(UiFontRole::Display.font(None), Handle::<Font>::default());
        assert_eq!(UiFontRole::Text.font(None), Handle::<Font>::default());
    }

    #[test]
    fn registering_twice_keeps_the_fonts_inserted_by_the_game() {
        let mut app = App::new();
        app.add_plugins(MinimalPlugins)
            .insert_resource(UiFonts::new(test_fonts::display(), test_fonts::text()));
        register_ui_fonts(&mut app);
        register_ui_fonts(&mut app);
        app.update();
        assert_eq!(
            *app.world().resource::<UiFonts>(),
            UiFonts::new(test_fonts::display(), test_fonts::text())
        );
    }

    #[test]
    fn changed_fonts_reach_tagged_text_and_leave_other_text_alone() {
        let mut app = App::new();
        app.add_plugins(MinimalPlugins);
        register_ui_fonts(&mut app);
        let title = app
            .world_mut()
            .spawn((UiFontRole::Display, TextFont::from_font_size(32.0)))
            .id();
        let label = app
            .world_mut()
            .spawn((UiFontRole::Text, TextFont::from_font_size(14.0)))
            .id();
        let game_text = app
            .world_mut()
            .spawn((Untagged, TextFont::from_font_size(20.0)))
            .id();
        app.update();
        let font = |app: &App, entity: Entity| app.world().get::<TextFont>(entity).unwrap().clone();
        assert_eq!(font(&app, title), TextFont::from_font_size(32.0));
        assert_eq!(font(&app, label), TextFont::from_font_size(14.0));

        app.insert_resource(UiFonts::new(test_fonts::display(), test_fonts::text()));
        app.update();
        assert_eq!(
            font(&app, title),
            TextFont::from_font_size(32.0).with_font(test_fonts::display())
        );
        assert_eq!(
            font(&app, label),
            TextFont::from_font_size(14.0).with_font(test_fonts::text())
        );
        assert_eq!(font(&app, game_text), TextFont::from_font_size(20.0));

        app.world_mut().resource_mut::<UiFonts>().text = test_fonts::other();
        app.update();
        assert_eq!(font(&app, title).font, test_fonts::display());
        assert_eq!(font(&app, label).font, test_fonts::other());
    }
}