blinc_text 0.5.1

High-quality text rendering for Blinc UI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
//! Glyph atlas management
//!
//! Manages a texture atlas for caching rendered glyphs. Uses a skyline/shelf
//! packing algorithm for efficient space utilization.
//!
//! Provides two atlas types:
//! - `GlyphAtlas`: Grayscale atlas for regular text glyphs
//! - `ColorGlyphAtlas`: RGBA atlas for color emoji

use crate::{Result, TextError};
use rustc_hash::FxHashMap;

/// Region in the atlas texture
#[derive(Debug, Clone, Copy)]
pub struct AtlasRegion {
    /// X position in atlas (pixels)
    pub x: u32,
    /// Y position in atlas (pixels)
    pub y: u32,
    /// Width in atlas (pixels)
    pub width: u32,
    /// Height in atlas (pixels)
    pub height: u32,
}

impl AtlasRegion {
    /// Get UV coordinates for this region given atlas dimensions
    pub fn uv_bounds(&self, atlas_width: u32, atlas_height: u32) -> [f32; 4] {
        let u_min = self.x as f32 / atlas_width as f32;
        let v_min = self.y as f32 / atlas_height as f32;
        let u_max = (self.x + self.width) as f32 / atlas_width as f32;
        let v_max = (self.y + self.height) as f32 / atlas_height as f32;
        [u_min, v_min, u_max, v_max]
    }
}

/// Information about a cached glyph
#[derive(Debug, Clone, Copy)]
pub struct GlyphInfo {
    /// Region in the atlas texture
    pub region: AtlasRegion,
    /// Horizontal bearing (offset from origin to left edge)
    pub bearing_x: i16,
    /// Vertical bearing (offset from baseline to top edge)
    pub bearing_y: i16,
    /// Horizontal advance to next glyph
    pub advance: u16,
    /// Font size this glyph was rasterized at
    pub font_size: f32,
}

/// Key for glyph cache lookup
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct GlyphKey {
    /// Font ID (hash of font name/family)
    font_id: u32,
    /// Glyph ID in the font
    glyph_id: u16,
    /// Font size (quantized to avoid too many entries)
    size_key: u16,
}

impl GlyphKey {
    fn new(font_id: u32, glyph_id: u16, font_size: f32) -> Self {
        // Quantize font size to reduce cache entries (0.5px granularity)
        let size_key = (font_size * 2.0).round() as u16;
        Self {
            font_id,
            glyph_id,
            size_key,
        }
    }
}

/// A shelf in the skyline packing algorithm
#[derive(Debug)]
struct Shelf {
    /// Y position of this shelf
    y: u32,
    /// Height of this shelf
    height: u32,
    /// Current X position (next free space)
    x: u32,
}

/// Glyph atlas for caching rendered glyphs
pub struct GlyphAtlas {
    /// Atlas width in pixels
    width: u32,
    /// Atlas height in pixels
    height: u32,
    /// Pixel data (single channel, 8-bit grayscale or SDF values)
    pixels: Vec<u8>,
    /// Cached glyph information
    glyphs: FxHashMap<GlyphKey, GlyphInfo>,
    /// Shelves for skyline packing
    shelves: Vec<Shelf>,
    /// Padding between glyphs
    padding: u32,
    /// Whether atlas data has been modified since last upload
    dirty: bool,
}

impl GlyphAtlas {
    /// Maximum atlas dimension (4096×4096 = 16 MB for R8)
    const MAX_SIZE: u32 = 4096;

    /// Create a new glyph atlas
    pub fn new(width: u32, height: u32) -> Self {
        Self {
            width,
            height,
            pixels: vec![0; (width * height) as usize],
            glyphs: FxHashMap::default(),
            shelves: Vec::new(),
            padding: 2, // 2 pixel padding between glyphs
            dirty: true,
        }
    }

    /// Get atlas dimensions
    pub fn dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// Get raw pixel data
    pub fn pixels(&self) -> &[u8] {
        &self.pixels
    }

    /// Check if atlas has been modified
    pub fn is_dirty(&self) -> bool {
        self.dirty
    }

    /// Mark atlas as clean (after GPU upload)
    pub fn mark_clean(&mut self) {
        self.dirty = false;
    }

