Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate to cosmic-text #8808

Closed
wants to merge 32 commits into from
Closed
Show file tree
Hide file tree
Changes from 24 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
c2b47f7
make text update lazier in tonemapping example
tigregalis Apr 29, 2023
c6c49aa
implemented cosmic_text side-by-side
tigregalis May 2, 2023
643fc6a
make text update lazier in tonemapping ex. try 2
tigregalis May 8, 2023
9118acc
introduce `BidiParagraphs` iterator
tigregalis May 8, 2023
fbba4c7
update `FontAtlasSet` `iter`, `has_glyph` methods
tigregalis May 12, 2023
7036d05
collect positioned glyphs rather than push vec
tigregalis May 12, 2023
6c5b506
remove unnecessary position calcs
tigregalis May 12, 2023
b759c85
implement horizontal text alignment
tigregalis May 12, 2023
aa37e0d
split up `TextPipeline::queue_text`
tigregalis May 12, 2023
1cf10ae
implement text measure
tigregalis May 15, 2023
ff2aeab
remove old implementation, dependencies
tigregalis May 15, 2023
79632d6
tidy up
tigregalis May 16, 2023
85063cf
fix tonemapping example layout bug
tigregalis Jun 3, 2023
86a90b3
update todos
tigregalis Jun 3, 2023
da8cb97
implement font query
tigregalis Jun 3, 2023
297a7a5
add system fonts example
tigregalis Jun 3, 2023
02e317e
promote GlyphAtlasInfoNew to sole GlyphAtlasInfo
tigregalis Jun 3, 2023
8694d48
fix crash from dropped `Handle<FontAtlasSet>`
tigregalis Jun 4, 2023
a424110
expand `FontRef`-related APIs
tigregalis Jun 4, 2023
ff1590a
improve `system_fonts` example
tigregalis Jun 4, 2023
193611d
update examples with `FontRef` not `Handle<Font>`
tigregalis Jun 4, 2023
cbfbfdf
fix lines not breaking when sections end with \n
tigregalis Jun 10, 2023
4b1f6f1
enhance system_fonts example
tigregalis Jun 10, 2023
d8b1afe
fix extra line bug
tigregalis Jun 10, 2023
ce44ab4
replace `(i32, i32, u32, u32)` with `Placement`
tigregalis Jun 11, 2023
ab8df89
extract `(glyph_index, placement)` to `*Location`
tigregalis Jun 11, 2023
117b6c3
replace `Placement` with `IVec2` offset
tigregalis Jun 11, 2023
8696b4e
extract and use `acquire_font_system`
tigregalis Jun 11, 2023
ab56e13
reorganize code and add more docs
tigregalis Jun 11, 2023
b25d8e7
renamed cosmic text re-exports
tigregalis Jun 11, 2023
da0a81f
incorporate docs suggestions
tigregalis Jun 11, 2023
0e59b11
fix doctests
tigregalis Jun 27, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,6 @@ wayland = ["bevy_internal/wayland"]
# X11 display server support
x11 = ["bevy_internal/x11"]

# Enable rendering of font glyphs using subpixel accuracy
subpixel_glyph_atlas = ["bevy_internal/subpixel_glyph_atlas"]

# Enable systems that allow for automated testing on CI
bevy_ci_testing = ["bevy_internal/bevy_ci_testing"]

Expand Down Expand Up @@ -1832,6 +1829,16 @@ description = "Demonstrates how the to use the size constraints to control the s
category = "UI (User Interface)"
wasm = true

[[example]]
name = "system_fonts"
path = "examples/ui/system_fonts.rs"

[package.metadata.example.system_fonts]
name = "System Fonts"
description = "Demonstrates using system fonts."
category = "UI (User Interface)"
wasm = false

