Use subpixel glyph positioning and layout linearity

... for offsetting and scaling text
This commit is contained in:
Héctor Ramón Jiménez 2023-06-20 06:22:17 +02:00
parent 8ae4e28013
commit 5bc7cbf5bc
No known key found for this signature in database
GPG key ID: 140CC052C94F138E
10 changed files with 47 additions and 108 deletions

View file

@ -6,18 +6,6 @@ use iced_core::{Font, Point, Size};
use std::borrow::Cow; use std::borrow::Cow;
/// The graphics backend of a [`Renderer`].
///
/// [`Renderer`]: crate::Renderer
pub trait Backend {
/// Trims the measurements cache.
///
/// This method is currently necessary to properly trim the text cache in
/// `iced_wgpu` and `iced_glow` because of limitations in the text rendering
/// pipeline. It will be removed in the future.
fn trim_measurements(&mut self) {}
}
/// A graphics backend that supports text rendering. /// A graphics backend that supports text rendering.
pub trait Text { pub trait Text {
/// The icon font of the backend. /// The icon font of the backend.

View file

@ -41,7 +41,6 @@ pub mod geometry;
pub mod image; pub mod image;
pub use antialiasing::Antialiasing; pub use antialiasing::Antialiasing;
pub use backend::Backend;
pub use compositor::Compositor; pub use compositor::Compositor;
pub use error::Error; pub use error::Error;
pub use gradient::Gradient; pub use gradient::Gradient;

View file

@ -1,5 +1,5 @@
//! Create a renderer from a [`Backend`]. //! Create a renderer from a [`Backend`].
use crate::backend::{self, Backend}; use crate::backend;
use crate::Primitive; use crate::Primitive;
use iced_core::image; use iced_core::image;
@ -16,13 +16,13 @@ use std::marker::PhantomData;
/// A backend-agnostic renderer that supports all the built-in widgets. /// A backend-agnostic renderer that supports all the built-in widgets.
#[derive(Debug)] #[derive(Debug)]
pub struct Renderer<B: Backend, Theme> { pub struct Renderer<B, Theme> {
backend: B, backend: B,
primitives: Vec<Primitive>, primitives: Vec<Primitive>,
theme: PhantomData<Theme>, theme: PhantomData<Theme>,
} }
impl<B: Backend, T> Renderer<B, T> { impl<B, T> Renderer<B, T> {
/// Creates a new [`Renderer`] from the given [`Backend`]. /// Creates a new [`Renderer`] from the given [`Backend`].
pub fn new(backend: B) -> Self { pub fn new(backend: B) -> Self {
Self { Self {
@ -52,10 +52,7 @@ impl<B: Backend, T> Renderer<B, T> {
} }
} }
impl<B, T> iced_core::Renderer for Renderer<B, T> impl<B, T> iced_core::Renderer for Renderer<B, T> {
where
B: Backend,
{
type Theme = T; type Theme = T;
fn layout<Message>( fn layout<Message>(
@ -63,11 +60,7 @@ where
element: &Element<'_, Message, Self>, element: &Element<'_, Message, Self>,
limits: &layout::Limits, limits: &layout::Limits,
) -> layout::Node { ) -> layout::Node {
let layout = element.as_widget().layout(self, limits); element.as_widget().layout(self, limits)
self.backend.trim_measurements();
layout
} }
fn with_layer(&mut self, bounds: Rectangle, f: impl FnOnce(&mut Self)) { fn with_layer(&mut self, bounds: Rectangle, f: impl FnOnce(&mut Self)) {
@ -116,7 +109,7 @@ where
impl<B, T> text::Renderer for Renderer<B, T> impl<B, T> text::Renderer for Renderer<B, T>
where where
B: Backend + backend::Text, B: backend::Text,
{ {
type Font = Font; type Font = Font;
@ -195,7 +188,7 @@ where
impl<B, T> image::Renderer for Renderer<B, T> impl<B, T> image::Renderer for Renderer<B, T>
where where
B: Backend + backend::Image, B: backend::Image,
{ {
type Handle = image::Handle; type Handle = image::Handle;
@ -210,7 +203,7 @@ where
impl<B, T> svg::Renderer for Renderer<B, T> impl<B, T> svg::Renderer for Renderer<B, T>
where where
B: Backend + backend::Svg, B: backend::Svg,
{ {
fn dimensions(&self, handle: &svg::Handle) -> Size<u32> { fn dimensions(&self, handle: &svg::Handle) -> Size<u32> {
self.backend().viewport_dimensions(handle) self.backend().viewport_dimensions(handle)
@ -231,10 +224,7 @@ where
} }
#[cfg(feature = "geometry")] #[cfg(feature = "geometry")]
impl<B, T> crate::geometry::Renderer for Renderer<B, T> impl<B, T> crate::geometry::Renderer for Renderer<B, T> {
where
B: Backend,
{
fn draw(&mut self, layers: Vec<crate::Geometry>) { fn draw(&mut self, layers: Vec<crate::Geometry>) {
self.primitives self.primitives
.extend(layers.into_iter().map(crate::Geometry::into)); .extend(layers.into_iter().map(crate::Geometry::into));

View file

@ -21,12 +21,6 @@ macro_rules! delegate {
}; };
} }
impl iced_graphics::Backend for Backend {
fn trim_measurements(&mut self) {
delegate!(self, backend, backend.trim_measurements());
}
}
impl backend::Text for Backend { impl backend::Text for Backend {
const ICON_FONT: Font = Font::with_name("Iced-Icons"); const ICON_FONT: Font = Font::with_name("Iced-Icons");
const CHECKMARK_ICON: char = '\u{f00c}'; const CHECKMARK_ICON: char = '\u{f00c}';

View file

@ -24,7 +24,7 @@ features = ["tiny-skia"]
[dependencies.cosmic-text] [dependencies.cosmic-text]
git = "https://github.com/hecrj/cosmic-text.git" git = "https://github.com/hecrj/cosmic-text.git"
rev = "e8b10fd675832cb9c1cc9de30922beb4cf883876" rev = "c3cd24dc972bb8fd55d016c81ac9fa637e0a4ada"
[dependencies.twox-hash] [dependencies.twox-hash]
version = "1.6" version = "1.6"

View file

@ -658,12 +658,6 @@ fn adjust_clip_mask(clip_mask: &mut tiny_skia::Mask, bounds: Rectangle) {
); );
} }
impl iced_graphics::Backend for Backend {
fn trim_measurements(&mut self) {
self.text_pipeline.trim_measurement_cache();
}
}
impl backend::Text for Backend { impl backend::Text for Backend {
const ICON_FONT: Font = Font::with_name("Iced-Icons"); const ICON_FONT: Font = Font::with_name("Iced-Icons");
const CHECKMARK_ICON: char = '\u{f00c}'; const CHECKMARK_ICON: char = '\u{f00c}';

View file

@ -14,8 +14,7 @@ use std::sync::Arc;
pub struct Pipeline { pub struct Pipeline {
font_system: RefCell<cosmic_text::FontSystem>, font_system: RefCell<cosmic_text::FontSystem>,
glyph_cache: GlyphCache, glyph_cache: GlyphCache,
measurement_cache: RefCell<Cache>, cache: RefCell<Cache>,
render_cache: Cache,
} }
impl Pipeline { impl Pipeline {
@ -29,8 +28,7 @@ impl Pipeline {
.into_iter(), .into_iter(),
)), )),
glyph_cache: GlyphCache::new(), glyph_cache: GlyphCache::new(),
measurement_cache: RefCell::new(Cache::new()), cache: RefCell::new(Cache::new()),
render_cache: Cache::new(),
} }
} }
@ -55,20 +53,11 @@ impl Pipeline {
pixels: &mut tiny_skia::PixmapMut<'_>, pixels: &mut tiny_skia::PixmapMut<'_>,
clip_mask: Option<&tiny_skia::Mask>, clip_mask: Option<&tiny_skia::Mask>,
) { ) {
let line_height = let line_height = f32::from(line_height.to_absolute(Pixels(size)));
f32::from(line_height.to_absolute(Pixels(size))) * scale_factor;
let bounds = bounds * scale_factor;
let size = size * scale_factor;
let font_system = self.font_system.get_mut(); let font_system = self.font_system.get_mut();
let key = Key { let key = Key {
bounds: { bounds: bounds.size(),
let size = bounds.size();
// TODO: Reuse buffers from layouting
Size::new(size.width.ceil(), size.height.ceil())
},
content, content,
font, font,
size, size,
@ -76,7 +65,7 @@ impl Pipeline {
shaping, shaping,
}; };
let (_, buffer) = self.render_cache.allocate(font_system, key); let (_, buffer) = self.cache.get_mut().allocate(font_system, key);
let (total_lines, max_width) = buffer let (total_lines, max_width) = buffer
.layout_runs() .layout_runs()
@ -85,7 +74,10 @@ impl Pipeline {
(i + 1, buffer.line_w.max(max)) (i + 1, buffer.line_w.max(max))
}); });
let total_height = total_lines as f32 * line_height; let total_height = total_lines as f32 * line_height * scale_factor;
let max_width = max_width * scale_factor;
let bounds = bounds * scale_factor;
let x = match horizontal_alignment { let x = match horizontal_alignment {
alignment::Horizontal::Left => bounds.x, alignment::Horizontal::Left => bounds.x,
@ -99,16 +91,14 @@ impl Pipeline {
alignment::Vertical::Bottom => bounds.y - total_height, alignment::Vertical::Bottom => bounds.y - total_height,
}; };
// TODO: Subpixel glyph positioning
let x = x.round() as i32;
let y = y.round() as i32;
let mut swash = cosmic_text::SwashCache::new(); let mut swash = cosmic_text::SwashCache::new();
for run in buffer.layout_runs() { for run in buffer.layout_runs() {
for glyph in run.glyphs { for glyph in run.glyphs {
let physical_glyph = glyph.physical((x, y), scale_factor);
if let Some((buffer, placement)) = self.glyph_cache.allocate( if let Some((buffer, placement)) = self.glyph_cache.allocate(
glyph.cache_key, physical_glyph.cache_key,
color, color,
font_system, font_system,
&mut swash, &mut swash,
@ -121,8 +111,9 @@ impl Pipeline {
.expect("Create glyph pixel map"); .expect("Create glyph pixel map");
pixels.draw_pixmap( pixels.draw_pixmap(
x + glyph.x_int + placement.left, physical_glyph.x + placement.left,
y - glyph.y_int - placement.top + run.line_y as i32, physical_glyph.y - placement.top
+ (run.line_y * scale_factor).round() as i32,
pixmap, pixmap,
&tiny_skia::PixmapPaint::default(), &tiny_skia::PixmapPaint::default(),
tiny_skia::Transform::identity(), tiny_skia::Transform::identity(),
@ -134,7 +125,7 @@ impl Pipeline {
} }
pub fn trim_cache(&mut self) { pub fn trim_cache(&mut self) {
self.render_cache.trim(); self.cache.get_mut().trim();
self.glyph_cache.trim(); self.glyph_cache.trim();
} }
@ -147,7 +138,7 @@ impl Pipeline {
bounds: Size, bounds: Size,
shaping: Shaping, shaping: Shaping,
) -> (f32, f32) { ) -> (f32, f32) {
let mut measurement_cache = self.measurement_cache.borrow_mut(); let mut measurement_cache = self.cache.borrow_mut();
let line_height = f32::from(line_height.to_absolute(Pixels(size))); let line_height = f32::from(line_height.to_absolute(Pixels(size)));
@ -184,7 +175,7 @@ impl Pipeline {
point: Point, point: Point,
_nearest_only: bool, _nearest_only: bool,
) -> Option<Hit> { ) -> Option<Hit> {
let mut measurement_cache = self.measurement_cache.borrow_mut(); let mut measurement_cache = self.cache.borrow_mut();
let line_height = f32::from(line_height.to_absolute(Pixels(size))); let line_height = f32::from(line_height.to_absolute(Pixels(size)));
@ -204,10 +195,6 @@ impl Pipeline {
Some(Hit::CharOffset(cursor.index)) Some(Hit::CharOffset(cursor.index))
} }
pub fn trim_measurement_cache(&mut self) {
self.measurement_cache.borrow_mut().trim();
}
} }
fn to_family(family: font::Family) -> cosmic_text::Family<'static> { fn to_family(family: font::Family) -> cosmic_text::Family<'static> {

View file

@ -45,7 +45,7 @@ path = "../graphics"
[dependencies.glyphon] [dependencies.glyphon]
version = "0.2" version = "0.2"
git = "https://github.com/hecrj/glyphon.git" git = "https://github.com/hecrj/glyphon.git"
rev = "8dbf36020e5759fa9144517b321372266160113e" rev = "8324f20158a62f8520bad4ed09f6aa5552f8f2a6"
[dependencies.glam] [dependencies.glam]
version = "0.24" version = "0.24"

View file

@ -334,12 +334,6 @@ impl Backend {
} }
} }
impl iced_graphics::Backend for Backend {
fn trim_measurements(&mut self) {
self.text_pipeline.trim_measurement_cache()
}
}
impl backend::Text for Backend { impl backend::Text for Backend {
const ICON_FONT: Font = Font::with_name("Iced-Icons"); const ICON_FONT: Font = Font::with_name("Iced-Icons");
const CHECKMARK_ICON: char = '\u{f00c}'; const CHECKMARK_ICON: char = '\u{f00c}';

View file

@ -18,8 +18,7 @@ pub struct Pipeline {
renderers: Vec<glyphon::TextRenderer>, renderers: Vec<glyphon::TextRenderer>,
atlas: glyphon::TextAtlas, atlas: glyphon::TextAtlas,
prepare_layer: usize, prepare_layer: usize,
measurement_cache: RefCell<Cache>, cache: RefCell<Cache>,
render_cache: Cache,
} }
impl Pipeline { impl Pipeline {
@ -47,8 +46,7 @@ impl Pipeline {
}, },
), ),
prepare_layer: 0, prepare_layer: 0,
measurement_cache: RefCell::new(Cache::new()), cache: RefCell::new(Cache::new()),
render_cache: Cache::new(),
} }
} }
@ -78,25 +76,25 @@ impl Pipeline {
let font_system = self.font_system.get_mut(); let font_system = self.font_system.get_mut();
let renderer = &mut self.renderers[self.prepare_layer]; let renderer = &mut self.renderers[self.prepare_layer];
let cache = self.cache.get_mut();
let keys: Vec<_> = sections let keys: Vec<_> = sections
.iter() .iter()
.map(|section| { .map(|section| {
let (key, _) = self.render_cache.allocate( let (key, _) = cache.allocate(
font_system, font_system,
Key { Key {
content: section.content, content: section.content,
size: section.size * scale_factor, size: section.size,
line_height: f32::from( line_height: f32::from(
section section
.line_height .line_height
.to_absolute(Pixels(section.size)), .to_absolute(Pixels(section.size)),
) * scale_factor, ),
font: section.font, font: section.font,
bounds: Size { bounds: Size {
width: (section.bounds.width * scale_factor).ceil(), width: section.bounds.width,
height: (section.bounds.height * scale_factor) height: section.bounds.height,
.ceil(),
}, },
shaping: section.shaping, shaping: section.shaping,
}, },
@ -113,14 +111,16 @@ impl Pipeline {
.iter() .iter()
.zip(keys.iter()) .zip(keys.iter())
.filter_map(|(section, key)| { .filter_map(|(section, key)| {
let buffer = let buffer = cache.get(key).expect("Get cached buffer");
self.render_cache.get(key).expect("Get cached buffer");
let (max_width, total_height) = measure(buffer);
let x = section.bounds.x * scale_factor; let x = section.bounds.x * scale_factor;
let y = section.bounds.y * scale_factor; let y = section.bounds.y * scale_factor;
let (max_width, total_height) = measure(buffer);
let max_width = max_width * scale_factor;
let total_height = total_height * scale_factor;
let left = match section.horizontal_alignment { let left = match section.horizontal_alignment {
alignment::Horizontal::Left => x, alignment::Horizontal::Left => x,
alignment::Horizontal::Center => x - max_width / 2.0, alignment::Horizontal::Center => x - max_width / 2.0,
@ -142,14 +142,11 @@ impl Pipeline {
let clip_bounds = bounds.intersection(&section_bounds)?; let clip_bounds = bounds.intersection(&section_bounds)?;
// TODO: Subpixel glyph positioning
let left = left.round() as i32;
let top = top.round() as i32;
Some(glyphon::TextArea { Some(glyphon::TextArea {
buffer, buffer,
left, left,
top, top,
scale: scale_factor,
bounds: glyphon::TextBounds { bounds: glyphon::TextBounds {
left: clip_bounds.x as i32, left: clip_bounds.x as i32,
top: clip_bounds.y as i32, top: clip_bounds.y as i32,
@ -227,7 +224,7 @@ impl Pipeline {
pub fn end_frame(&mut self) { pub fn end_frame(&mut self) {
self.atlas.trim(); self.atlas.trim();
self.render_cache.trim(); self.cache.get_mut().trim();
self.prepare_layer = 0; self.prepare_layer = 0;
} }
@ -241,7 +238,7 @@ impl Pipeline {
bounds: Size, bounds: Size,
shaping: Shaping, shaping: Shaping,
) -> (f32, f32) { ) -> (f32, f32) {
let mut measurement_cache = self.measurement_cache.borrow_mut(); let mut measurement_cache = self.cache.borrow_mut();
let line_height = f32::from(line_height.to_absolute(Pixels(size))); let line_height = f32::from(line_height.to_absolute(Pixels(size)));
@ -271,7 +268,7 @@ impl Pipeline {
point: Point, point: Point,
_nearest_only: bool, _nearest_only: bool,
) -> Option<Hit> { ) -> Option<Hit> {
let mut measurement_cache = self.measurement_cache.borrow_mut(); let mut measurement_cache = self.cache.borrow_mut();
let line_height = f32::from(line_height.to_absolute(Pixels(size))); let line_height = f32::from(line_height.to_absolute(Pixels(size)));
@ -291,10 +288,6 @@ impl Pipeline {
Some(Hit::CharOffset(cursor.index)) Some(Hit::CharOffset(cursor.index))
} }
pub fn trim_measurement_cache(&mut self) {
self.measurement_cache.borrow_mut().trim();
}
} }
fn measure(buffer: &glyphon::Buffer) -> (f32, f32) { fn measure(buffer: &glyphon::Buffer) -> (f32, f32) {