diff --git a/assets/fonts/EBGaramond-LICENSE b/assets/fonts/EBGaramond-LICENSE new file mode 100644 index 0000000000000..392771d39ab0f --- /dev/null +++ b/assets/fonts/EBGaramond-LICENSE @@ -0,0 +1,93 @@ +Copyright (c) 2010-2013 Georg Duffner (http://www.georgduffner.at) + +All "EB Garamond" Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/fonts/EBGaramond12-Regular.otf b/assets/fonts/EBGaramond12-Regular.otf new file mode 100644 index 0000000000000..6f26875528ea6 Binary files /dev/null and b/assets/fonts/EBGaramond12-Regular.otf differ diff --git a/crates/bevy_text/src/pipeline.rs b/crates/bevy_text/src/pipeline.rs index f1bdeded917bb..c4f9d6523b1d7 100644 --- a/crates/bevy_text/src/pipeline.rs +++ b/crates/bevy_text/src/pipeline.rs @@ -508,6 +508,7 @@ fn get_attrs<'a>( } .scale(scale_factor as f32), ) + .font_features((&text_font.font_features).into()) .color(cosmic_text::Color(color.to_linear().as_u32())); attrs } diff --git a/crates/bevy_text/src/text.rs b/crates/bevy_text/src/text.rs index faa5d93dc9cee..2f9e3e2533fc4 100644 --- a/crates/bevy_text/src/text.rs +++ b/crates/bevy_text/src/text.rs @@ -307,6 +307,8 @@ pub struct TextFont { pub line_height: LineHeight, /// The antialiasing method to use when rendering text. pub font_smoothing: FontSmoothing, + /// OpenType features for .otf fonts that support them. + pub font_features: FontFeatures, } impl TextFont { @@ -351,11 +353,175 @@ impl Default for TextFont { font: Default::default(), font_size: 20.0, line_height: LineHeight::default(), + font_features: FontFeatures::default(), font_smoothing: Default::default(), } } } +/// OpenType features for .otf fonts that support them. +/// +/// Examples features include ligatures, small-caps, and fractional number display. For the complete +/// list of OpenType features, see the spec at +/// ``. +/// +/// # Usage: +/// ``` +/// use bevy_text::FontFeatures; +/// +/// // Create using the builder +/// let font_features = FontFeatures::builder() +/// .enable(FontFeatures::STANDARD_LIGATURES) +/// .set(FontFeatures::WEIGHT, 300) +/// .build(); +/// +/// // Create from a list +/// let more_font_features: FontFeatures = [ +/// FontFeatures::STANDARD_LIGATURES, +/// FontFeatures::OLDSTYLE_FIGURES, +/// FontFeatures::TABULAR_FIGURES +/// ].into(); +/// ``` +#[derive(Clone, Debug, Default, Reflect)] +pub struct FontFeatures { + features: Vec<([u8; 4], u32)>, +} + +impl FontFeatures { + /// Replaces character combinations like fi, fl with ligatures. + pub const STANDARD_LIGATURES: [u8; 4] = *b"liga"; + + /// Enables ligatures based on character context. + pub const CONTEXTUAL_LIGATURES: [u8; 4] = *b"clig"; + + /// Enables optional ligatures for stylistic use (e.g., ct, st). + pub const DISCRETIONARY_LIGATURES: [u8; 4] = *b"dlig"; + + /// Adjust glyph shapes based on surrounding letters. + pub const CONTEXTUAL_ALTERNATES: [u8; 4] = *b"calt"; + + /// Use alternate glyph designs. + pub const STYLISTIC_ALTERNATES: [u8; 4] = *b"salt"; + + /// Replaces lowercase letters with small caps. + pub const SMALL_CAPS: [u8; 4] = *b"smcp"; + + /// Replaces uppercase letters with small caps. + pub const CAPS_TO_SMALL_CAPS: [u8; 4] = *b"c2sc"; + + /// Replaces characters with swash versions (often decorative). + pub const SWASH: [u8; 4] = *b"swsh"; + + /// Enables alternate glyphs for large sizes or titles. + pub const TITLING_ALTERNATES: [u8; 4] = *b"titl"; + + /// Converts numbers like 1/2 into true fractions (½). + pub const FRACTIONS: [u8; 4] = *b"frac"; + + /// Formats characters like 1st, 2nd properly. + pub const ORDINALS: [u8; 4] = *b"ordn"; + + /// Uses a slashed version of zero (0) to differentiate from O. + pub const SLASHED_ZERO: [u8; 4] = *b"ordn"; + + /// Replaces figures with superscript figures, e.g. for indicating footnotes. + pub const SUPERSCRIPT: [u8; 4] = *b"sups"; + + /// Replaces figures with subscript figures. + pub const SUBSCRIPT: [u8; 4] = *b"subs"; + + /// Changes numbers to "oldstyle" form, which fit better in the flow of sentences or other text. + pub const OLDSTYLE_FIGURES: [u8; 4] = *b"onum"; + + /// Changes numbers to "lining" form, which are better suited for standalone numbers. When + /// enabled, the bottom of all numbers will be aligned with each other. + pub const LINING_FIGURES: [u8; 4] = *b"lnum"; + + /// Changes numbers to be of proportional width. When enabled, numbers may have varying widths. + pub const PROPORTIONAL_FIGURES: [u8; 4] = *b"pnum"; + + /// Changes numbers to be of uniform (tabular) width. When enabled, all numbers will have the + /// same width. + pub const TABULAR_FIGURES: [u8; 4] = *b"tnum"; + + /// Varies the stroke thickness. Values must be in the range of 0 to 1000. + pub const WEIGHT: [u8; 4] = *b"wght"; + + /// Varies the width of text from narrower to wider. Must be a value greater than 0. A value of + /// 100 is typically considered standard width. + pub const WIDTH: [u8; 4] = *b"wdth"; + + /// Varies between upright and slanted text. Must be a value greater than -90 and less than +90. + /// A value of 0 is upright. + pub const SLANT: [u8; 4] = *b"slnt"; + + /// Create a new [`FontFeaturesBuilder`]. + pub fn builder() -> FontFeaturesBuilder { + FontFeaturesBuilder::default() + } +} + +/// A builder for [`FontFeatures`]. +#[derive(Clone, Default)] +pub struct FontFeaturesBuilder { + features: Vec<([u8; 4], u32)>, +} + +impl FontFeaturesBuilder { + /// Enable an OpenType feature. + /// + /// Most OpenType features are on/off switches, so this is a convenience method that sets the + /// feature's value to "1" (enabled). For non-boolean features, see [`FontFeaturesBuilder::set`]. + pub fn enable(self, feature: [u8; 4]) -> Self { + self.set(feature, 1) + } + + /// Set an OpenType feature to a specific value. + /// + /// For most features, the [`FontFeaturesBuilder::enable`] method should be used instead. A few + /// features, such as "wght", take numeric values, so this method may be used for these cases. + pub fn set(mut self, feature: [u8; 4], value: u32) -> Self { + self.features.push((feature, value)); + self + } + + /// Build a [`FontFeatures`] from the values set within this builder. + pub fn build(self) -> FontFeatures { + FontFeatures { + features: self.features, + } + } +} + +/// Allow [`FontFeatures`] to be built from a list. This is suitable for the standard case when each +/// listed feature is a boolean type. If any features require a numeric value (like "wght"), use +/// [`FontFeaturesBuilder`] instead. +impl From for FontFeatures +where + T: IntoIterator, +{ + fn from(value: T) -> Self { + FontFeatures { + features: value.into_iter().map(|x| (x, 1)).collect(), + } + } +} + +impl From<&FontFeatures> for cosmic_text::FontFeatures { + fn from(font_features: &FontFeatures) -> Self { + cosmic_text::FontFeatures { + features: font_features + .features + .iter() + .map(|(tag, value)| cosmic_text::Feature { + tag: cosmic_text::FeatureTag::new(tag), + value: *value, + }) + .collect(), + } + } +} + /// Specifies the height of each line of text for `Text` and `Text2d` /// /// Default is 1.2x the font size diff --git a/examples/ui/text.rs b/examples/ui/text.rs index 8bf34cc96ee7c..85dc264c4e97b 100644 --- a/examples/ui/text.rs +++ b/examples/ui/text.rs @@ -7,6 +7,7 @@ use bevy::{ color::palettes::css::GOLD, diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin}, prelude::*, + text::FontFeatures, }; fn main() { @@ -88,6 +89,68 @@ fn setup(mut commands: Commands, asset_server: Res) { FpsText, )); + // Text with OpenType features + let opentype_font_handle = asset_server.load("fonts/EBGaramond12-Regular.otf"); + commands + .spawn(( + Node { + margin: UiRect::all(Val::Px(12.0)), + position_type: PositionType::Absolute, + top: Val::Px(5.0), + right: Val::Px(5.0), + ..default() + }, + Text::new("Opentype features:\n"), + TextFont { + font: opentype_font_handle.clone(), + font_size: 32.0, + ..default() + }, + )) + .with_children(|parent| { + let text_rows = [ + ("Smallcaps: ", FontFeatures::SMALL_CAPS, "Hello World"), + ( + "Ligatures: ", + FontFeatures::STANDARD_LIGATURES, + "fi fl ff ffi ffl", + ), + ("Fractions: ", FontFeatures::FRACTIONS, "12/134"), + ("Superscript: ", FontFeatures::SUPERSCRIPT, "Up here!"), + ("Subscript: ", FontFeatures::SUBSCRIPT, "Down here!"), + ( + "Oldstyle figures: ", + FontFeatures::OLDSTYLE_FIGURES, + "1234567890", + ), + ( + "Lining figures: ", + FontFeatures::LINING_FIGURES, + "1234567890", + ), + ]; + + for (title, feature, text) in text_rows { + parent.spawn(( + TextSpan::new(title), + TextFont { + font: opentype_font_handle.clone(), + font_size: 24.0, + ..default() + }, + )); + parent.spawn(( + TextSpan::new(format!("{text}\n")), + TextFont { + font: opentype_font_handle.clone(), + font_size: 24.0, + font_features: FontFeatures::builder().enable(feature).build(), + ..default() + }, + )); + } + }); + #[cfg(feature = "default_font")] commands.spawn(( // Here we are able to call the `From` method instead of creating a new `TextSection`. diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000000000..c919097261f26 --- /dev/null +++ b/flake.lock @@ -0,0 +1,46 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1746328495, + "narHash": "sha256-uKCfuDs7ZM3QpCE/jnfubTg459CnKnJG/LwqEVEdEiw=", + "rev": "979daf34c8cacebcd917d540070b52a3c2b9b16e", + "revCount": 793735, + "type": "tarball", + "url": "https://api.flakehub.com/f/pinned/NixOS/nixpkgs/0.1.793735%2Brev-979daf34c8cacebcd917d540070b52a3c2b9b16e/01969d23-5ba8-7fc5-8c51-ca8a03c73413/source.tar.gz" + }, + "original": { + "type": "tarball", + "url": "https://flakehub.com/f/NixOS/nixpkgs/0.1.%2A.tar.gz" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs", + "rust-overlay": "rust-overlay" + } + }, + "rust-overlay": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1746412651, + "narHash": "sha256-wwyhceL2urIUIhHtTS8QmRtxAigPBBnTWalxYf5h1uI=", + "owner": "oxalica", + "repo": "rust-overlay", + "rev": "ce79bb52eb023f71a03e88cb36c66f35c6668a95", + "type": "github" + }, + "original": { + "owner": "oxalica", + "repo": "rust-overlay", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/release-content/release-notes/opentype_font_features.md b/release-content/release-notes/opentype_font_features.md new file mode 100644 index 0000000000000..942e4074fa6ee --- /dev/null +++ b/release-content/release-notes/opentype_font_features.md @@ -0,0 +1,41 @@ +--- +title: OpenType Font Features +authors: ["@hansler"] +pull_requests: [19020] +--- + +OpenType font features allow fine-grained control over how text is displayed, including [ligatures](https://en.wikipedia.org/wiki/Ligature_(writing)), [small caps](https://en.wikipedia.org/wiki/Small_caps), and [many more](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist). + +These features can now be used in Bevy, allowing users to add typographic polish (like discretionary ligatures and oldstyle numerals) to their UI. It also allows complex scripts like Arabic or Devanagari to render more correctly with their intended ligatures. + +Example usage: + +```rust +commands.spawn(( + TextSpan::new("Ligatures: ff, fi, fl, ffi, ffl"), + TextFont { + font: opentype_font_handle, + font_features: FontFeatures::builder() + .enable(FontFeatures::STANDARD_LIGATURES) + .set(FontFeatures::WIDTH, 300) + .build(), + ..default() + }, +)); +``` + +FontFeatures can also be constructed from a list: + +```rust +TextFont { + font: opentype_font_handle, + font_features: [ + FontFeatures::STANDARD_LIGATURES, + FontFeatures::STYLISTIC_ALTERNATES, + FontFeatures::SLASHED_ZERO + ].into(), + ..default() +} +``` + +Note that OpenType font features are only available for `.otf` fonts that support them, and different fonts may support different subsets of OpenType features. diff --git a/typos.toml b/typos.toml index e3a5c2bf4a8d1..11f77f6d47897 100644 --- a/typos.toml +++ b/typos.toml @@ -36,4 +36,5 @@ extend-ignore-re = [ "\\bmetalness\\b", # Rendering term (metallicity) "\\bNDKs\\b", # NDK - Native Development Kit "\\bPNGs\\b", # PNG - Portable Network Graphics file format + "b\"wdth\"", # OpenType feature identifier for "width" ]