[[example]]
name = "text"
path = "examples/ui/text.rs"
Expand Down
3 changes: 0 additions & 3 deletions crates/bevy_internal/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,6 @@ serialize = ["bevy_core/serialize", "bevy_input/serialize", "bevy_time/serialize
wayland = ["bevy_winit/wayland"]
x11 = ["bevy_winit/x11"]

# enable rendering of font glyphs using subpixel accuracy
subpixel_glyph_atlas = ["bevy_text/subpixel_glyph_atlas"]

# Optimise for WebGL2
webgl = ["bevy_core_pipeline?/webgl", "bevy_pbr?/webgl", "bevy_render?/webgl"]

Expand Down
6 changes: 3 additions & 3 deletions crates/bevy_text/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ license = "MIT OR Apache-2.0"
keywords = ["bevy"]

[features]
subpixel_glyph_atlas = []
default_font = []

[dependencies]
Expand All @@ -27,7 +26,8 @@ bevy_utils = { path = "../bevy_utils", version = "0.11.0-dev" }

# other
anyhow = "1.0.4"
ab_glyph = "0.2.6"
glyph_brush_layout = "0.2.1"
cosmic-text = "0.8.0"
thiserror = "1.0"
serde = {version = "1", features = ["derive"]}
sys-locale = "0.3.0"
unicode-bidi = "0.3.13"
5 changes: 3 additions & 2 deletions crates/bevy_text/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use ab_glyph::GlyphId;
use thiserror::Error;

#[derive(Debug, PartialEq, Eq, Error)]
pub enum TextError {
#[error("font not found")]
NoSuchFont,
#[error("failed to add glyph to newly-created atlas {0:?}")]
FailedToAddGlyph(GlyphId),
FailedToAddGlyph(u16),
#[error("font system mutex could not be acquired or is poisoned")]
FailedToAcquireMutex,
}
74 changes: 48 additions & 26 deletions crates/bevy_text/src/font.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use ab_glyph::{FontArc, FontVec, InvalidFont, OutlinedGlyph};
use bevy_reflect::{TypePath, TypeUuid};
use bevy_render::{
render_resource::{Extent3d, TextureDimension, TextureFormat},
Expand All @@ -8,38 +7,61 @@ use bevy_render::{
#[derive(Debug, TypeUuid, TypePath, Clone)]
#[uuid = "97059ac6-c9ba-4da9-95b6-bed82c3ce198"]
pub struct Font {
pub font: FontArc,
pub data: std::sync::Arc<Vec<u8>>,
}

impl Font {
pub fn try_from_bytes(font_data: Vec<u8>) -> Result<Self, InvalidFont> {
let font = FontVec::try_from_vec(font_data)?;
let font = FontArc::new(font);
Ok(Font { font })
pub fn from_bytes(font_data: Vec<u8>) -> Self {
// TODO: validate font, restore `try_from_bytes`
Self {
data: std::sync::Arc::new(font_data),
}
}

pub fn get_outlined_glyph_texture(outlined_glyph: OutlinedGlyph) -> Image {
let bounds = outlined_glyph.px_bounds();
let width = bounds.width() as usize;
let height = bounds.height() as usize;
let mut alpha = vec![0.0; width * height];
outlined_glyph.draw(|x, y, v| {
alpha[y as usize * width + x as usize] = v;
});
// TODO: consider moving to pipeline.rs
pub fn get_outlined_glyph_texture(
font_system: &mut cosmic_text::FontSystem,
swash_cache: &mut cosmic_text::SwashCache,
layout_glyph: &cosmic_text::LayoutGlyph,
) -> (Image, i32, i32, u32, u32) {
// TODO: consider using cosmic_text's own caching mechanism
let image = swash_cache
.get_image_uncached(font_system, layout_glyph.cache_key)
// TODO: don't unwrap
.unwrap();

// TODO: make this texture grayscale
Image::new(
Extent3d {
width: width as u32,
height: height as u32,
depth_or_array_layers: 1,
},
TextureDimension::D2,
alpha
let width = image.placement.width;
let height = image.placement.height;

let data = match image.content {
cosmic_text::SwashContent::Mask => image
.data
.iter()
.flat_map(|a| vec![255, 255, 255, (*a * 255.0) as u8])
.collect::<Vec<u8>>(),
TextureFormat::Rgba8UnormSrgb,
.flat_map(|a| [255, 255, 255, *a])
.collect(),
cosmic_text::SwashContent::Color => image.data,
cosmic_text::SwashContent::SubpixelMask => {
// TODO
todo!()
}
};

// TODO: make this texture grayscale
(
Image::new(
Extent3d {
width,
height,
depth_or_array_layers: 1,
},
TextureDimension::D2,
data,
TextureFormat::Rgba8UnormSrgb,
),
image.placement.left,
image.placement.top,
width,
height,
)
}
}
57 changes: 12 additions & 45 deletions crates/bevy_text/src/font_atlas.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use ab_glyph::{GlyphId, Point};
use bevy_asset::{Assets, Handle};
use bevy_math::Vec2;
use bevy_render::{
Expand All @@ -8,40 +7,9 @@ use bevy_render::{
use bevy_sprite::{DynamicTextureAtlasBuilder, TextureAtlas};
use bevy_utils::HashMap;

#[cfg(feature = "subpixel_glyph_atlas")]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct SubpixelOffset {
x: u16,
y: u16,
}

#[cfg(feature = "subpixel_glyph_atlas")]
impl From<Point> for SubpixelOffset {
fn from(p: Point) -> Self {
fn f(v: f32) -> u16 {
((v % 1.) * (u16::MAX as f32)) as u16
}
Self {
x: f(p.x),
y: f(p.y),
}
}
}

#[cfg(not(feature = "subpixel_glyph_atlas"))]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct SubpixelOffset;

#[cfg(not(feature = "subpixel_glyph_atlas"))]
impl From<Point> for SubpixelOffset {
fn from(_: Point) -> Self {
Self
}
}

pub struct FontAtlas {
pub dynamic_texture_atlas_builder: DynamicTextureAtlasBuilder,
pub glyph_to_atlas_index: HashMap<(GlyphId, SubpixelOffset), usize>,
pub glyph_to_atlas_index: HashMap<cosmic_text::CacheKey, (usize, i32, i32, u32, u32)>,
tigregalis marked this conversation as resolved.
Show resolved Hide resolved
pub texture_atlas: Handle<TextureAtlas>,
}

Expand Down Expand Up @@ -71,34 +39,33 @@ impl FontAtlas {

pub fn get_glyph_index(
&self,
glyph_id: GlyphId,
subpixel_offset: SubpixelOffset,
) -> Option<usize> {
self.glyph_to_atlas_index
.get(&(glyph_id, subpixel_offset))
.copied()
cache_key: cosmic_text::CacheKey,
) -> Option<(usize, i32, i32, u32, u32)> {
self.glyph_to_atlas_index.get(&cache_key).copied()
}

pub fn has_glyph(&self, glyph_id: GlyphId, subpixel_offset: SubpixelOffset) -> bool {
self.glyph_to_atlas_index
.contains_key(&(glyph_id, subpixel_offset))
pub fn has_glyph(&self, cache_key: cosmic_text::CacheKey) -> bool {
self.glyph_to_atlas_index.contains_key(&cache_key)
}

pub fn add_glyph(
&mut self,
textures: &mut Assets<Image>,
texture_atlases: &mut Assets<TextureAtlas>,
glyph_id: GlyphId,
subpixel_offset: SubpixelOffset,
cache_key: cosmic_text::CacheKey,
texture: &Image,
left: i32,
top: i32,
width: u32,
height: u32,
) -> bool {
let texture_atlas = texture_atlases.get_mut(&self.texture_atlas).unwrap();
if let Some(index) =
self.dynamic_texture_atlas_builder
.add_texture(texture_atlas, textures, texture)
{
self.glyph_to_atlas_index
.insert((glyph_id, subpixel_offset), index);
.insert(cache_key, (index, left, top, width, height));
true
} else {
false
Expand Down
Loading