1use crate::{Color, font, font_modern, shapes::Sink};
31
32#[inline]
41pub fn modern_glyph(c: char) -> Option<(u8, [u16; 13])> {
42 font_modern::TABLE.get(c).map(|g| (g.width, g.rows))
43}
44
45#[inline]
52pub fn modern_kerning(left: char, right: char) -> i8 {
53 font_modern::kerning(left, right)
54}
55
56#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
58pub enum FontFace {
59 Classic,
61 #[default]
63 Modern,
64}
65
66#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
68pub enum TextAlign {
69 #[default]
71 Left,
72 Center,
74 Right,
76}
77
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub struct FaceMetrics {
81 pub ascent: u8,
83 pub descent: u8,
85 pub line_height: u8,
87 pub cap_height: u8,
88 pub x_height: u8,
89}
90
91impl FontFace {
92 pub const fn metrics(self) -> FaceMetrics {
101 match self {
102 Self::Classic => FaceMetrics {
103 ascent: 7,
104 descent: 0,
105 line_height: 8,
106 cap_height: 7,
107 x_height: 7,
108 },
109 Self::Modern => FaceMetrics {
110 ascent: font_modern::ASCENT,
111 descent: font_modern::DESCENT,
112 line_height: font_modern::LINE_HEIGHT,
113 cap_height: font_modern::CAP_HEIGHT,
114 x_height: font_modern::X_HEIGHT,
115 },
116 }
117 }
118
119 pub fn supports(self, c: char) -> bool {
129 match self {
130 Self::Classic => c == ' ' || font::glyph(c.to_ascii_uppercase()) != [0; 7],
131 Self::Modern => font_modern::TABLE.get(c).is_some(),
132 }
133 }
134
135 pub fn characters(self) -> impl Iterator<Item = char> {
142 let classic = (' '..='~')
143 .chain("°×—·→←↑↓".chars())
144 .filter(|&c| !c.is_ascii_lowercase() && Self::Classic.supports(c));
145 let modern = font_modern::TABLE.chars();
146 let (a, b) = match self {
147 Self::Classic => (Some(classic), None),
148 Self::Modern => (None, Some(modern)),
149 };
150 a.into_iter().flatten().chain(b.into_iter().flatten())
151 }
152}
153
154#[derive(Clone, Copy, Debug, PartialEq)]
167pub struct TextStyle {
168 pub face: FontFace,
169 pub size: f32,
171 pub color: Color,
172 pub shadow: Option<Color>,
174 pub outline: Option<Color>,
177 pub letter_spacing: f32,
179 pub line_spacing: f32,
181 pub align: TextAlign,
182 pub pixel_snap: bool,
185}
186
187impl Default for TextStyle {
188 fn default() -> Self {
189 Self::modern(16., crate::WHITE)
190 }
191}
192
193impl TextStyle {
194 pub const fn modern(size: f32, color: Color) -> Self {
196 Self {
197 face: FontFace::Modern,
198 size,
199 color,
200 shadow: None,
201 outline: None,
202 letter_spacing: 0.,
203 line_spacing: 0.,
204 align: TextAlign::Left,
205 pixel_snap: true,
206 }
207 }
208 pub const fn classic(size: f32, color: Color) -> Self {
210 let mut style = Self::modern(size, color);
211 style.face = FontFace::Classic;
212 style
213 }
214 pub const fn with_face(mut self, face: FontFace) -> Self {
215 self.face = face;
216 self
217 }
218 pub const fn with_size(mut self, size: f32) -> Self {
219 self.size = size;
220 self
221 }
222 pub const fn with_color(mut self, color: Color) -> Self {
223 self.color = color;
224 self
225 }
226 pub const fn with_shadow(mut self, color: Color) -> Self {
227 self.shadow = Some(color);
228 self
229 }
230 pub const fn with_outline(mut self, color: Color) -> Self {
231 self.outline = Some(color);
232 self
233 }
234 pub const fn with_letter_spacing(mut self, pixels: f32) -> Self {
235 self.letter_spacing = pixels;
236 self
237 }
238 pub const fn with_line_spacing(mut self, pixels: f32) -> Self {
239 self.line_spacing = pixels;
240 self
241 }
242 pub const fn with_align(mut self, align: TextAlign) -> Self {
243 self.align = align;
244 self
245 }
246 pub const fn with_pixel_snap(mut self, snap: bool) -> Self {
247 self.pixel_snap = snap;
248 self
249 }
250 pub fn pixel(&self) -> f32 {
252 self.size / 8.
253 }
254 pub fn line_height(&self) -> f32 {
256 (self.face.metrics().line_height as f32 + self.line_spacing) * self.pixel()
257 }
258 pub fn centered_baseline(&self, center_y: f32) -> f32 {
266 center_y + self.face.metrics().cap_height as f32 * self.pixel() * 0.5
267 }
268 fn is_valid(&self) -> bool {
269 let c = self.color;
270 self.size.is_finite()
271 && self.size > 0.
272 && self.letter_spacing.is_finite()
273 && self.line_spacing.is_finite()
274 && [c.r, c.g, c.b, c.a].iter().all(|v| v.is_finite())
275 }
276}
277
278#[derive(Clone, Copy, Debug, Default, PartialEq)]
280pub struct TextMetrics {
281 pub width: f32,
284 pub height: f32,
286 pub line_count: usize,
288 pub line_height: f32,
290 pub ascent: f32,
292 pub descent: f32,
294 pub cap_height: f32,
295 pub x_height: f32,
296 pub unsupported: usize,
298}
299
300#[derive(Clone, Copy)]
304struct Shape {
305 width: u8,
306 bits: u16,
308}
309
310#[inline]
311fn modern(c: char) -> (&'static font_modern::Glyph, bool) {
312 match font_modern::TABLE.get(c) {
313 Some(g) => (g, true),
314 None => (
315 font_modern::TABLE.get('?').expect("modern '?' glyph"),
316 false,
317 ),
318 }
319}
320
321#[inline]
322fn classic(c: char) -> ([u8; 7], bool) {
323 let rows = font::glyph(c.to_ascii_uppercase());
324 if c == ' ' || rows != [0; 7] {
325 (rows, true)
326 } else {
327 (font::glyph('?'), false)
328 }
329}
330
331#[inline]
332fn width_of(face: FontFace, c: char) -> (u8, bool) {
333 match face {
334 FontFace::Classic => (5, classic(c).1),
335 FontFace::Modern => {
336 let (g, ok) = modern(c);
337 (g.width, ok)
338 }
339 }
340}
341
342#[inline]
344fn row_of(face: FontFace, c: char, row: i32) -> Shape {
345 match face {
346 FontFace::Classic => {
347 let rows = classic(c).0;
348 let bits = usize::try_from(row)
349 .ok()
350 .and_then(|r| rows.get(r))
351 .map_or(0, |&b| b as u16);
352 Shape { width: 5, bits }
353 }
354 FontFace::Modern => {
355 let g = modern(c).0;
356 let bits = usize::try_from(row)
357 .ok()
358 .and_then(|r| g.rows.get(r))
359 .map_or(0, |&b| b);
360 Shape {
361 width: g.width,
362 bits,
363 }
364 }
365 }
366}
367
368fn kern(face: FontFace, left: char, right: char) -> i8 {
369 match face {
370 FontFace::Classic => 0,
371 FontFace::Modern => font_modern::kerning(left, right),
372 }
373}
374
375fn rows(face: FontFace) -> i32 {
376 match face {
377 FontFace::Classic => 7,
378 FontFace::Modern => font_modern::ROWS as i32,
379 }
380}
381
382fn layout(line: &str, face: FontFace, spacing: f32) -> impl Iterator<Item = (char, f32, u8)> + '_ {
384 let mut x = 0.;
385 let mut prev: Option<char> = None;
386 line.chars().map(move |c| {
387 if let Some(p) = prev {
388 x += 1. + spacing + kern(face, p, c) as f32;
389 }
390 let width = width_of(face, c).0;
391 let origin = x;
392 x += width as f32;
393 prev = Some(c);
394 (c, origin, width)
395 })
396}
397
398fn line_units(line: &str, face: FontFace, spacing: f32) -> (f32, usize) {
400 let mut end: f32 = 0.;
401 let mut missing = 0;
402 for (c, x, w) in layout(line, face, spacing) {
403 end = x + w as f32;
404 missing += usize::from(!width_of(face, c).1);
405 }
406 (end.max(0.), missing)
407}
408
409fn lines(text: &str) -> impl Iterator<Item = &str> {
410 text.split('\n').map(|l| l.strip_suffix('\r').unwrap_or(l))
411}
412
413pub fn measure_text_styled(text: &str, style: TextStyle) -> TextMetrics {
426 let px = style.pixel();
427 let m = style.face.metrics();
428 let mut out = TextMetrics {
429 line_height: style.line_height(),
430 ascent: m.ascent as f32 * px,
431 descent: m.descent as f32 * px,
432 cap_height: m.cap_height as f32 * px,
433 x_height: m.x_height as f32 * px,
434 ..Default::default()
435 };
436 if !style.is_valid() || text.is_empty() {
437 return out;
438 }
439 let mut widest: f32 = 0.;
440 for line in lines(text) {
441 let (units, missing) = line_units(line, style.face, style.letter_spacing);
442 widest = widest.max(units);
443 out.unsupported += missing;
444 out.line_count += 1;
445 }
446 out.width = widest * px;
447 out.height = (out.line_count - 1) as f32 * out.line_height + out.ascent + out.descent;
448 out
449}
450
451pub fn text_width(line: &str, style: TextStyle) -> f32 {
459 if !style.is_valid() {
460 return 0.;
461 }
462 line_units(line, style.face, style.letter_spacing).0 * style.pixel()
463}
464
465#[derive(Clone, Copy)]
469struct Layer {
470 color: Color,
471 dx: f32,
473 dy: f32,
474 dilate: bool,
475}
476
477#[inline]
480fn dilated(face: FontFace, c: char, row: i32) -> Shape {
481 let mut acc = 0_u16;
482 let mut width = 0;
483 for r in row - 1..=row + 1 {
484 let s = row_of(face, c, r);
485 width = s.width;
486 let e = s.bits << 1;
487 acc |= e | (e << 1) | (e >> 1);
488 }
489 Shape {
490 width: width + 2,
491 bits: acc,
492 }
493}
494
495#[inline]
497fn span(start: i32, end: i32, width: i32) -> u16 {
498 ((((1_u32 << (end - start)) - 1) << (width - end)) & 0xffff) as u16
499}
500
501#[inline]
503fn is_run(bits: u16, start: i32, end: i32, width: i32) -> bool {
504 let mask = span(start, end, width);
505 let left = start == 0 || bits & span(start - 1, start, width) == 0;
506 let right = end == width || bits & span(end, end + 1, width) == 0;
507 bits & mask == mask && left && right
508}
509
510fn runs(bits: u16, width: i32) -> impl Iterator<Item = (i32, i32)> {
512 let lit = move |col: i32| col < width && bits >> (width - 1 - col) & 1 != 0;
513 let mut col = 0;
514 std::iter::from_fn(move || {
515 while col < width && !lit(col) {
516 col += 1;
517 }
518 if col >= width {
519 return None;
520 }
521 let start = col;
522 while lit(col) {
523 col += 1;
524 }
525 Some((start, col))
526 })
527}
528
529fn draw_line_stacked(
532 sink: &mut Sink,
533 line: &str,
534 left: f32,
535 baseline: f32,
536 px: f32,
537 style: &TextStyle,
538 layer: Layer,
539) {
540 let face = style.face;
541 let ascent = face.metrics().ascent as f32;
542 let count = rows(face);
543 for (c, origin, _) in layout(line, face, style.letter_spacing) {
544 let mut bits = [0_u16; font_modern::ROWS];
545 let mut width = 0;
546 for (r, slot) in bits.iter_mut().enumerate().take(count as usize) {
547 let shape = row_of(face, c, r as i32);
548 *slot = shape.bits;
549 width = shape.width as i32;
550 }
551 for r in 0..count as usize {
552 for (start, end) in runs(bits[r], width) {
553 if r > 0 && is_run(bits[r - 1], start, end, width) {
554 continue; }
556 let mut height = 1;
557 while r + height < count as usize && is_run(bits[r + height], start, end, width) {
558 height += 1;
559 }
560 let x = left + (origin + start as f32 + layer.dx) * px;
561 let y = baseline + (r as f32 - ascent + layer.dy) * px;
562 sink.rect(
563 x,
564 y,
565 (end - start) as f32 * px,
566 height as f32 * px,
567 layer.color,
568 );
569 }
570 }
571 }
572}
573
574fn draw_line_merged(
577 sink: &mut Sink,
578 line: &str,
579 left: f32,
580 baseline: f32,
581 px: f32,
582 style: &TextStyle,
583 layer: Layer,
584) {
585 let face = style.face;
586 let ascent = face.metrics().ascent as f32;
587 let (first, last) = if layer.dilate {
588 (-1, rows(face))
589 } else {
590 (0, rows(face) - 1)
591 };
592 for row in first..=last {
593 let top = baseline + (row as f32 - ascent + layer.dy) * px;
594 let mut run: Option<(f32, f32)> = None;
596 let flush = |run: (f32, f32), sink: &mut Sink| {
597 let x = left + (run.0 + layer.dx) * px;
598 sink.rect(x, top, (run.1 - run.0) * px, px, layer.color);
599 };
600 for (c, origin, _) in layout(line, face, style.letter_spacing) {
601 let (shape, origin) = if layer.dilate {
602 (dilated(face, c, row), origin - 1.)
603 } else {
604 (row_of(face, c, row), origin)
605 };
606 for (start, end) in runs(shape.bits, shape.width as i32) {
607 let s = origin + start as f32;
608 let e = origin + end as f32;
609 run = match run {
610 Some((a, b)) if s <= b + 1e-4 => Some((a.min(s), b.max(e))),
611 Some(done) => {
612 flush(done, sink);
613 Some((s, e))
614 }
615 None => Some((s, e)),
616 };
617 }
618 }
619 if let Some(done) = run {
620 flush(done, sink);
621 }
622 }
623}
624
625pub fn draw_text_styled(text: &str, x: f32, y: f32, style: TextStyle) -> TextMetrics {
639 let metrics = measure_text_styled(text, style);
640 if metrics.line_count == 0 || !x.is_finite() || !y.is_finite() {
641 return metrics;
642 }
643 crate::edit(|s| {
644 let mut sink = Sink::new(s);
645 let dp = sink.device_pixel();
646 let px = style.pixel();
647 let snap = |v: f32| {
648 if style.pixel_snap {
649 (v / dp).round() * dp
650 } else {
651 v
652 }
653 };
654 let mut layers = [None; 3];
655 if let Some(color) = style.shadow {
656 layers[0] = Some(Layer {
657 color,
658 dx: 1.,
659 dy: 1.,
660 dilate: style.outline.is_some(),
661 });
662 }
663 if let Some(color) = style.outline {
664 layers[1] = Some(Layer {
665 color,
666 dx: 0.,
667 dy: 0.,
668 dilate: true,
669 });
670 }
671 layers[2] = Some(Layer {
672 color: style.color,
673 dx: 0.,
674 dy: 0.,
675 dilate: false,
676 });
677 for layer in layers.into_iter().flatten() {
680 let mut baseline = y;
681 for line in lines(text) {
682 let width = line_units(line, style.face, style.letter_spacing).0 * px;
683 let left = match style.align {
684 TextAlign::Left => x,
685 TextAlign::Center => x - width * 0.5,
686 TextAlign::Right => x - width,
687 };
688 let (left, line_y) = (snap(left), snap(baseline));
689 if layer.dilate {
690 draw_line_merged(&mut sink, line, left, line_y, px, &style, layer);
691 } else {
692 draw_line_stacked(&mut sink, line, left, line_y, px, &style, layer);
693 }
694 baseline += metrics.line_height;
695 }
696 }
697 });
698 metrics
699}
700
701pub fn wrap_text(text: &str, max_width: f32, style: TextStyle) -> WrapLines<'_> {
714 let limit = if style.is_valid() && max_width.is_finite() {
715 (max_width / style.pixel()).max(0.)
716 } else {
717 f32::INFINITY
718 };
719 WrapLines {
720 rest: (!text.is_empty()).then_some(text),
721 paragraph: "",
722 limit,
723 face: style.face,
724 spacing: style.letter_spacing,
725 }
726}
727
728#[derive(Clone, Debug)]
730pub struct WrapLines<'a> {
731 rest: Option<&'a str>,
733 paragraph: &'a str,
735 limit: f32,
736 face: FontFace,
737 spacing: f32,
738}
739
740impl<'a> Iterator for WrapLines<'a> {
741 type Item = &'a str;
742 fn next(&mut self) -> Option<&'a str> {
743 if self.paragraph.is_empty() {
744 let rest = self.rest?;
745 let (line, tail) = match rest.find('\n') {
746 Some(i) => (&rest[..i], Some(&rest[i + 1..])),
747 None => (rest, None),
748 };
749 self.rest = tail;
750 let line = line.strip_suffix('\r').unwrap_or(line);
751 if line.is_empty() {
752 return Some(line);
753 }
754 self.paragraph = line;
755 }
756 let text = self.paragraph;
757 let mut right = 0.;
758 let mut prev: Option<char> = None;
759 let mut word_end: Option<usize> = None;
761 let mut space_break: Option<(usize, usize)> = None;
762 for (i, c) in text.char_indices() {
763 let advance = prev.map_or(0., |p| 1. + self.spacing + kern(self.face, p, c) as f32);
764 let next_right = right + advance + width_of(self.face, c).0 as f32;
765 if c == ' ' {
766 if prev.is_some_and(|p| p != ' ') {
767 word_end = Some(i);
768 }
769 } else {
770 if prev == Some(' ')
771 && let Some(end) = word_end
772 {
773 space_break = Some((end, i));
774 }
775 if next_right > self.limit + 1e-4 && i > 0 {
776 let (line, next) = match space_break {
777 Some((end, next)) => (&text[..end], &text[next..]),
778 None => (&text[..i], &text[i..]),
779 };
780 self.paragraph = next;
781 return Some(line);
782 }
783 }
784 right = next_right;
785 prev = Some(c);
786 }
787 self.paragraph = "";
788 Some(text.trim_end_matches(' '))
789 }
790}
791
792pub fn draw_text_wrapped(
802 text: &str,
803 x: f32,
804 y: f32,
805 max_width: f32,
806 style: TextStyle,
807) -> TextMetrics {
808 let mut total = measure_text_styled("", style);
809 if !style.is_valid() {
810 return total;
811 }
812 let mut baseline = y;
813 for line in wrap_text(text, max_width, style) {
814 let m = draw_text_styled(line, x, baseline, style);
815 total.width = total.width.max(m.width);
816 total.unsupported += m.unsupported;
817 total.line_count += 1;
818 baseline += total.line_height;
819 }
820 if total.line_count > 0 {
821 total.height =
822 (total.line_count - 1) as f32 * total.line_height + total.ascent + total.descent;
823 }
824 total
825}
826
827#[cfg(test)]
828mod tests {
829 use super::*;
830 use crate::shapes::tests::capture;
831
832 const WHITE: Color = Color::new(1., 1., 1., 1.);
833
834 fn coverage(vertices: &[[f32; 8]], w: usize, h: usize) -> Vec<u8> {
837 let mut grid = vec![0_u8; w * h];
838 for quad in vertices.chunks(6) {
839 let xs = quad.iter().map(|v| (v[0] + 1.) * w as f32 * 0.5);
840 let ys = quad.iter().map(|v| (1. - v[1]) * h as f32 * 0.5);
841 let (x0, x1) = xs.fold((f32::MAX, f32::MIN), |(a, b), x| (a.min(x), b.max(x)));
842 let (y0, y1) = ys.fold((f32::MAX, f32::MIN), |(a, b), y| (a.min(y), b.max(y)));
843 for py in 0..h {
844 for px in 0..w {
845 let (cx, cy) = (px as f32 + 0.5, py as f32 + 0.5);
846 if cx > x0 && cx < x1 && cy > y0 && cy < y1 {
847 grid[py * w + px] += 1;
848 }
849 }
850 }
851 }
852 grid
853 }
854
855 #[test]
856 fn measure_equals_draw_extent_for_both_faces_and_alignments() {
857 for face in [FontFace::Modern, FontFace::Classic] {
858 for align in [TextAlign::Left, TextAlign::Center, TextAlign::Right] {
859 let style = TextStyle::modern(16., WHITE)
860 .with_face(face)
861 .with_align(align);
862 let text = "Hydra Wave 7 — x×y";
863 let m = measure_text_styled(text, style);
864 let v = capture(800, 200, || {
865 draw_text_styled(text, 400., 100., style);
866 });
867 let xs = v.iter().map(|v| (v[0] + 1.) * 400.);
868 let (lo, hi) = xs.fold((f32::MAX, f32::MIN), |(a, b), x| (a.min(x), b.max(x)));
869 let expect_left = match align {
870 TextAlign::Left => 400.,
871 TextAlign::Center => 400. - m.width / 2.,
872 TextAlign::Right => 400. - m.width,
873 };
874 assert!(
875 (lo - expect_left.round()).abs() < 1e-3,
876 "{face:?} {align:?} {lo}"
877 );
878 assert!(
879 (hi - lo - m.width).abs() < 1e-3,
880 "{face:?} {align:?} {}",
881 hi - lo
882 );
883 }
884 }
885 }
886
887 #[test]
888 fn merged_runs_cover_exactly_the_lit_pixels_without_overlap() {
889 let text = "Quick fox, jumpy dwarves! 0123456789 ÀÉÎõü ★♥→";
890 let style = TextStyle::modern(8., WHITE);
891 let v = capture(400, 40, || {
892 draw_text_styled(text, 2., 20., style);
893 });
894 let grid = coverage(&v, 400, 40);
895 assert!(grid.iter().all(|&n| n <= 1), "runs overlap");
896 let lit: usize = text
897 .chars()
898 .map(|c| {
899 modern(c)
900 .0
901 .rows
902 .iter()
903 .map(|r| r.count_ones() as usize)
904 .sum::<usize>()
905 })
906 .sum();
907 assert_eq!(grid.iter().filter(|&&n| n == 1).count(), lit);
908 assert!(
910 v.len() / 6 < lit * 2 / 5,
911 "{} quads for {lit} pixels",
912 v.len() / 6
913 );
914 }
915
916 const HUD: [&str; 10] = [
917 "SCORE 012480",
918 "BEST 98000",
919 "WAVE 7/10",
920 "LIVES 3",
921 "COMBO X12",
922 "HEALTH 87%",
923 "TIME 02:15.40",
924 "PRESS SPACE TO JUMP",
925 "PAUSED - ESC TO RESUME",
926 "GEMS 14 / 20 KEYS 2",
927 ];
928
929 #[test]
930 fn legacy_draw_text_ex_merges_row_runs_and_styled_text_saves_vertices() {
931 use crate::{TextParams, draw_text_ex};
932 let (w, h) = (420, 240);
933 let v = capture(w as u32, h as u32, || {
934 for (i, line) in HUD.iter().enumerate() {
935 draw_text_ex(
936 line,
937 4.,
938 20. + i as f32 * 22.,
939 TextParams {
940 font_size: 16,
941 font_scale: 1.,
942 color: WHITE,
943 },
944 );
945 }
946 });
947 let mut expected = vec![0_u8; w * h];
949 let (mut lit, mut runs) = (0, 0);
950 for (i, line) in HUD.iter().enumerate() {
951 for (k, c) in line.chars().enumerate() {
952 for (row, bits) in font::glyph(c).into_iter().enumerate() {
953 for col in 0..5 {
954 let on = |col: usize| col < 5 && bits & (1 << (4 - col)) != 0;
955 if on(col) {
956 lit += 1;
957 runs += usize::from(col == 0 || !on(col - 1));
958 let x0 = 4 + k * 12 + col * 2;
959 let y0 = (20 + i * 22) - 14 + row * 2;
960 for y in y0..y0 + 2 {
961 for x in x0..x0 + 2 {
962 expected[y * w + x] = 1;
963 }
964 }
965 }
966 }
967 }
968 }
969 }
970 assert_eq!(coverage(&v, w, h), expected);
971 assert_eq!(v.len(), runs * 6);
975 assert!(runs * 3 < lit * 2, "runs {runs}, lit pixels {lit}");
976 for quad in v.chunks(6) {
977 let ys = quad.iter().map(|v| (1. - v[1]) * h as f32 * 0.5);
978 let (lo, hi) = ys.fold((f32::MAX, f32::MIN), |(lo, hi), y| (lo.min(y), hi.max(y)));
979 assert!((hi - lo - 2.).abs() < 1e-3, "{lo}..{hi}");
980 }
981 let reference = capture(w as u32, h as u32, || {
982 for (i, line) in HUD.iter().enumerate() {
983 let mut x = 4.;
984 for c in line.chars() {
985 for (row, bits) in font::glyph(c).into_iter().enumerate() {
986 for col in 0..5 {
987 if bits & (1 << (4 - col)) != 0 {
988 let y = 20. + i as f32 * 22. - 14. + row as f32 * 2.;
989 crate::draw_rectangle(x + col as f32 * 2., y, 2., 2., WHITE);
990 }
991 }
992 }
993 x += 12.;
994 }
995 }
996 });
997 assert_eq!(reference.len(), lit * 6);
998 assert_eq!(coverage(&v, w, h), coverage(&reference, w, h));
999 let per_pixel = lit * 6;
1000 let modern = capture(w as u32, h as u32, || {
1001 for (i, line) in HUD.iter().enumerate() {
1002 draw_text_styled(
1003 line,
1004 4.,
1005 20. + i as f32 * 28.,
1006 TextStyle::modern(16., WHITE),
1007 );
1008 }
1009 })
1010 .len();
1011 let classic_styled = capture(w as u32, h as u32, || {
1012 for (i, line) in HUD.iter().enumerate() {
1013 draw_text_styled(
1014 line,
1015 4.,
1016 20. + i as f32 * 22.,
1017 TextStyle::classic(16., WHITE),
1018 );
1019 }
1020 })
1021 .len();
1022 println!(
1023 "HUD vertices: per-pixel {per_pixel}, classic draw_text_ex runs {}, classic styled {classic_styled} \
1024 ({:.0}% fewer), modern styled {modern} ({:.0}% fewer)",
1025 v.len(),
1026 100. * (1. - classic_styled as f32 / per_pixel as f32),
1027 100. * (1. - modern as f32 / per_pixel as f32),
1028 );
1029 assert!(classic_styled * 2 < per_pixel && modern * 2 < per_pixel);
1030 }
1031
1032 #[test]
1033 fn outline_and_shadow_layers_merge_and_order_back_to_front() {
1034 let style = TextStyle::modern(8., WHITE)
1035 .with_outline(Color::new(0., 0., 0., 0.5))
1036 .with_shadow(Color::new(0., 0., 1., 0.5));
1037 let v = capture(100, 30, || {
1038 draw_text_styled("ab", 10., 15., style);
1039 });
1040 assert_eq!(v[0][6], 1.);
1042 assert_eq!(v.last().unwrap()[4], 1.);
1043 let outline: Vec<_> = v
1044 .iter()
1045 .filter(|v| v[7] == 0.5 && v[6] == 0.)
1046 .copied()
1047 .collect();
1048 let grid = coverage(&outline, 100, 30);
1049 assert!(
1050 grid.iter().all(|&n| n <= 1),
1051 "translucent outline double-blends"
1052 );
1053 let m = measure_text_styled("ab", style);
1054 let (lo, hi) = outline
1055 .iter()
1056 .map(|v| (v[0] + 1.) * 50.)
1057 .fold((f32::MAX, f32::MIN), |(a, b), x| (a.min(x), b.max(x)));
1058 assert!(
1059 (lo - 9.).abs() < 1e-3 && (hi - 11. - m.width).abs() < 1e-3,
1060 "{lo} {hi}"
1061 );
1062 }
1063
1064 #[test]
1065 fn wrapping_respects_width_newlines_and_long_words() {
1066 let s = TextStyle::modern(8., WHITE);
1067 let all: Vec<_> = wrap_text("a\n\nbb cc\r\nsupercalifragilistic", 20., s).collect();
1068 assert_eq!(all[..4], ["a", "", "bb", "cc"]);
1069 assert!(
1070 all[4..]
1071 .iter()
1072 .all(|l| text_width(l, s) <= 20. && !l.is_empty())
1073 );
1074 assert_eq!(all[4..].concat(), "supercalifragilistic");
1075 assert_eq!(wrap_text("", 10., s).count(), 0);
1076 assert_eq!(wrap_text("x", 0., s).collect::<Vec<_>>(), ["x"]);
1077 let m = draw_text_wrapped("one two three four", 0., 20., 40., s);
1078 assert_eq!(
1079 m.line_count,
1080 wrap_text("one two three four", 40., s).count()
1081 );
1082 }
1083
1084 #[test]
1085 fn tabular_digits_kerning_and_invalid_styles() {
1086 let s = TextStyle::modern(8., WHITE);
1087 let w = text_width("0000", s);
1088 for n in ["1111", "1234", "9876", "7171"] {
1089 assert_eq!(text_width(n, s), w);
1090 }
1091 assert_eq!(text_width("To", s), text_width("T", s) + text_width("o", s));
1092 assert_eq!(
1093 text_width("Ta", s) + 1.,
1094 text_width("T", s) + 1. + text_width("a", s)
1095 );
1096 assert_eq!(measure_text_styled("☃", s).unsupported, 1);
1097 let bad = TextStyle::modern(f32::NAN, WHITE);
1098 assert_eq!(measure_text_styled("abc", bad).line_count, 0);
1099 assert!(
1100 capture(64, 64, || {
1101 draw_text_styled("abc", 0., 10., bad);
1102 draw_text_styled("abc", f32::INFINITY, 10., s);
1103 })
1104 .is_empty()
1105 );
1106 }
1107}