use ab_glyph::{Font, FontVec, PxScale, ScaleFont};
use anyhow::{anyhow, Result};
use crate::quad::{push_glyph, GlyphQuad, TextVertex};
const ATLAS_SIZE: u32 = 2048;
const PAD: u32 = 1;
#[derive(Clone, Copy, Debug)]
struct Glyph {
x: u16,
y: u16,
w: u16,
h: u16,
bearing_x: f32,
bearing_y: f32,
advance: f32,
}
impl Glyph {
fn blank(advance: f32) -> Self {
Self {
x: 0,
y: 0,
w: 0,
h: 0,
bearing_x: 0.0,
bearing_y: 0.0,
advance,
}
}
}
pub struct GlyphAtlas {
font: FontVec,
scale: PxScale,
size: f32,
line_height: f32,
ascent: f32,
descent: f32,
space_advance: f32,
monospace: bool,
glyphs: std::collections::HashMap<char, Glyph>,
coverage: Vec<u8>,
pen_x: u32,
pen_y: u32,
row_height: u32,
dirty: bool,
}
impl GlyphAtlas {
pub fn new(font_bytes: &[u8], size: f32) -> Result<Self> {
let font = FontVec::try_from_vec(font_bytes.to_vec())
.map_err(|error| anyhow!("font parse failed: {error:?}"))?;
let scale = PxScale::from(size.max(1.0));
let scaled = font.as_scaled(scale);
let ascent = scaled.ascent();
let descent = scaled.descent();
let line_height = (ascent - descent).ceil().max(1.0);
let space_advance = scaled.h_advance(scaled.glyph_id(' '));
Ok(Self {
font,
scale,
size: size.max(1.0),
line_height,
ascent,
descent,
space_advance,
monospace: false,
glyphs: std::collections::HashMap::new(),
coverage: vec![0u8; (ATLAS_SIZE * ATLAS_SIZE) as usize],
pen_x: PAD,
pen_y: PAD,
row_height: 0,
dirty: true,
})
}
pub fn set_monospace(&mut self, enabled: bool) {
self.monospace = enabled;
}
pub fn size(&self) -> f32 {
self.size
}
pub fn line_height(&self) -> f32 {
self.line_height
}
pub fn ascent(&self) -> f32 {
self.ascent
}
pub fn descent(&self) -> f32 {
self.descent
}
pub fn cell_advance(&self) -> Option<f32> {
self.monospace.then_some(self.space_advance)
}
pub fn take_dirty(&mut self) -> bool {
std::mem::take(&mut self.dirty)
}
pub fn coverage(&self) -> &[u8] {
&self.coverage
}
pub fn atlas_size(&self) -> u32 {
ATLAS_SIZE
}
pub fn measure(&mut self, text: &str) -> f32 {
match self.cell_advance() {
Some(cell) => cell * text.chars().count() as f32,
None => text.chars().map(|ch| self.advance(ch)).sum(),
}
}
pub fn ellipsize(&mut self, text: &str, max_width: f32) -> String {
if self.measure(text) <= max_width {
return text.to_string();
}
let ellipsis = "\u{2026}";
let budget = max_width - self.measure(ellipsis);
let mut out = String::new();
let mut width = 0.0;
for ch in text.chars() {
let advance = self.advance(ch);
if width + advance > budget {
break;
}
out.push(ch);
width += advance;
}
out.push_str(ellipsis);
out
}
pub fn advance(&mut self, ch: char) -> f32 {
if self.monospace {
return self.space_advance;
}
let scaled = self.font.as_scaled(self.scale);
scaled.h_advance(scaled.glyph_id(ch))
}
fn rasterize(&mut self, ch: char) -> Glyph {
let advance = self.advance(ch);
let outlined = {
let scaled = self.font.as_scaled(self.scale);
scaled.outline_glyph(scaled.scaled_glyph(ch))
};
let Some(outlined) = outlined else {
return Glyph::blank(advance);
};
let bounds = outlined.px_bounds();
let w = bounds.width().max(0.0) as u32;
let h = bounds.height().max(0.0) as u32;
if w == 0 || h == 0 {
return Glyph::blank(advance);
}
let Some((x, y)) = self.allocate(w, h) else {
return Glyph::blank(advance);
};
let mut coverage = vec![0u8; (w * h) as usize];
outlined.draw(|px, py, value| {
let index = py as usize * w as usize + px as usize;
if let Some(slot) = coverage.get_mut(index) {
*slot = (value.clamp(0.0, 1.0) * 255.0) as u8;
}
});
self.blit(x, y, w, h, &coverage);
self.dirty = true;
Glyph {
x: x as u16,
y: y as u16,
w: w as u16,
h: h as u16,
bearing_x: bounds.min.x,
bearing_y: bounds.max.y,
advance,
}
}
fn allocate(&mut self, w: u32, h: u32) -> Option<(u32, u32)> {
if self.pen_x + w + PAD > ATLAS_SIZE {
self.pen_x = PAD;
self.pen_y += self.row_height + PAD;
self.row_height = 0;
}
if self.pen_y + h + PAD > ATLAS_SIZE {
return None;
}
let slot = (self.pen_x, self.pen_y);
self.pen_x += w + PAD;
self.row_height = self.row_height.max(h);
Some(slot)
}
fn blit(&mut self, x: u32, y: u32, w: u32, h: u32, coverage: &[u8]) {
for row in 0..h {
let source = (row as usize) * w as usize;
let target = ((y + row) * ATLAS_SIZE + x) as usize;
self.coverage[target..target + w as usize]
.copy_from_slice(&coverage[source..source + w as usize]);
}
}
pub fn shape(
&mut self,
out: &mut Vec<TextVertex>,
text: &str,
x: f32,
baseline_y: f32,
color: [f32; 4],
layer: usize,
) -> f32 {
let mut pen = x;
for ch in text.chars() {
if ch == '\n' || ch == '\r' {
continue;
}
if ch == '\t' {
pen += self.space_advance * 4.0;
continue;
}
if ch.is_control() {
continue;
}
let glyph = match self.glyphs.get(&ch) {
Some(glyph) => *glyph,
None => {
let glyph = self.rasterize(ch);
self.glyphs.insert(ch, glyph);
glyph
}
};
if glyph.w > 0 && glyph.h > 0 {
let scale = ATLAS_SIZE as f32;
push_glyph(
out,
GlyphQuad {
left: pen + glyph.bearing_x,
top: baseline_y - glyph.bearing_y,
width: glyph.w as f32,
height: glyph.h as f32,
uv: [
glyph.x as f32 / scale,
glyph.y as f32 / scale,
glyph.w as f32 / scale,
glyph.h as f32 / scale,
],
color,
layer: layer as f32,
},
);
}
pen += glyph.advance;
}
pen - x
}
}
#[derive(Clone)]
pub struct TextMetrics {
font: std::sync::Arc<FontVec>,
}
impl TextMetrics {
pub fn new(font_bytes: &[u8]) -> Result<Self> {
let font = FontVec::try_from_vec(font_bytes.to_vec())
.map_err(|error| anyhow!("font parse failed: {error:?}"))?;
Ok(Self {
font: std::sync::Arc::new(font),
})
}
pub fn measure(&self, text: &str, size: f32) -> f32 {
let scaled = self.font.as_scaled(PxScale::from(size.max(1.0)));
text.chars()
.map(|ch| scaled.h_advance(scaled.glyph_id(ch)))
.sum()
}
pub fn line_height(&self, size: f32) -> f32 {
let scaled = self.font.as_scaled(PxScale::from(size.max(1.0)));
(scaled.ascent() - scaled.descent()).ceil().max(1.0)
}
pub fn ascent(&self, size: f32) -> f32 {
self.font.as_scaled(PxScale::from(size.max(1.0))).ascent()
}
}
pub struct AtlasSet {
atlases: Vec<GlyphAtlas>,
keys: Vec<(u32, bool)>,
dirty: bool,
}
impl AtlasSet {
pub fn new() -> Self {
Self {
atlases: Vec::new(),
keys: Vec::new(),
dirty: true,
}
}
pub fn layer(&mut self, size: f32, monospace: bool, font: &[u8]) -> Result<usize> {
let key = (size.max(1.0).to_bits(), monospace);
if let Some(index) = self.keys.iter().position(|existing| *existing == key) {
return Ok(index);
}
let mut atlas = GlyphAtlas::new(font, size)?;
atlas.set_monospace(monospace);
self.atlases.push(atlas);
self.keys.push(key);
self.dirty = true;
Ok(self.atlases.len() - 1)
}
pub fn get(&self, index: usize) -> &GlyphAtlas {
&self.atlases[index]
}
pub fn get_mut(&mut self, index: usize) -> &mut GlyphAtlas {
&mut self.atlases[index]
}
pub fn layers(&self) -> usize {
self.atlases.len()
}
pub fn take_dirty(&mut self) -> bool {
let mut dirty = std::mem::take(&mut self.dirty);
for atlas in &mut self.atlases {
dirty |= std::mem::take(&mut atlas.dirty);
}
dirty
}
pub fn atlases(&self) -> &[GlyphAtlas] {
&self.atlases
}
}
impl Default for AtlasSet {
fn default() -> Self {
Self::new()
}
}
pub fn atlas_extent(layers: usize) -> wgpu::Extent3d {
wgpu::Extent3d {
width: ATLAS_SIZE,
height: ATLAS_SIZE,
depth_or_array_layers: layers.max(1) as u32,
}
}
pub fn create_atlas_texture(device: &wgpu::Device, layers: usize) -> wgpu::Texture {
device.create_texture(&wgpu::TextureDescriptor {
label: Some("rcus-glyph-atlas"),
size: atlas_extent(layers),
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::R8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
})
}
pub fn upload_atlas_layers(queue: &wgpu::Queue, texture: &wgpu::Texture, set: &AtlasSet) {
for (layer, atlas) in set.atlases().iter().enumerate() {
let size = wgpu::Extent3d {
width: ATLAS_SIZE,
height: ATLAS_SIZE,
depth_or_array_layers: 1,
};
queue.write_texture(
wgpu::ImageCopyTexture {
texture,
mip_level: 0,
origin: wgpu::Origin3d {
x: 0,
y: 0,
z: layer as u32,
},
aspect: wgpu::TextureAspect::All,
},
atlas.coverage(),
wgpu::ImageDataLayout {
offset: 0,
bytes_per_row: Some(ATLAS_SIZE),
rows_per_image: Some(ATLAS_SIZE),
},
size,
);
}
}
pub fn atlas_view(texture: &wgpu::Texture) -> wgpu::TextureView {
texture.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default()
})
}