mirror of
https://github.com/bevyengine/bevy.git
synced 2026-05-06 06:06:42 -04:00
Add support for OpenType features in text (e.g. ligatures, smallcaps) (#19020)
# Objective OpenType features include things like smallcaps, lined vs old-style numbers, ligatures, stylistic alternate characters, fractional numbers (numerator placed above the denominator), forced monospacing for numbers, and more. There are >100 possible OpenType feature tags; see https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist for the up-to-date list. This provides a way for Bevy users to use these features when using .otf fonts that support them. ## Solution OpenType features are now supported in cosmic-text, so this just provides a way to pass them through. A few notes: - I extended the existing "text" example to showcase a few different OpenType features. - OpenType features are only available for .otf fonts. Since there weren't any existing .otf fonts in the asset/ folder, I've added an SIL-licenced font so that we can showcase this in example code. - I added a "FontFeatures" struct. cosmic-text does already include its own FontFeatures struct, but 1) it does not implement Reflect, which is required by TextFont, and 2) the one I added has a couple ergonomics improvements for the builder methods compared to cosmic-text's. - OpenType font features are four characters strings, e.g. "liga". I considered representing these within an enum, but decided against this since there are hundreds of possible features, and more get added frequently, so this would require quite a bit of ongoing maintenance. Since these features are typically referred to by their four-letter name in documentation, I think the [u8; 4] representation is appropriate, and this mirrors what cosmic-text does as well. I added some consts for commonly used features. ## Testing I extended the "text" example. Run: `cargo run --example text` --- ## Showcase Screenshot:  --------- Co-authored-by: John Hansler <john@hansler.net>
This commit is contained in:
@@ -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.
@@ -667,6 +667,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()))
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ use bevy_derive::{Deref, DerefMut};
|
||||
use bevy_ecs::{prelude::*, reflect::ReflectComponent};
|
||||
use bevy_reflect::prelude::*;
|
||||
use bevy_utils::{default, once};
|
||||
use core::fmt::{Debug, Formatter};
|
||||
use core::str::from_utf8;
|
||||
use cosmic_text::{Buffer, Metrics};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use smallvec::SmallVec;
|
||||
@@ -266,6 +268,8 @@ pub struct TextFont {
|
||||
pub font_size: f32,
|
||||
/// 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 {
|
||||
@@ -304,11 +308,197 @@ impl Default for TextFont {
|
||||
Self {
|
||||
font: Default::default(),
|
||||
font_size: 20.0,
|
||||
font_features: FontFeatures::default(),
|
||||
font_smoothing: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An OpenType font feature tag.
|
||||
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Reflect)]
|
||||
pub struct FontFeatureTag([u8; 4]);
|
||||
|
||||
impl FontFeatureTag {
|
||||
/// Replaces character combinations like fi, fl with ligatures.
|
||||
pub const STANDARD_LIGATURES: FontFeatureTag = FontFeatureTag::new(b"liga");
|
||||
|
||||
/// Enables ligatures based on character context.
|
||||
pub const CONTEXTUAL_LIGATURES: FontFeatureTag = FontFeatureTag::new(b"clig");
|
||||
|
||||
/// Enables optional ligatures for stylistic use (e.g., ct, st).
|
||||
pub const DISCRETIONARY_LIGATURES: FontFeatureTag = FontFeatureTag::new(b"dlig");
|
||||
|
||||
/// Adjust glyph shapes based on surrounding letters.
|
||||
pub const CONTEXTUAL_ALTERNATES: FontFeatureTag = FontFeatureTag::new(b"calt");
|
||||
|
||||
/// Use alternate glyph designs.
|
||||
pub const STYLISTIC_ALTERNATES: FontFeatureTag = FontFeatureTag::new(b"salt");
|
||||
|
||||
/// Replaces lowercase letters with small caps.
|
||||
pub const SMALL_CAPS: FontFeatureTag = FontFeatureTag::new(b"smcp");
|
||||
|
||||
/// Replaces uppercase letters with small caps.
|
||||
pub const CAPS_TO_SMALL_CAPS: FontFeatureTag = FontFeatureTag::new(b"c2sc");
|
||||
|
||||
/// Replaces characters with swash versions (often decorative).
|
||||
pub const SWASH: FontFeatureTag = FontFeatureTag::new(b"swsh");
|
||||
|
||||
/// Enables alternate glyphs for large sizes or titles.
|
||||
pub const TITLING_ALTERNATES: FontFeatureTag = FontFeatureTag::new(b"titl");
|
||||
|
||||
/// Converts numbers like 1/2 into true fractions (½).
|
||||
pub const FRACTIONS: FontFeatureTag = FontFeatureTag::new(b"frac");
|
||||
|
||||
/// Formats characters like 1st, 2nd properly.
|
||||
pub const ORDINALS: FontFeatureTag = FontFeatureTag::new(b"ordn");
|
||||
|
||||
/// Uses a slashed version of zero (0) to differentiate from O.
|
||||
pub const SLASHED_ZERO: FontFeatureTag = FontFeatureTag::new(b"ordn");
|
||||
|
||||
/// Replaces figures with superscript figures, e.g. for indicating footnotes.
|
||||
pub const SUPERSCRIPT: FontFeatureTag = FontFeatureTag::new(b"sups");
|
||||
|
||||
/// Replaces figures with subscript figures.
|
||||
pub const SUBSCRIPT: FontFeatureTag = FontFeatureTag::new(b"subs");
|
||||
|
||||
/// Changes numbers to "oldstyle" form, which fit better in the flow of sentences or other text.
|
||||
pub const OLDSTYLE_FIGURES: FontFeatureTag = FontFeatureTag::new(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: FontFeatureTag = FontFeatureTag::new(b"lnum");
|
||||
|
||||
/// Changes numbers to be of proportional width. When enabled, numbers may have varying widths.
|
||||
pub const PROPORTIONAL_FIGURES: FontFeatureTag = FontFeatureTag::new(b"pnum");
|
||||
|
||||
/// Changes numbers to be of uniform (tabular) width. When enabled, all numbers will have the
|
||||
/// same width.
|
||||
pub const TABULAR_FIGURES: FontFeatureTag = FontFeatureTag::new(b"tnum");
|
||||
|
||||
/// Varies the stroke thickness. Values must be in the range of 0 to 1000.
|
||||
pub const WEIGHT: FontFeatureTag = FontFeatureTag::new(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: FontFeatureTag = FontFeatureTag::new(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: FontFeatureTag = FontFeatureTag::new(b"slnt");
|
||||
|
||||
/// Create a new [`FontFeatureTag`] from raw bytes.
|
||||
pub const fn new(src: &[u8; 4]) -> Self {
|
||||
Self(*src)
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for FontFeatureTag {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
||||
// OpenType tags are always ASCII, so this match will succeed for valid tags. This gives us
|
||||
// human-readable debug output, e.g. FontFeatureTag("liga").
|
||||
match from_utf8(&self.0) {
|
||||
Ok(s) => write!(f, "FontFeatureTag(\"{}\")", s),
|
||||
Err(_) => write!(f, "FontFeatureTag({:?})", self.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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::{FontFeatureTag, FontFeatures};
|
||||
///
|
||||
/// // Create using the builder
|
||||
/// let font_features = FontFeatures::builder()
|
||||
/// .enable(FontFeatureTag::STANDARD_LIGATURES)
|
||||
/// .set(FontFeatureTag::WEIGHT, 300)
|
||||
/// .build();
|
||||
///
|
||||
/// // Create from a list
|
||||
/// let more_font_features: FontFeatures = [
|
||||
/// FontFeatureTag::STANDARD_LIGATURES,
|
||||
/// FontFeatureTag::OLDSTYLE_FIGURES,
|
||||
/// FontFeatureTag::TABULAR_FIGURES
|
||||
/// ].into();
|
||||
/// ```
|
||||
#[derive(Clone, Debug, Default, Reflect, PartialEq)]
|
||||
pub struct FontFeatures {
|
||||
features: Vec<(FontFeatureTag, u32)>,
|
||||
}
|
||||
|
||||
impl FontFeatures {
|
||||
/// Create a new [`FontFeaturesBuilder`].
|
||||
pub fn builder() -> FontFeaturesBuilder {
|
||||
FontFeaturesBuilder::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A builder for [`FontFeatures`].
|
||||
#[derive(Clone, Default)]
|
||||
pub struct FontFeaturesBuilder {
|
||||
features: Vec<(FontFeatureTag, 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_tag: FontFeatureTag) -> Self {
|
||||
self.set(feature_tag, 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_tag: FontFeatureTag, value: u32) -> Self {
|
||||
self.features.push((feature_tag, 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 = FontFeatureTag>,
|
||||
{
|
||||
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.0),
|
||||
value: *value,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Specifies the height of each line of text for `Text` and `Text2d`
|
||||
///
|
||||
/// Default is 1.2x the font size
|
||||
|
||||
@@ -26,6 +26,7 @@ fn main() {
|
||||
font: default(),
|
||||
// We could also disable font smoothing,
|
||||
font_smoothing: FontSmoothing::default(),
|
||||
..default()
|
||||
},
|
||||
// We can also change color of the overlay
|
||||
text_color: OverlayColor::GREEN,
|
||||
|
||||
+63
-1
@@ -7,7 +7,7 @@ use bevy::{
|
||||
color::palettes::css::GOLD,
|
||||
diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin},
|
||||
prelude::*,
|
||||
text::Underline,
|
||||
text::{FontFeatureTag, FontFeatures, Underline},
|
||||
};
|
||||
|
||||
fn main() {
|
||||
@@ -90,6 +90,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: ", FontFeatureTag::SMALL_CAPS, "Hello World"),
|
||||
(
|
||||
"Ligatures: ",
|
||||
FontFeatureTag::STANDARD_LIGATURES,
|
||||
"fi fl ff ffi ffl",
|
||||
),
|
||||
("Fractions: ", FontFeatureTag::FRACTIONS, "12/134"),
|
||||
("Superscript: ", FontFeatureTag::SUPERSCRIPT, "Up here!"),
|
||||
("Subscript: ", FontFeatureTag::SUBSCRIPT, "Down here!"),
|
||||
(
|
||||
"Oldstyle figures: ",
|
||||
FontFeatureTag::OLDSTYLE_FIGURES,
|
||||
"1234567890",
|
||||
),
|
||||
(
|
||||
"Lining figures: ",
|
||||
FontFeatureTag::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`.
|
||||
|
||||
@@ -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(FontFeatureTag::STANDARD_LIGATURES)
|
||||
.set(FontFeatureTag::WIDTH, 300)
|
||||
.build(),
|
||||
..default()
|
||||
},
|
||||
));
|
||||
```
|
||||
|
||||
FontFeatures can also be constructed from a list:
|
||||
|
||||
```rust
|
||||
TextFont {
|
||||
font: opentype_font_handle,
|
||||
font_features: [
|
||||
FontFeatureTag::STANDARD_LIGATURES,
|
||||
FontFeatureTag::STYLISTIC_ALTERNATES,
|
||||
FontFeatureTag::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.
|
||||
@@ -38,4 +38,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"
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user