    /// Look up a cached glyph
    pub fn get_glyph(&self, font_id: u32, glyph_id: u16, font_size: f32) -> Option<&GlyphInfo> {
        let key = GlyphKey::new(font_id, glyph_id, font_size);
        self.glyphs.get(&key)
    }

    /// Allocate space for a glyph using skyline packing
    fn allocate(&mut self, width: u32, height: u32) -> Result<AtlasRegion> {
        let padded_width = width + self.padding;
        let padded_height = height + self.padding;

        // Find best shelf (smallest height that fits)
        let mut best_shelf = None;
        let mut best_y = u32::MAX;

        for (i, shelf) in self.shelves.iter().enumerate() {
            // Check if glyph fits in this shelf
            if shelf.height >= padded_height
                && shelf.x + padded_width <= self.width
                && shelf.y < best_y
            {
                best_y = shelf.y;
                best_shelf = Some(i);
            }
        }

        if let Some(shelf_idx) = best_shelf {
            // Use existing shelf
            let shelf = &mut self.shelves[shelf_idx];
            let region = AtlasRegion {
                x: shelf.x,
                y: shelf.y,
                width,
                height,
            };
            shelf.x += padded_width;
            return Ok(region);
        }

        // Create new shelf
        let new_y = self.shelves.last().map(|s| s.y + s.height).unwrap_or(0);

        if new_y + padded_height > self.height {
            return Err(TextError::AtlasFull);
        }

        let region = AtlasRegion {
            x: 0,
            y: new_y,
            width,
            height,
        };

        self.shelves.push(Shelf {
            y: new_y,
            height: padded_height,
            x: padded_width,
        });

        Ok(region)
    }

    /// Insert a rasterized glyph into the atlas
    #[allow(clippy::too_many_arguments)]
    pub fn insert_glyph(
        &mut self,
        font_id: u32,
        glyph_id: u16,
        font_size: f32,
        width: u32,
        height: u32,
        bearing_x: i16,
        bearing_y: i16,
        advance: u16,
        bitmap: &[u8],
    ) -> Result<GlyphInfo> {
        let key = GlyphKey::new(font_id, glyph_id, font_size);

        // Check if already cached
        if let Some(info) = self.glyphs.get(&key) {
            return Ok(*info);
        }

        // Allocate region
        let region = self.allocate(width, height)?;

        // Copy bitmap to atlas
        for y in 0..height {
            let src_offset = (y * width) as usize;
            let dst_offset = ((region.y + y) * self.width + region.x) as usize;
            let row_end = src_offset + width as usize;

            if row_end <= bitmap.len() && dst_offset + width as usize <= self.pixels.len() {
                self.pixels[dst_offset..dst_offset + width as usize]
                    .copy_from_slice(&bitmap[src_offset..row_end]);
            }
        }

        let info = GlyphInfo {
            region,
            bearing_x,
            bearing_y,
            advance,
            font_size,
        };

        self.glyphs.insert(key, info);
        self.dirty = true;

        Ok(info)
    }

    /// Double the atlas dimensions and repack existing pixel data.
    ///
    /// Old pixel data is copied into the top-left quadrant of the new buffer.
    /// Existing `AtlasRegion` pixel coords remain valid because `uv_bounds()`
    /// recomputes UVs dynamically from the (now larger) atlas dimensions.
    /// Returns `true` if growth succeeded, `false` if already at max size.
    pub fn grow(&mut self) -> bool {
        let new_width = (self.width * 2).min(Self::MAX_SIZE);
        let new_height = (self.height * 2).min(Self::MAX_SIZE);

        if new_width == self.width && new_height == self.height {
            return false; // Already at max size
        }

        // Copy old pixel data row-by-row into top-left of new buffer
        let mut new_pixels = vec![0u8; (new_width * new_height) as usize];
        for y in 0..self.height {
            let src_start = (y * self.width) as usize;
            let src_end = src_start + self.width as usize;
            let dst_start = (y * new_width) as usize;
            let dst_end = dst_start + self.width as usize;
            new_pixels[dst_start..dst_end].copy_from_slice(&self.pixels[src_start..src_end]);
        }

        self.pixels = new_pixels;
        self.width = new_width;
        self.height = new_height;
        self.dirty = true;
        true
    }

