Clean up glyph rasterization

This commit is contained in:
meehl committed 2026-08-26 14:41:32 +02:00
1 parent 963a9ba1d1
commit a678c8148d
6 files changed
+114 -122

No files matched your search

-1
View File
@@ -4,7 +4,6 @@ pub struct LogicalScreenSpace;
pub struct PhysicalScreenSpace;
pub type LogicalPoint<T> = Point<T, LogicalScreenSpace>;
pub type LogicalVector<T> = Vector<T, LogicalScreenSpace>;
pub type LogicalSize<T> = Size<T, LogicalScreenSpace>;
pub type LogicalRect<T> = Rect<T, LogicalScreenSpace>;
pub type LogicalQuad<T> = Quad<T, LogicalScreenSpace>;
+8 -5
View File
@@ -1,9 +1,12 @@
use crate::{
color::Srgba,
dpi::{LogicalVector, ScaleFactor},
dpi::ScaleFactor,
fonts::{
atlas::FontAtlas, glyph_key::SubpixelBin, layout::PositionedGlyph,
layout_cache::LayoutCache, rasterizer::GlyphRasterizer,
atlas::FontAtlas,
glyph_key::SubpixelBin,
layout::{LayoutVector, PositionedGlyph},
layout_cache::LayoutCache,
rasterizer::GlyphRasterizer,
},
renderer::image::ImageDelta,
util::calculate_hash,
@@ -176,7 +179,7 @@ impl Fonts {
.rasterize_glyph_run(
&mut self.atlas,
&run,
LogicalVector::new(horizontal_offset, 0.0),
LayoutVector::new(horizontal_offset, 0.0),
ScaleFactor::identity(),
)
.for_each(|_| {});
@@ -228,7 +231,7 @@ impl Fonts {
parley_layout.break_all_lines(None);
// extra offset applied to each glyph to get position relative to layout origin
let mut glyph_offset = LogicalVector::new(0.0, 0.0);
let mut glyph_offset = LayoutVector::new(0.0, 0.0);
if let Some(alignment) = job.alignment {
let alignment = match alignment {
Alignment::Min => parley::Alignment::Start,
+28 -1
View File
@@ -2,6 +2,7 @@ use std::num::NonZeroU32;
use crate::{
color::Srgba,
dpi::PhysicalSize,
math::{Point, Rect, Scale, Size},
renderer::{
image::{DataOrder, ImageData, ImageDelta},
@@ -74,7 +75,7 @@ impl FontAtlas {
}
/// Allocates a new glyph
pub fn allocate(&mut self, requested_size: FontAtlasSize) -> AllocatedGlyph<'_> {
fn allocate(&mut self, requested_size: FontAtlasSize) -> AllocatedGlyph<'_> {
const PADDING: u32 = 1;
let mut idx = self.layers.len() - 1;
@@ -150,4 +151,30 @@ impl FontAtlas {
TextureOptions::LINEAR,
))
}
pub fn write_mask(
&mut self,
image: &swash::scale::image::Image,
) -> (PhysicalSize<u32>, UvRect, u32) {
debug_assert!(matches!(image.content, swash::scale::image::Content::Mask));
let size = Size::new(image.placement.width, image.placement.height);
let mut allocation = self.allocate(size);
let mut i = 0;
for y in 0..size.height {
for x in 0..size.width {
let a = image.data[i];
// SAFETY: allocated atlas region and swash image have the same size
unsafe {
allocation
.sub_image
.unsafe_put_pixel(x, y, Srgba::new(255, 255, 255, a).into())
};
i += 1;
}
}
(size.cast_unit(), allocation.uv, allocation.layer_idx)
}
}
+13 -11
View File
@@ -1,7 +1,9 @@
use ordered_float::OrderedFloat;
use parley::Glyph;
use crate::{dpi::PhysicalPoint, fonts::style_cache::StyleId};
use crate::{
dpi::PhysicalPoint,
fonts::{layout::LayoutPoint, style_cache::StyleId},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GlyphKey {
@@ -12,25 +14,25 @@ pub struct GlyphKey {
}
impl GlyphKey {
pub fn from_glyph(
glyph: &Glyph,
pub fn from_position(
position: LayoutPoint<f32>,
glyph_id: u32,
style_id: StyleId,
scale_factor: f32,
) -> (Self, PhysicalPoint<i32>) {
// Use subpixel binning for x coordinate
let (x, x_bin) = SubpixelBin::<4>::new(glyph.x * scale_factor);
// No binning for y coordinate, just rounding
let y = (glyph.y * scale_factor).round() as i32;
let glyph_pos = PhysicalPoint::new(x, y);
// x: use subpixel binning so bitmap encodes sub-pixel position
let (x, x_bin) = SubpixelBin::<4>::new(position.x * scale_factor);
// y: just rounded. not much benefit from sub-pixel vertical positioning
let y = (position.y * scale_factor).round() as i32;
(
Self {
glyph_id: glyph.id as u16,
glyph_id: glyph_id as u16,
style_id,
x_bin,
scale_factor: OrderedFloat(scale_factor),
},
glyph_pos,
PhysicalPoint::new(x, y),
)
}
+3 -1
View File
@@ -1,7 +1,7 @@
use crate::{
color::Srgba,
dpi::{LogicalPoint, LogicalScreenSpace},
math::{Rect, Translation},
math::{Point, Rect, Translation, Vector},
uv::UvRect,
};
use ordered_float::OrderedFloat;
@@ -10,6 +10,8 @@ use parley::{FontFamily, FontFamilyName};
// All coordinates relative to layout origin
pub struct LayoutSpace;
pub type LayoutPoint<T> = Point<T, LayoutSpace>;
pub type LayoutVector<T> = Vector<T, LayoutSpace>;
pub type LayoutRect<T> = Rect<T, LayoutSpace>;
pub type LayoutToLogical = Translation<f32, LayoutSpace, LogicalScreenSpace>;
+62 -103
View File
@@ -1,12 +1,15 @@
use crate::{
color::Srgba,
dpi::{LogicalVector, PhysicalPoint, PhysicalRect, PhysicalSize, PhysicalVector, ScaleFactor},
fonts::{atlas::FontAtlas, glyph_key::GlyphKey, layout::LayoutRect, style_cache::StyleCache},
math::Size,
dpi::{PhysicalRect, PhysicalSize, PhysicalVector, ScaleFactor},
fonts::{
atlas::FontAtlas,
glyph_key::GlyphKey,
layout::{LayoutPoint, LayoutRect, LayoutVector},
style_cache::StyleCache,
},
uv::UvRect,
};
use ahash::HashMap;
use image::GenericImage;
use parley::{FontData, GlyphRun};
use swash::zeno;
@@ -32,33 +35,12 @@ pub struct RasterizedGlyph {
pub color: Srgba,
}
impl RasterizedGlyph {
fn from_cached(
cached: CachedGlyph,
position: PhysicalPoint<i32>,
color: Srgba,
scale_factor: ScaleFactor<f32>,
) -> Self {
let glyph_rect = PhysicalRect::from_origin_and_size(
position + cached.baseline_offset,
cached.size.cast(),
);
RasterizedGlyph {
rect: (glyph_rect.cast() / scale_factor).cast_unit(),
uv: cached.uv,
texture_layer_idx: cached.texture_layer_idx,
color,
}
}
}
pub struct GlyphRasterizer {
scale_context: swash::scale::ScaleContext,
swash_keys: HashMap<(FontBlobId, FontIndex), (SwashFontOffset, swash::CacheKey)>,
style_cache: StyleCache,
cached_glyphs: HashMap<GlyphKey, Option<CachedGlyph>>,
// scratch image buffer used to write bitmap data into
/// Scratch image buffer used to temporarily write bitmap data into
scratch: swash::scale::image::Image,
}
@@ -93,14 +75,14 @@ impl GlyphRasterizer {
}
}
/// Rasterizes glyph run and returns the placement and UV for each glyph.
/// Can return `None` if glyph doesn't take up any space (e.g. whitespace).
/// Rasterizes a glyph run and returns the placement and UV for each glyph.
/// Returns `None` for glyphs that doesn't take up visible space (e.g. whitespace).
pub fn rasterize_glyph_run<'slf: 'run, 'run, 'atlas>(
&'slf mut self,
atlas: &'atlas mut FontAtlas,
glyph_run: &'run GlyphRun<'_, Srgba>,
// additional offset relative to layout origin
glyph_offset: LogicalVector<f32>,
layout_offset: LayoutVector<f32>,
scale_factor: ScaleFactor<f32>,
) -> impl Iterator<Item = Option<RasterizedGlyph>> + use<'slf, 'run, 'atlas> {
let run = glyph_run.run();
@@ -128,91 +110,68 @@ impl GlyphRasterizer {
let image = &mut self.scratch;
let cached_glyphs = &mut self.cached_glyphs;
glyph_run.positioned_glyphs().map(move |mut glyph| {
glyph.x += glyph_offset.x;
glyph.y += glyph_offset.y;
let (glyph_key, glyph_pos) = GlyphKey::from_glyph(&glyph, style_id, scale_factor.get());
glyph_run.positioned_glyphs().map(move |glyph| {
let layout_position = LayoutPoint::new(glyph.x, glyph.y) + layout_offset;
if let Some(cached_glyph) = cached_glyphs.get(&glyph_key) {
return cached_glyph.map(|cached| {
RasterizedGlyph::from_cached(cached, glyph_pos, color, scale_factor)
});
}
let (glyph_key, pixel_position) =
GlyphKey::from_position(layout_position, glyph.id, style_id, scale_factor.get());
let fract_offset = glyph_key.get_fractional_offset();
let cached = *cached_glyphs.entry(glyph_key).or_insert_with(|| {
rasterize_glyph(&mut scaler, image, atlas, glyph.id, &glyph_key, skew)
});
image.clear();
let did_render = swash::scale::Render::new(&[
swash::scale::Source::ColorOutline(0),
swash::scale::Source::ColorBitmap(swash::scale::StrikeWith::BestFit),
swash::scale::Source::Outline,
])
.format(zeno::Format::Alpha)
.transform(skew.map(|skew| {
zeno::Transform::skew(zeno::Angle::from_degrees(skew), zeno::Angle::ZERO)
}))
.offset(fract_offset)
.render_into(&mut scaler, glyph.id as u16, image);
cached.map(|cached| {
// apply the baseline offset to get the actual bitmap position
let bitmap_top_left = pixel_position + cached.baseline_offset;
let physical_rect =
PhysicalRect::from_origin_and_size(bitmap_top_left, cached.size.cast());
if !did_render || image.placement.width == 0 || image.placement.height == 0 {
cached_glyphs.insert(glyph_key, None);
return None;
};
let (glyph_size, atlas_uv, atlas_layer_idx) = write_to_atlas(image, atlas);
let cached_glyph = CachedGlyph {
size: glyph_size,
uv: atlas_uv,
texture_layer_idx: atlas_layer_idx,
// swash uses `Origin::BottomLeft` so we need to negate the vertical component
baseline_offset: PhysicalVector::new(image.placement.left, -image.placement.top),
};
cached_glyphs.insert(glyph_key, Some(cached_glyph));
Some(RasterizedGlyph::from_cached(
cached_glyph,
glyph_pos,
color,
scale_factor,
))
RasterizedGlyph {
rect: (physical_rect.cast() / scale_factor).cast_unit(),
uv: cached.uv,
texture_layer_idx: cached.texture_layer_idx,
color,
}
})
})
}
}
/// Writes rasterized glyph to atlas and returns the UV coordinates of it
fn write_to_atlas(
image: &swash::scale::image::Image,
/// Renders glyph's bitmap into the atlas
fn rasterize_glyph(
scaler: &mut swash::scale::Scaler,
image: &mut swash::scale::image::Image,
atlas: &mut FontAtlas,
) -> (PhysicalSize<u32>, UvRect, u32) {
let size = Size::new(image.placement.width, image.placement.height);
let mut allocated_glyph = atlas.allocate(size);
glyph_id: u32,
glyph_key: &GlyphKey,
skew: Option<f32>,
) -> Option<CachedGlyph> {
image.clear();
match image.content {
swash::scale::image::Content::Mask => {
let mut i = 0;
for y in 0..image.placement.height {
for x in 0..image.placement.width {
let a = image.data[i];
// SAFETY: allocated atlas region and swash image have the same size
unsafe {
allocated_glyph.sub_image.unsafe_put_pixel(
x,
y,
Srgba::new(255, 255, 255, a).into(),
)
};
i += 1;
}
}
}
_ => unreachable!(),
let did_render = swash::scale::Render::new(&[
swash::scale::Source::ColorOutline(0),
swash::scale::Source::ColorBitmap(swash::scale::StrikeWith::BestFit),
swash::scale::Source::Outline,
])
.format(zeno::Format::Alpha)
.transform(
skew.map(|skew| zeno::Transform::skew(zeno::Angle::from_degrees(skew), zeno::Angle::ZERO)),
)
.offset(glyph_key.get_fractional_offset())
.render_into(scaler, glyph_id as u16, image);
if !did_render || image.placement.width == 0 || image.placement.height == 0 {
return None;
};
(
size.cast_unit(),
allocated_glyph.uv,
allocated_glyph.layer_idx,
)
let (size, uv, layer_idx) = atlas.write_mask(image);
Some(CachedGlyph {
size,
uv,
texture_layer_idx: layer_idx,
// swash uses `Origin::BottomLeft` so we need to negate the vertical component
baseline_offset: PhysicalVector::new(image.placement.left, -image.placement.top),
})
}