This commit is contained in:
John Hansler 2025-07-14 12:09:38 +01:00 committed by GitHub
commit 0342812ea8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 365 additions and 0 deletions

View File

@ -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.

Binary file not shown.

View File

@ -545,6 +545,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()))
}

View File

@ -302,6 +302,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 {
@ -346,11 +348,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
/// `<https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist>`.
///
/// # 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<T> From<T> for FontFeatures
where
T: IntoIterator<Item = [u8; 4]>,
{
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

View File

@ -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<AssetServer>) {
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`.

View File

@ -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.

View File

@ -37,4 +37,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"
]