1use ab_glyph::{Font, FontVec, PxScale, ScaleFont};
6use anyhow::{anyhow, Result};
7
8use crate::quad::{push_glyph, GlyphQuad, TextVertex};
9
10const ATLAS_SIZE: u32 = 2048;
11const PAD: u32 = 1;
12
13#[derive(Clone, Copy, Debug)]
15struct Glyph {
16 x: u16,
18 y: u16,
19 w: u16,
20 h: u16,
21 bearing_x: f32,
23 bearing_y: f32,
25 advance: f32,
26}
27
28impl Glyph {
29 fn blank(advance: f32) -> Self {
30 Self {
31 x: 0,
32 y: 0,
33 w: 0,
34 h: 0,
35 bearing_x: 0.0,
36 bearing_y: 0.0,
37 advance,
38 }
39 }
40}
41
42pub struct GlyphAtlas {
44 font: FontVec,
45 scale: PxScale,
46 size: f32,
47 line_height: f32,
48 ascent: f32,
49 descent: f32,
50 space_advance: f32,
51 monospace: bool,
52 glyphs: std::collections::HashMap<char, Glyph>,
53 coverage: Vec<u8>,
54 pen_x: u32,
56 pen_y: u32,
57 row_height: u32,
58 dirty: bool,
59}
60
61impl GlyphAtlas {
62 pub fn new(font_bytes: &[u8], size: f32) -> Result<Self> {
63 let font = FontVec::try_from_vec(font_bytes.to_vec())
64 .map_err(|error| anyhow!("font parse failed: {error:?}"))?;
65 let scale = PxScale::from(size.max(1.0));
66 let scaled = font.as_scaled(scale);
67 let ascent = scaled.ascent();
68 let descent = scaled.descent();
69 let line_height = (ascent - descent).ceil().max(1.0);
70 let space_advance = scaled.h_advance(scaled.glyph_id(' '));
71 Ok(Self {
72 font,
73 scale,
74 size: size.max(1.0),
75 line_height,
76 ascent,
77 descent,
78 space_advance,
79 monospace: false,
80 glyphs: std::collections::HashMap::new(),
81 coverage: vec![0u8; (ATLAS_SIZE * ATLAS_SIZE) as usize],
82 pen_x: PAD,
83 pen_y: PAD,
84 row_height: 0,
85 dirty: true,
86 })
87 }
88
89 pub fn set_monospace(&mut self, enabled: bool) {
92 self.monospace = enabled;
93 }
94
95 pub fn size(&self) -> f32 {
96 self.size
97 }
98
99 pub fn line_height(&self) -> f32 {
100 self.line_height
101 }
102
103 pub fn ascent(&self) -> f32 {
104 self.ascent
105 }
106
107 pub fn descent(&self) -> f32 {
108 self.descent
109 }
110
111 pub fn cell_advance(&self) -> Option<f32> {
113 self.monospace.then_some(self.space_advance)
114 }
115
116 pub fn take_dirty(&mut self) -> bool {
117 std::mem::take(&mut self.dirty)
118 }
119
120 pub fn coverage(&self) -> &[u8] {
121 &self.coverage
122 }
123
124 pub fn atlas_size(&self) -> u32 {
125 ATLAS_SIZE
126 }
127
128 pub fn measure(&mut self, text: &str) -> f32 {
130 match self.cell_advance() {
131 Some(cell) => cell * text.chars().count() as f32,
132 None => text.chars().map(|ch| self.advance(ch)).sum(),
133 }
134 }
135
136 pub fn ellipsize(&mut self, text: &str, max_width: f32) -> String {
138 if self.measure(text) <= max_width {
139 return text.to_string();
140 }
141 let ellipsis = "\u{2026}";
142 let budget = max_width - self.measure(ellipsis);
143 let mut out = String::new();
144 let mut width = 0.0;
145 for ch in text.chars() {
146 let advance = self.advance(ch);
147 if width + advance > budget {
148 break;
149 }
150 out.push(ch);
151 width += advance;
152 }
153 out.push_str(ellipsis);
154 out
155 }
156
157 pub fn advance(&mut self, ch: char) -> f32 {
158 if self.monospace {
159 return self.space_advance;
160 }
161 let scaled = self.font.as_scaled(self.scale);
162 scaled.h_advance(scaled.glyph_id(ch))
163 }
164
165 fn rasterize(&mut self, ch: char) -> Glyph {
166 let advance = self.advance(ch);
167 let outlined = {
168 let scaled = self.font.as_scaled(self.scale);
169 scaled.outline_glyph(scaled.scaled_glyph(ch))
170 };
171 let Some(outlined) = outlined else {
172 return Glyph::blank(advance);
173 };
174 let bounds = outlined.px_bounds();
175 let w = bounds.width().max(0.0) as u32;
176 let h = bounds.height().max(0.0) as u32;
177 if w == 0 || h == 0 {
178 return Glyph::blank(advance);
179 }
180 let Some((x, y)) = self.allocate(w, h) else {
181 return Glyph::blank(advance);
184 };
185 let mut coverage = vec![0u8; (w * h) as usize];
186 outlined.draw(|px, py, value| {
187 let index = py as usize * w as usize + px as usize;
188 if let Some(slot) = coverage.get_mut(index) {
189 *slot = (value.clamp(0.0, 1.0) * 255.0) as u8;
190 }
191 });
192 self.blit(x, y, w, h, &coverage);
193 self.dirty = true;
194 Glyph {
195 x: x as u16,
196 y: y as u16,
197 w: w as u16,
198 h: h as u16,
199 bearing_x: bounds.min.x,
200 bearing_y: bounds.max.y,
201 advance,
202 }
203 }
204
205 fn allocate(&mut self, w: u32, h: u32) -> Option<(u32, u32)> {
208 if self.pen_x + w + PAD > ATLAS_SIZE {
209 self.pen_x = PAD;
210 self.pen_y += self.row_height + PAD;
211 self.row_height = 0;
212 }
213 if self.pen_y + h + PAD > ATLAS_SIZE {
214 return None;
215 }
216 let slot = (self.pen_x, self.pen_y);
217 self.pen_x += w + PAD;
218 self.row_height = self.row_height.max(h);
219 Some(slot)
220 }
221
222 fn blit(&mut self, x: u32, y: u32, w: u32, h: u32, coverage: &[u8]) {
223 for row in 0..h {
224 let source = (row as usize) * w as usize;
225 let target = ((y + row) * ATLAS_SIZE + x) as usize;
226 self.coverage[target..target + w as usize]
227 .copy_from_slice(&coverage[source..source + w as usize]);
228 }
229 }
230
231 pub fn shape(
233 &mut self,
234 out: &mut Vec<TextVertex>,
235 text: &str,
236 x: f32,
237 baseline_y: f32,
238 color: [f32; 4],
239 layer: usize,
240 ) -> f32 {
241 let mut pen = x;
242 for ch in text.chars() {
243 if ch == '\n' || ch == '\r' {
244 continue;
245 }
246 if ch == '\t' {
247 pen += self.space_advance * 4.0;
248 continue;
249 }
250 if ch.is_control() {
251 continue;
252 }
253 let glyph = match self.glyphs.get(&ch) {
254 Some(glyph) => *glyph,
255 None => {
256 let glyph = self.rasterize(ch);
257 self.glyphs.insert(ch, glyph);
258 glyph
259 }
260 };
261 if glyph.w > 0 && glyph.h > 0 {
262 let scale = ATLAS_SIZE as f32;
263 push_glyph(
264 out,
265 GlyphQuad {
266 left: pen + glyph.bearing_x,
267 top: baseline_y - glyph.bearing_y,
268 width: glyph.w as f32,
269 height: glyph.h as f32,
270 uv: [
271 glyph.x as f32 / scale,
272 glyph.y as f32 / scale,
273 glyph.w as f32 / scale,
274 glyph.h as f32 / scale,
275 ],
276 color,
277 layer: layer as f32,
278 },
279 );
280 }
281 pen += glyph.advance;
282 }
283 pen - x
284 }
285}
286
287#[derive(Clone)]
291pub struct TextMetrics {
292 font: std::sync::Arc<FontVec>,
295}
296
297impl TextMetrics {
298 pub fn new(font_bytes: &[u8]) -> Result<Self> {
299 let font = FontVec::try_from_vec(font_bytes.to_vec())
300 .map_err(|error| anyhow!("font parse failed: {error:?}"))?;
301 Ok(Self {
302 font: std::sync::Arc::new(font),
303 })
304 }
305
306 pub fn measure(&self, text: &str, size: f32) -> f32 {
308 let scaled = self.font.as_scaled(PxScale::from(size.max(1.0)));
309 text.chars()
310 .map(|ch| scaled.h_advance(scaled.glyph_id(ch)))
311 .sum()
312 }
313
314 pub fn line_height(&self, size: f32) -> f32 {
316 let scaled = self.font.as_scaled(PxScale::from(size.max(1.0)));
317 (scaled.ascent() - scaled.descent()).ceil().max(1.0)
318 }
319
320 pub fn ascent(&self, size: f32) -> f32 {
322 self.font.as_scaled(PxScale::from(size.max(1.0))).ascent()
323 }
324}
325
326pub struct AtlasSet {
329 atlases: Vec<GlyphAtlas>,
330 keys: Vec<(u32, bool)>,
331 dirty: bool,
332}
333
334impl AtlasSet {
335 pub fn new() -> Self {
336 Self {
337 atlases: Vec::new(),
338 keys: Vec::new(),
339 dirty: true,
340 }
341 }
342
343 pub fn layer(&mut self, size: f32, monospace: bool, font: &[u8]) -> Result<usize> {
345 let key = (size.max(1.0).to_bits(), monospace);
346 if let Some(index) = self.keys.iter().position(|existing| *existing == key) {
347 return Ok(index);
348 }
349 let mut atlas = GlyphAtlas::new(font, size)?;
350 atlas.set_monospace(monospace);
351 self.atlases.push(atlas);
352 self.keys.push(key);
353 self.dirty = true;
354 Ok(self.atlases.len() - 1)
355 }
356
357 pub fn get(&self, index: usize) -> &GlyphAtlas {
358 &self.atlases[index]
359 }
360
361 pub fn get_mut(&mut self, index: usize) -> &mut GlyphAtlas {
362 &mut self.atlases[index]
363 }
364
365 pub fn layers(&self) -> usize {
366 self.atlases.len()
367 }
368
369 pub fn take_dirty(&mut self) -> bool {
370 let mut dirty = std::mem::take(&mut self.dirty);
371 for atlas in &mut self.atlases {
372 dirty |= std::mem::take(&mut atlas.dirty);
373 }
374 dirty
375 }
376
377 pub fn atlases(&self) -> &[GlyphAtlas] {
378 &self.atlases
379 }
380}
381
382impl Default for AtlasSet {
383 fn default() -> Self {
384 Self::new()
385 }
386}
387
388pub fn atlas_extent(layers: usize) -> wgpu::Extent3d {
390 wgpu::Extent3d {
391 width: ATLAS_SIZE,
392 height: ATLAS_SIZE,
393 depth_or_array_layers: layers.max(1) as u32,
394 }
395}
396
397pub fn create_atlas_texture(device: &wgpu::Device, layers: usize) -> wgpu::Texture {
399 device.create_texture(&wgpu::TextureDescriptor {
400 label: Some("rcus-glyph-atlas"),
401 size: atlas_extent(layers),
402 mip_level_count: 1,
403 sample_count: 1,
404 dimension: wgpu::TextureDimension::D2,
405 format: wgpu::TextureFormat::R8Unorm,
406 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
407 view_formats: &[],
408 })
409}
410
411pub fn upload_atlas_layers(queue: &wgpu::Queue, texture: &wgpu::Texture, set: &AtlasSet) {
414 for (layer, atlas) in set.atlases().iter().enumerate() {
415 let size = wgpu::Extent3d {
416 width: ATLAS_SIZE,
417 height: ATLAS_SIZE,
418 depth_or_array_layers: 1,
419 };
420 queue.write_texture(
421 wgpu::ImageCopyTexture {
422 texture,
423 mip_level: 0,
424 origin: wgpu::Origin3d {
425 x: 0,
426 y: 0,
427 z: layer as u32,
428 },
429 aspect: wgpu::TextureAspect::All,
430 },
431 atlas.coverage(),
432 wgpu::ImageDataLayout {
433 offset: 0,
434 bytes_per_row: Some(ATLAS_SIZE),
435 rows_per_image: Some(ATLAS_SIZE),
436 },
437 size,
438 );
439 }
440}
441
442pub fn atlas_view(texture: &wgpu::Texture) -> wgpu::TextureView {
444 texture.create_view(&wgpu::TextureViewDescriptor {
445 dimension: Some(wgpu::TextureViewDimension::D2Array),
446 ..Default::default()
447 })
448}