1mod font_bitmap;
4mod font_sdf;
5pub(crate) mod font_ttf;
6mod pixel;
7
8pub(crate) use font_ttf as ttf_atlas;
9pub use font_ttf::{
10 get_cached_glyph_styled_q4, register_font_bytes, register_font_vec,
11 registered_custom_font_count,
12};
13pub use pixel::{PixelFormat, Rgb565, Rgba8888, SpriteFormat, Xrgb8888};
14
15use crate::solver::Region;
16
17pub trait DisplaySurface {
19 type Pixel: PixelFormat;
20 fn viewport(&self) -> Region;
22}
23
24#[inline]
26pub fn measure_char_advance(ch: char, font_size: u8) -> i16 {
27 {
28 if let Some(adv) = ttf_atlas::measure_ttf_char_advance(ch, font_size) {
29 return adv.max(2);
30 }
31 }
32 let cw = if ch.is_ascii() {
33 ((font_size as i16) * 6 + 5) / 10
34 } else if ch == '°' {
35 ((font_size as i16) * 5 + 5) / 10
36 } else {
37 font_size as i16
38 }
39 .max(4);
40 cw
41}
42
43#[inline]
45pub fn measure_char_kerning(prev: char, curr: char, font_size: u8) -> i16 {
46 {
47 return ttf_atlas::measure_ttf_kerning(prev, curr, font_size);
48 }
49}
50
51#[inline]
53pub fn measure_char_advance_f32(ch: char, font_size: u8) -> f32 {
54 {
55 if let Some(adv) = ttf_atlas::measure_ttf_char_advance_f32(ch, font_size) {
56 return adv.max(1.0);
57 }
58 }
59 measure_char_advance(ch, font_size) as f32
60}
61
62#[inline]
64pub fn measure_char_advance_styled_f32(
65 ch: char,
66 font_size: u8,
67 spec: crate::text_rich::FontSpec,
68) -> f32 {
69 {
70 if let Some(adv) = ttf_atlas::measure_ttf_char_advance_styled_f32(ch, font_size, spec) {
71 return adv.max(1.0);
72 }
73 }
74 let base = measure_char_advance_f32(ch, font_size);
75 if spec.weight.is_bold() {
76 base + 0.8
77 } else {
78 base
79 }
80}
81
82#[inline]
84pub fn measure_char_kerning_f32(prev: char, curr: char, font_size: u8) -> f32 {
85 {
86 return ttf_atlas::measure_ttf_kerning_f32(prev, curr, font_size);
87 }
88}
89
90pub fn measure_line_width_f32(line: &str, font_size: u8) -> f32 {
95 if line.is_empty() {
96 return 0.0;
97 }
98 if ttf_atlas::has_system_font() {
99 if let Some(lw) = ttf_atlas::measure_ttf_line_width_f32(line, font_size) {
100 return lw;
101 }
102 }
103 let mut cur_w: f32 = 0.0;
104 let mut prev_ch: Option<char> = None;
105 for ch in line.chars() {
106 if let Some(p) = prev_ch {
107 cur_w += measure_char_kerning_f32(p, ch, font_size);
108 }
109 cur_w = (cur_w + measure_char_advance_f32(ch, font_size)).max(0.0);
110 prev_ch = Some(ch);
111 }
112 cur_w
113}
114
115pub fn measure_line_width_px(line: &str, font_size: u8) -> i16 {
117 if line.is_empty() {
118 return 0;
119 }
120 if ttf_atlas::has_system_font() {
121 if let Some(lw) = ttf_atlas::measure_ttf_line_width_exact(line, font_size) {
122 return lw;
123 }
124 }
125 let mut cur_w: i16 = 0;
126 let mut prev_ch: Option<char> = None;
127 for ch in line.chars() {
128 if let Some(p) = prev_ch {
129 cur_w = cur_w.saturating_add(measure_char_kerning(p, ch, font_size));
130 }
131 cur_w = cur_w.saturating_add(measure_char_advance(ch, font_size)).max(0);
132 prev_ch = Some(ch);
133 }
134 cur_w
135}
136
137pub fn next_wrapped_line<'a>(text: &'a str, font_size: u8, avail_w: i16) -> (&'a str, &'a str) {
139 if text.is_empty() {
140 return ("", "");
141 }
142 if ttf_atlas::has_system_font() {
143 let avail_f = (avail_w.max(0) as f32) + 0.01;
144 let mut line_w = 0.0f32;
145 let mut prev_ch: Option<char> = None;
146 let mut last_space_end: Option<usize> = None;
147 let mut last_space_next: usize = 0;
148
149 for (byte_idx, ch) in text.char_indices() {
150 if ch == '\n' {
151 return (&text[..byte_idx], &text[byte_idx + 1..]);
152 }
153 let kern = prev_ch
154 .map(|p| ttf_atlas::measure_ttf_kerning_f32(p, ch, font_size))
155 .unwrap_or(0.0);
156 let cw = ttf_atlas::measure_ttf_char_advance_f32(ch, font_size)
157 .unwrap_or_else(|| measure_char_advance(ch, font_size) as f32);
158 let step_w = cw + kern;
159 if ch == ' ' {
160 last_space_end = Some(byte_idx);
161 last_space_next = byte_idx + 1;
162 }
163 if line_w > 0.0 && (line_w + step_w) > avail_f {
164 if let Some(sp_end) = last_space_end {
165 if sp_end > 0 {
166 return (
167 &text[..sp_end],
168 text[last_space_next..].trim_start_matches(' '),
169 );
170 }
171 }
172 return (&text[..byte_idx], &text[byte_idx..]);
173 }
174 line_w = (line_w + step_w).max(0.0);
175 prev_ch = Some(ch);
176 }
177 return (text, "");
178 }
179
180 let mut line_w: i16 = 0;
181 let mut prev_ch: Option<char> = None;
182 let mut last_space_end: Option<usize> = None;
183 let mut last_space_next: usize = 0;
184
185 for (byte_idx, ch) in text.char_indices() {
186 if ch == '\n' {
187 return (&text[..byte_idx], &text[byte_idx + 1..]);
188 }
189 let kern = prev_ch
190 .map(|p| measure_char_kerning(p, ch, font_size))
191 .unwrap_or(0);
192 let cw = measure_char_advance(ch, font_size);
193 let step_w = cw.saturating_add(kern);
194 if ch == ' ' {
195 last_space_end = Some(byte_idx);
196 last_space_next = byte_idx + 1;
197 }
198 if line_w > 0 && line_w.saturating_add(step_w) > avail_w {
199 if let Some(sp_end) = last_space_end {
200 if sp_end > 0 {
201 return (&text[..sp_end], text[last_space_next..].trim_start_matches(' '));
202 }
203 }
204 return (&text[..byte_idx], &text[byte_idx..]);
205 }
206 line_w = line_w.saturating_add(step_w).max(0);
207 prev_ch = Some(ch);
208 }
209 (text, "")
210}
211
212#[inline(always)]
214pub const fn text_line_height_px(font_size: u8) -> i16 {
215 let h = ((font_size as i16) * 5) / 4;
216 if h > 10 { h } else { 10 }
217}
218
219#[derive(Copy, Clone)]
220struct TextMetricCacheEntry {
221 key_hash: u64,
222 text_len: u32,
223 font_size: u8,
224 avail_w: i16,
225 single_line: bool,
226 atlas_ptr: usize,
227 width: i16,
228 height: i16,
229 lines: i16,
230}
231
232impl TextMetricCacheEntry {
233 const EMPTY: Self = Self {
234 key_hash: 0,
235 text_len: u32::MAX,
236 font_size: 0,
237 avail_w: 0,
238 single_line: false,
239 atlas_ptr: 0,
240 width: 0,
241 height: 0,
242 lines: 0,
243 };
244}
245
246const TEXT_CACHE_SLOTS: usize = 256;
247
248std::thread_local! {
249 static TLS_TEXT_METRICS: core::cell::RefCell<[TextMetricCacheEntry; TEXT_CACHE_SLOTS]> =
250 const { core::cell::RefCell::new([TextMetricCacheEntry::EMPTY; TEXT_CACHE_SLOTS]) };
251}
252
253#[inline]
254fn hash_text_key(text: &str) -> u64 {
255 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
256 for &b in text.as_bytes() {
257 h ^= b as u64;
258 h = h.wrapping_mul(0x0100_0000_01b3);
259 }
260 h
261}
262
263pub fn count_text_lines(text: &str, font_size: u8, avail_w: i16, single_line: bool) -> i16 {
265 if text.is_empty() || single_line || avail_w <= 0 {
266 return 1;
267 }
268 let (key_hash, slot_idx, atlas_ptr) = {
269 let kh = hash_text_key(text);
270 let ap = 0usize;
271 let idx = ((kh as usize)
272 ^ ((font_size as usize) << 4)
273 ^ ((avail_w as usize) << 1)
274 ^ (single_line as usize))
275 & (TEXT_CACHE_SLOTS - 1);
276 if let Some(cached_lines) = TLS_TEXT_METRICS.with(|tls| {
277 let e = &tls.borrow()[idx];
278 if e.key_hash == kh
279 && e.text_len == text.len() as u32
280 && e.font_size == font_size
281 && e.avail_w == avail_w
282 && e.single_line == single_line
283 && e.atlas_ptr == ap
284 && e.lines > 0
285 {
286 Some(e.lines)
287 } else {
288 None
289 }
290 }) {
291 return cached_lines;
292 }
293 (kh, idx, ap)
294 };
295
296 let mut lines: i16 = 0;
297 let mut rem = text;
298 while !rem.is_empty() {
299 lines = lines.saturating_add(1);
300 let (_, next_rem) = next_wrapped_line(rem, font_size, avail_w);
301 if next_rem.len() == rem.len() {
302 break;
303 }
304 rem = next_rem;
305 }
306 let result = lines.max(1);
307
308 TLS_TEXT_METRICS.with(|tls| {
309 let mut borrow = tls.borrow_mut();
310 borrow[slot_idx] = TextMetricCacheEntry {
311 key_hash,
312 text_len: text.len() as u32,
313 font_size,
314 avail_w,
315 single_line,
316 atlas_ptr,
317 width: 0,
318 height: text_line_height_px(font_size),
319 lines: result,
320 };
321 });
322
323 result
324}
325
326pub fn measure_text_px(text: &str, font_size: u8) -> (i16, i16) {
328 let h = text_line_height_px(font_size);
329 if text.is_empty() {
330 return (2, h);
331 }
332
333 let (key_hash, slot_idx, atlas_ptr) = {
334 let kh = hash_text_key(text);
335 let ap = 0usize;
336 let idx = ((kh as usize) ^ ((font_size as usize) << 3) ^ 0x5A) & (TEXT_CACHE_SLOTS - 1);
337 if let Some(hit) = TLS_TEXT_METRICS.with(|tls| {
338 let e = &tls.borrow()[idx];
339 if e.key_hash == kh
340 && e.text_len == text.len() as u32
341 && e.font_size == font_size
342 && e.avail_w == -1
343 && e.atlas_ptr == ap
344 && e.width > 0
345 {
346 Some((e.width, e.height))
347 } else {
348 None
349 }
350 }) {
351 return hit;
352 }
353 (kh, idx, ap)
354 };
355
356 let mut max_w: i16 = 0;
357 for line in text.split('\n') {
358 max_w = max_w.max(measure_line_width_px(line, font_size));
359 }
360 let w = max_w.saturating_add(2).max(2);
363
364 TLS_TEXT_METRICS.with(|tls| {
365 let mut borrow = tls.borrow_mut();
366 borrow[slot_idx] = TextMetricCacheEntry {
367 key_hash,
368 text_len: text.len() as u32,
369 font_size,
370 avail_w: -1,
371 single_line: true,
372 atlas_ptr,
373 width: w,
374 height: h,
375 lines: 1,
376 };
377 });
378
379 (w, h)
380}
381
382pub fn sample_glyph_coverage(ch: char, rel_x: i16, rel_y: i16, char_w: i16, char_h: i16) -> u8 {
384 if rel_x < 0 || rel_y < 0 || rel_x >= char_w || rel_y >= char_h || char_w <= 0 || char_h <= 0 {
385 return 0;
386 }
387
388
389 if let Some(cov) = font_sdf::sample_vector_sdf_char(ch, rel_x, rel_y, char_w, char_h) {
390 return cov;
391 }
392
393 if ch.is_ascii() {
394 let gx_fp = ((rel_x as i32) * 8 * 16) / (char_w as i32);
395 let gy_fp = ((rel_y as i32) * 16 * 16) / (char_h as i32);
396 font_bitmap::sample_8x16_bilinear(font_bitmap::ascii_or_deg_bitmap(ch), gx_fp, gy_fp)
397 } else {
398 let gx_fp = ((rel_x as i32) * 16 * 16) / (char_w as i32);
399 let gy_fp = ((rel_y as i32) * 16 * 16) / (char_h as i32);
400 font_bitmap::sample_16x16_bilinear(font_bitmap::fallback_unihan_bitmap(ch), gx_fp, gy_fp)
401 }
402}