1use crate::Rect;
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum FontMeasureError {
14 ZeroSize,
16 InvalidScale,
18 Unrepresentable,
21}
22
23impl std::fmt::Display for FontMeasureError {
24 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25 f.write_str(match self {
26 Self::ZeroSize => "bitmap font size must be nonzero",
27 Self::InvalidScale => "bitmap font scale must be finite and positive",
28 Self::Unrepresentable => "bitmap text geometry is not representable in f32",
29 })
30 }
31}
32
33impl std::error::Error for FontMeasureError {}
34
35#[derive(Clone, Copy, Debug, PartialEq)]
47pub struct BitmapFontMetrics {
48 pixel_size: f32,
49}
50
51#[derive(Clone, Copy, Debug, Default, PartialEq)]
61pub struct BitmapTextMetrics {
62 pub width: f32,
65 pub height: f32,
68 pub line_count: usize,
70 pub unsupported_glyphs: usize,
73 pub ink_bounds: Option<Rect>,
76}
77
78impl crate::Font {
79 pub fn try_metrics(
94 &self,
95 size: u16,
96 scale: f32,
97 ) -> Result<BitmapFontMetrics, FontMeasureError> {
98 if size == 0 {
99 return Err(FontMeasureError::ZeroSize);
100 }
101 if !scale.is_finite() || scale <= 0.0 {
102 return Err(FontMeasureError::InvalidScale);
103 }
104 let pixel_size = size as f32 * scale / 8.0;
105 if !pixel_size.is_finite() || pixel_size <= 0.0 || !(8.0 * pixel_size).is_finite() {
106 return Err(FontMeasureError::Unrepresentable);
107 }
108 Ok(BitmapFontMetrics { pixel_size })
109 }
110}
111
112impl BitmapFontMetrics {
113 pub fn pixel_size(self) -> f32 {
115 self.pixel_size
116 }
117
118 pub fn glyph_advance(self) -> f32 {
120 6.0 * self.pixel_size
121 }
122
123 pub fn baseline(self) -> f32 {
126 7.0 * self.pixel_size
127 }
128
129 pub fn line_height(self) -> f32 {
131 8.0 * self.pixel_size
132 }
133
134 pub fn measure_line(self, text: &str) -> Result<BitmapTextMetrics, FontMeasureError> {
150 self.measure(text, false)
151 }
152
153 pub fn measure_multiline(self, text: &str) -> Result<BitmapTextMetrics, FontMeasureError> {
177 self.measure(text, true)
178 }
179
180 fn measure(self, text: &str, multiline: bool) -> Result<BitmapTextMetrics, FontMeasureError> {
181 let mut result = BitmapTextMetrics::default();
182 if text.is_empty() {
183 return Ok(result);
184 }
185 let mut x = 0.0;
186 let mut baseline = self.baseline();
187 result.line_count = 1;
188 let mut ink: Option<[f32; 4]> = None;
190 let mut chars = text.chars().peekable();
191 while let Some(c) = chars.next() {
192 let crlf = multiline && c == '\r' && chars.peek() == Some(&'\n');
193 if multiline && (c == '\n' || crlf) {
194 if crlf {
195 chars.next();
196 }
197 result.width = result.width.max(x);
198 x = 0.0;
199 baseline = checked_advance(baseline, self.line_height())?;
200 result.line_count += 1;
201 continue;
202 }
203
204 let rows = glyph(c.to_ascii_uppercase());
205 if c != ' ' && rows == [0; 7] {
206 result.unsupported_glyphs += 1;
207 }
208 for (row, bits) in rows.into_iter().enumerate() {
209 if bits == 0 {
210 continue;
211 }
212 let left = x + (bits.leading_zeros() - 3) as f32 * self.pixel_size;
214 let last = x + (4 - bits.trailing_zeros()) as f32 * self.pixel_size;
215 let top = baseline - self.baseline() + row as f32 * self.pixel_size;
216 let right = checked_advance(last, self.pixel_size)?;
217 let bottom = checked_advance(top, self.pixel_size)?;
218 ink = Some(match ink {
219 None => [left, top, right, bottom],
220 Some([l, t, r, b]) => [l.min(left), t.min(top), r.max(right), b.max(bottom)],
221 });
222 }
223 x = checked_advance(x, self.glyph_advance())?;
224 }
225 result.width = result.width.max(x);
226 result.height = baseline;
227 result.ink_bounds =
228 ink.map(|[left, top, right, bottom]| Rect::new(left, top, right - left, bottom - top));
229 Ok(result)
230 }
231}
232
233fn checked_advance(position: f32, distance: f32) -> Result<f32, FontMeasureError> {
234 let next = position + distance;
235 if !next.is_finite() || next <= position {
236 Err(FontMeasureError::Unrepresentable)
237 } else {
238 Ok(next)
239 }
240}
241
242pub fn glyph(c: char) -> [u8; 7] {
244 match c {
245 'A' => [14, 17, 17, 31, 17, 17, 17],
246 'B' => [30, 17, 17, 30, 17, 17, 30],
247 'C' => [14, 17, 16, 16, 16, 17, 14],
248 'D' => [30, 17, 17, 17, 17, 17, 30],
249 'E' => [31, 16, 16, 30, 16, 16, 31],
250 'F' => [31, 16, 16, 30, 16, 16, 16],
251 'G' => [14, 17, 16, 23, 17, 17, 15],
252 'H' => [17, 17, 17, 31, 17, 17, 17],
253 'I' => [31, 4, 4, 4, 4, 4, 31],
254 'J' => [7, 2, 2, 2, 18, 18, 12],
255 'K' => [17, 18, 20, 24, 20, 18, 17],
256 'L' => [16, 16, 16, 16, 16, 16, 31],
257 'M' => [17, 27, 21, 21, 17, 17, 17],
258 'N' => [17, 25, 21, 19, 17, 17, 17],
259 'O' => [14, 17, 17, 17, 17, 17, 14],
260 'P' => [30, 17, 17, 30, 16, 16, 16],
261 'Q' => [14, 17, 17, 17, 21, 18, 13],
262 'R' => [30, 17, 17, 30, 20, 18, 17],
263 'S' => [15, 16, 16, 14, 1, 1, 30],
264 'T' => [31, 4, 4, 4, 4, 4, 4],
265 'U' => [17, 17, 17, 17, 17, 17, 14],
266 'V' => [17, 17, 17, 17, 17, 10, 4],
267 'W' => [17, 17, 17, 21, 21, 21, 10],
268 'X' => [17, 17, 10, 4, 10, 17, 17],
269 'Y' => [17, 17, 10, 4, 4, 4, 4],
270 'Z' => [31, 1, 2, 4, 8, 16, 31],
271 '0' => [14, 17, 19, 21, 25, 17, 14],
272 '1' => [4, 12, 4, 4, 4, 4, 14],
273 '2' => [14, 17, 1, 2, 4, 8, 31],
274 '3' => [30, 1, 1, 14, 1, 1, 30],
275 '4' => [2, 6, 10, 18, 31, 2, 2],
276 '5' => [31, 16, 16, 30, 1, 1, 30],
277 '6' => [14, 16, 16, 30, 17, 17, 14],
278 '7' => [31, 1, 2, 4, 8, 8, 8],
279 '8' => [14, 17, 17, 14, 17, 17, 14],
280 '9' => [14, 17, 17, 15, 1, 1, 14],
281 '$' => [4, 15, 20, 14, 5, 30, 4],
282 ',' => [0, 0, 0, 12, 12, 4, 8],
283 ';' => [12, 12, 0, 12, 12, 4, 8],
284 ':' => [0, 12, 12, 0, 12, 12, 0],
285 '+' => [0, 4, 4, 31, 4, 4, 0],
286 '(' => [2, 4, 8, 8, 8, 4, 2],
287 ')' => [8, 4, 2, 2, 2, 4, 8],
288 '%' => [17, 2, 4, 4, 8, 16, 17],
289 '!' => [4, 4, 4, 4, 4, 0, 4],
290 '?' => [14, 17, 1, 2, 4, 0, 4],
291 '°' => [6, 9, 9, 6, 0, 0, 0],
292 '×' => [0, 17, 10, 4, 10, 17, 0],
293 '—' => [0, 0, 0, 31, 0, 0, 0],
294 '·' => [0, 0, 0, 4, 0, 0, 0],
295 '→' => [0, 4, 2, 31, 2, 4, 0],
296 '←' => [0, 4, 8, 31, 8, 4, 0],
297 '↑' => [4, 14, 21, 4, 4, 4, 0],
298 '↓' => [4, 4, 4, 4, 21, 14, 4],
299 '/' => [1, 1, 2, 4, 8, 16, 16],
300 '-' => [0, 0, 0, 31, 0, 0, 0],
301 '.' => [0, 0, 0, 0, 0, 12, 12],
302 '[' => [14, 8, 8, 8, 8, 8, 14],
303 ']' => [14, 2, 2, 2, 2, 2, 14],
304 '=' => [0, 0, 31, 0, 31, 0, 0],
305 '_' => [0, 0, 0, 0, 0, 0, 31],
306 '\'' => [4, 4, 2, 0, 0, 0, 0],
307 '\"' => [10, 10, 5, 0, 0, 0, 0],
308 '&' => [12, 18, 20, 8, 21, 18, 13],
309 '*' => [0, 21, 14, 31, 14, 21, 0],
310 '<' => [2, 4, 8, 16, 8, 4, 2],
311 '>' => [8, 4, 2, 1, 2, 4, 8],
312 '#' => [10, 31, 10, 10, 31, 10, 0],
313 _ => [0; 7],
314 }
315}
316
317#[cfg(test)]
318mod tests {
319 use super::*;
320 use crate::{Font, Mat4, State, TextParams, WHITE, draw_text_ex};
321
322 fn drawn_bounds<'a>(
323 lines: impl IntoIterator<Item = &'a str>,
324 size: u16,
325 scale: f32,
326 ) -> Option<Rect> {
327 crate::edit(|s| {
328 *s = State::default();
329 s.matrix = Mat4::IDENTITY;
331 });
332 let px = size as f32 * scale / 8.0;
333 let mut y = 7.0 * px;
334 for line in lines {
335 draw_text_ex(
336 line,
337 0.0,
338 y,
339 TextParams {
340 font_size: size,
341 font_scale: scale,
342 color: WHITE,
343 },
344 );
345 y += 8.0 * px;
346 }
347 crate::read(|s| {
348 let first = s.vertices.first()?;
349 let [mut left, mut top, mut right, mut bottom] =
350 [first[0], first[1], first[0], first[1]];
351 for v in &s.vertices {
352 left = left.min(v[0]);
353 top = top.min(v[1]);
354 right = right.max(v[0]);
355 bottom = bottom.max(v[1]);
356 }
357 Some(Rect::new(left, top, right - left, bottom - top))
358 })
359 }
360
361 #[test]
362 fn checked_font_geometry_rejects_invalid_inputs_and_derived_overflow() {
363 assert_eq!(Font.try_metrics(0, 1.0), Err(FontMeasureError::ZeroSize));
364 for scale in [0.0, -0.0, -1.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
365 assert_eq!(
366 Font.try_metrics(8, scale),
367 Err(FontMeasureError::InvalidScale)
368 );
369 }
370 for (size, scale) in [(1, f32::from_bits(1)), (8, f32::MAX), (u16::MAX, f32::MAX)] {
371 assert_eq!(
372 Font.try_metrics(size, scale),
373 Err(FontMeasureError::Unrepresentable)
374 );
375 }
376 for (size, scale) in [(1, f32::MIN_POSITIVE), (1, f32::MAX), (u16::MAX, 0.125)] {
377 let metrics = Font.try_metrics(size, scale).unwrap();
378 assert!(metrics.pixel_size() > 0.0);
379 assert!(metrics.line_height().is_finite());
380 }
381 }
382
383 #[test]
384 fn scaled_advances_baselines_and_ink_are_distinct() {
385 let metrics = Font.try_metrics(16, 1.5).unwrap();
386 assert_eq!(metrics.pixel_size(), 3.0);
387 assert_eq!(metrics.glyph_advance(), 18.0);
388 assert_eq!(metrics.baseline(), 21.0);
389 assert_eq!(metrics.line_height(), 24.0);
390 let text = metrics.measure_line("A ").unwrap();
391 assert_eq!((text.width, text.height, text.line_count), (36.0, 21.0, 1));
392 assert_eq!(text.ink_bounds, Some(Rect::new(0.0, 0.0, 15.0, 21.0)));
393 let punctuation = metrics.measure_line(".").unwrap();
394 assert_eq!(punctuation.ink_bounds, Some(Rect::new(3.0, 15.0, 6.0, 6.0)));
395 }
396
397 #[test]
398 fn empty_blank_and_unsupported_scalars_have_explicit_sizes() {
399 let metrics = Font.try_metrics(8, 1.0).unwrap();
400 assert_eq!(metrics.measure_line(""), Ok(BitmapTextMetrics::default()));
401 assert_eq!(
402 metrics.measure_multiline(""),
403 Ok(BitmapTextMetrics::default())
404 );
405 let blank = metrics.measure_line(" ").unwrap();
406 assert_eq!(
407 (blank.width, blank.height, blank.line_count),
408 (12.0, 7.0, 1)
409 );
410 assert_eq!(blank.ink_bounds, None);
411 assert_eq!(blank.unsupported_glyphs, 0);
412 let missing = metrics.measure_line("☃é😀ß\t\r\n").unwrap();
413 assert_eq!(missing.width, 42.0);
414 assert_eq!(missing.unsupported_glyphs, 7);
415 assert_eq!(missing.ink_bounds, None);
416 assert_eq!(metrics.measure_line("abc"), metrics.measure_line("ABC"));
417 assert_eq!(
418 metrics.measure_line("°×—·→←↑↓").unwrap().unsupported_glyphs,
419 0
420 );
421 }
422
423 #[test]
424 fn multiline_tracks_longest_line_crlf_and_trailing_empty_lines() {
425 let metrics = Font.try_metrics(8, 1.0).unwrap();
426 let label = metrics.measure_multiline("\nA☃\r\n.\n").unwrap();
427 assert_eq!(
428 (label.width, label.height, label.line_count),
429 (12.0, 31.0, 4)
430 );
431 assert_eq!(label.unsupported_glyphs, 1);
432 assert_eq!(label.ink_bounds, Some(Rect::new(0.0, 8.0, 5.0, 15.0)));
433 assert_eq!(label.ink_bounds, drawn_bounds(["", "A☃", ".", ""], 8, 1.0));
434 for text in ["\n", "\r\n"] {
435 let blank = metrics.measure_multiline(text).unwrap();
436 assert_eq!(
437 (blank.width, blank.height, blank.line_count),
438 (0.0, 15.0, 2)
439 );
440 assert_eq!(blank.unsupported_glyphs, 0);
441 assert_eq!(blank.ink_bounds, None);
442 }
443 let bare_cr = metrics.measure_multiline("A\r").unwrap();
444 assert_eq!(
445 (
446 bare_cr.width,
447 bare_cr.line_count,
448 bare_cr.unsupported_glyphs
449 ),
450 (12.0, 1, 1)
451 );
452 assert_eq!(
453 metrics.measure_multiline("A\r\n"),
454 metrics.measure_multiline("A\n")
455 );
456 }
457
458 #[test]
459 fn ink_bounds_match_actual_raster_rectangles_for_ascii_and_supported_unicode() {
460 let chars = (0..=127).map(char::from).chain("°×—·→←↑↓☃é😀ß".chars());
461 for c in chars {
462 let mut buffer = [0; 4];
463 let text = c.encode_utf8(&mut buffer);
464 for (size, scale) in [(8, 1.0), (16, 1.5), (17, 0.7), (1, 0.25)] {
465 let metrics = Font.try_metrics(size, scale).unwrap();
466 let measured = metrics.measure_line(text).unwrap();
467 assert_eq!(
468 measured.ink_bounds,
469 drawn_bounds([&*text], size, scale),
470 "{c:?}, {size}, {scale}"
471 );
472 }
473 }
474 }
475
476 #[test]
477 fn label_bounds_match_fractional_raster_advances_and_successive_baselines() {
478 for (size, scale) in [(8, 1.0), (16, 1.5), (17, 0.7), (1, 0.25)] {
479 let metrics = Font.try_metrics(size, scale).unwrap();
480 let line = " a☃ . 1 LONG LABEL 29:!? → ";
481 assert_eq!(
482 metrics.measure_line(line).unwrap().ink_bounds,
483 drawn_bounds([line], size, scale)
484 );
485 let mut pen = 0.0;
486 for _ in line.chars() {
487 pen += 6.0 * (size as f32 * scale / 8.0);
488 }
489 assert_eq!(metrics.measure_line(line).unwrap().width, pen);
490 let text = "\n.a☃.\nAAA\n.\n";
491 assert_eq!(
492 metrics.measure_multiline(text).unwrap().ink_bounds,
493 drawn_bounds(text.split('\n'), size, scale)
494 );
495 }
496 }
497
498 #[test]
499 fn layout_overflow_is_checked_after_valid_font_setup() {
500 let metrics = Font.try_metrics(1, f32::MAX).unwrap();
501 assert!(metrics.measure_line("A").is_ok());
502 for text in ["AA", " ", "☃☃"] {
503 assert_eq!(
504 metrics.measure_line(text),
505 Err(FontMeasureError::Unrepresentable)
506 );
507 }
508 assert_eq!(
509 metrics.measure_multiline("\n"),
510 Err(FontMeasureError::Unrepresentable)
511 );
512 assert_eq!(
513 metrics.measure_multiline("A\nB"),
514 Err(FontMeasureError::Unrepresentable)
515 );
516 assert_eq!(
518 checked_advance(16_777_216.0, 1.0),
519 Err(FontMeasureError::Unrepresentable)
520 );
521 }
522}