    /// Clear all cached glyphs
    pub fn clear(&mut self) {
        self.glyphs.clear();
        self.shelves.clear();
        self.pixels.fill(0);
        self.dirty = true;
    }

    /// Get number of cached glyphs
    pub fn glyph_count(&self) -> usize {
        self.glyphs.len()
    }

    /// Calculate atlas utilization (0.0 to 1.0)
    pub fn utilization(&self) -> f32 {
        let used_height = self.shelves.last().map(|s| s.y + s.height).unwrap_or(0);
        used_height as f32 / self.height as f32
    }
}

impl Default for GlyphAtlas {
    fn default() -> Self {
        // 1024x1024 atlas (1 MB for R8) — large enough for most UIs without growing.
        // grow() doubles dimensions (up to 4096) if more space is needed.
        Self::new(1024, 1024)
    }
}

impl std::fmt::Debug for GlyphAtlas {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GlyphAtlas")
            .field("dimensions", &(self.width, self.height))
            .field("glyph_count", &self.glyphs.len())
            .field(
                "utilization",
                &format!("{:.1}%", self.utilization() * 100.0),
            )
            .field("dirty", &self.dirty)
            .finish()
    }
}

/// Color glyph atlas for RGBA emoji
///
/// Similar to GlyphAtlas but stores RGBA pixel data (4 bytes per pixel)
/// for color emoji and other color glyphs.
pub struct ColorGlyphAtlas {
    /// Atlas width in pixels
    width: u32,
    /// Atlas height in pixels
    height: u32,
    /// Pixel data (RGBA, 4 bytes per pixel)
    pixels: Vec<u8>,
    /// Cached glyph information
    glyphs: FxHashMap<GlyphKey, GlyphInfo>,
    /// Shelves for skyline packing
    shelves: Vec<Shelf>,
    /// Padding between glyphs
    padding: u32,
    /// Whether atlas data has been modified since last upload
    dirty: bool,
}

impl ColorGlyphAtlas {
    /// Maximum atlas dimension (4096×4096 = 64 MB for RGBA)
    const MAX_SIZE: u32 = 4096;

    /// Create a new color glyph atlas
    pub fn new(width: u32, height: u32) -> Self {
        Self {
            width,
            height,
            pixels: vec![0; (width * height * 4) as usize], // RGBA = 4 bytes per pixel
            glyphs: FxHashMap::default(),
            shelves: Vec::new(),
            padding: 2,
            dirty: true,
        }
    }

    /// Get atlas dimensions
    pub fn dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// Get raw pixel data (RGBA format)
    pub fn pixels(&self) -> &[u8] {
        &self.pixels
    }

    /// Check if atlas has been modified
    pub fn is_dirty(&self) -> bool {
        self.dirty
    }

    /// Mark atlas as clean (after GPU upload)
    pub fn mark_clean(&mut self) {
        self.dirty = false;
    }

    /// Look up a cached glyph
    pub fn get_glyph(&self, font_id: u32, glyph_id: u16, font_size: f32) -> Option<&GlyphInfo> {
        let key = GlyphKey::new(font_id, glyph_id, font_size);
        self.glyphs.get(&key)
    }

    /// Allocate space for a glyph using skyline packing
    fn allocate(&mut self, width: u32, height: u32) -> Result<AtlasRegion> {
        let padded_width = width + self.padding;
        let padded_height = height + self.padding;

        // Find best shelf (smallest height that fits)
        let mut best_shelf = None;
        let mut best_y = u32::MAX;

        for (i, shelf) in self.shelves.iter().enumerate() {
            if shelf.height >= padded_height
                && shelf.x + padded_width <= self.width
                && shelf.y < best_y
            {
                best_y = shelf.y;
                best_shelf = Some(i);
            }
        }

        if let Some(shelf_idx) = best_shelf {
            let shelf = &mut self.shelves[shelf_idx];
            let region = AtlasRegion {
                x: shelf.x,
                y: shelf.y,
                width,
                height,
            };
            shelf.x += padded_width;
            return Ok(region);
        }

        // Create new shelf
        let new_y = self.shelves.last().map(|s| s.y + s.height).unwrap_or(0);

        if new_y + padded_height > self.height {
            return Err(TextError::AtlasFull);
        }

        let region = AtlasRegion {
            x: 0,
            y: new_y,
            width,
            height,
        };

        self.shelves.push(Shelf {
            y: new_y,
            height: padded_height,
            x: padded_width,
        });

        Ok(region)
    }

    /// Insert a rasterized color glyph (RGBA) into the atlas
    #[allow(clippy::too_many_arguments)]
    pub fn insert_glyph(
        &mut self,
        font_id: u32,
        glyph_id: u16,
        font_size: f32,
        width: u32,
        height: u32,
        bearing_x: i16,
        bearing_y: i16,
        advance: u16,
        bitmap: &[u8],
    ) -> Result<GlyphInfo> {
        let key = GlyphKey::new(font_id, glyph_id, font_size);

        // Check if already cached
        if let Some(info) = self.glyphs.get(&key) {
            return Ok(*info);
        }

        // Allocate region
        let region = self.allocate(width, height)?;

        // Copy RGBA bitmap to atlas (4 bytes per pixel)
        for y in 0..height {
            let src_offset = (y * width * 4) as usize;
            let dst_offset = ((region.y + y) * self.width * 4 + region.x * 4) as usize;
            let row_bytes = (width * 4) as usize;

            if src_offset + row_bytes <= bitmap.len() && dst_offset + row_bytes <= self.pixels.len()
            {
                self.pixels[dst_offset..dst_offset + row_bytes]
                    .copy_from_slice(&bitmap[src_offset..src_offset + row_bytes]);
            }
        }

        let info = GlyphInfo {
            region,
            bearing_x,
            bearing_y,
            advance,
            font_size,
        };

        self.glyphs.insert(key, info);
        self.dirty = true;

        Ok(info)
    }

    /// Double the atlas dimensions and repack existing pixel data (RGBA).
    ///
    /// Same approach as `GlyphAtlas::grow()` but with 4 bytes per pixel.
    /// Returns `true` if growth succeeded, `false` if already at max size.
    pub fn grow(&mut self) -> bool {
        let new_width = (self.width * 2).min(Self::MAX_SIZE);
        let new_height = (self.height * 2).min(Self::MAX_SIZE);

        if new_width == self.width && new_height == self.height {
            return false;
        }

        let mut new_pixels = vec![0u8; (new_width * new_height * 4) as usize];
        for y in 0..self.height {
            let src_start = (y * self.width * 4) as usize;
            let row_bytes = (self.width * 4) as usize;
            let dst_start = (y * new_width * 4) as usize;
            new_pixels[dst_start..dst_start + row_bytes]
                .copy_from_slice(&self.pixels[src_start..src_start + row_bytes]);
        }

        self.pixels = new_pixels;
        self.width = new_width;
        self.height = new_height;
        self.dirty = true;
        true
    }

    /// Clear all cached glyphs
    pub fn clear(&mut self) {
        self.glyphs.clear();
        self.shelves.clear();
        self.pixels.fill(0);
        self.dirty = true;
    }

    /// Get number of cached glyphs
    pub fn glyph_count(&self) -> usize {
        self.glyphs.len()
    }

    /// Calculate atlas utilization (0.0 to 1.0)
    pub fn utilization(&self) -> f32 {
        let used_height = self.shelves.last().map(|s| s.y + s.height).unwrap_or(0);
        used_height as f32 / self.height as f32
    }
}

impl Default for ColorGlyphAtlas {
    fn default() -> Self {
        // 512x512 atlas (1 MB for RGBA) — sufficient for typical emoji usage.
        // grow() doubles dimensions (up to 4096) if more space is needed.
        Self::new(512, 512)
    }
}

impl std::fmt::Debug for ColorGlyphAtlas {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ColorGlyphAtlas")
            .field("dimensions", &(self.width, self.height))
            .field("glyph_count", &self.glyphs.len())
            .field(
                "utilization",
                &format!("{:.1}%", self.utilization() * 100.0),
            )
            .field("dirty", &self.dirty)
            .finish()
    }
}