kas-core 0.17.0

KAS GUI / core
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
//     https://www.apache.org/licenses/LICENSE-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
//     https://www.apache.org/licenses/LICENSE-2.0

//! Text drawing pipeline

use kas::cast::traits::*;
use kas::config::RasterConfig;
use kas::draw::{AllocError, Allocation, PassId, color::Rgba};
use kas::geom::{Quad, Vec2};
use kas_text::fonts::{self, FaceId};
use kas_text::{Effect, Glyph, GlyphId, TextDisplay};
use rustc_hash::FxHashMap as HashMap;
use swash::zeno::Format;

use crate::config::SubpixelMode;

/// Number of sub-pixel text sizes
///
/// Text `dpem * SCALE_STEPS` is rounded to the nearest integer, so for example
/// `SCALE_STEPS = 4.0` would support a text size of 5.25 pixels per Em.
/// In practice it's not very useful to support fractional text sizes.
const SCALE_STEPS: f32 = 1.0;

/// Support allocation of glyph sprites
///
/// Allocation failures will result in glyphs not drawing.
pub trait SpriteAllocator {
    /// Returns true if sub-pixel rendering is available
    fn query_subpixel_rendering(&self) -> bool;

    /// Allocate a sprite using an 8-bit coverage mask
    fn alloc_mask(&mut self, size: (u32, u32)) -> Result<Allocation, AllocError>;

    /// Allocate a sprite using a 32-bit RGBA coverage mask
    ///
    /// This is an optional feature, only used if
    /// [`Self::query_subpixel_rendering`] returns `true`.
    fn alloc_rgba_mask(&mut self, size: (u32, u32)) -> Result<Allocation, AllocError>;

    /// Allocate a sprite using a 32-bit RGBA bitmap
    ///
    /// This is only used for colored glyphs.
    fn alloc_rgba(&mut self, size: (u32, u32)) -> Result<Allocation, AllocError>;
}

/// Render queue
pub trait RenderQueue {
    /// Push a sprite to the render queue
    fn push_sprite(
        &mut self,
        pass: PassId,
        glyph_pos: Vec2,
        rect: Quad,
        col: Rgba,
        sprite: &Sprite,
    );
}

kas::impl_scope! {
    /// Raster configuration
    #[derive(Debug, PartialEq)]
    #[impl_default]
    pub struct Config {
        subpixel_threshold: f32 = 18.0,
        subpixel_x_steps: u8 = 3,
        subpixel_format: Format = Format::Alpha,
    }
}

enum Rasterer {
    #[cfg(feature = "ab_glyph")]
    AbGlyph,
    Swash,
}

impl Default for Rasterer {
    #[allow(clippy::needless_return, unreachable_code)]
    fn default() -> Self {
        return Rasterer::Swash;
    }
}

/// A Sprite descriptor
///
/// This descriptor includes all important properties of a rastered glyph in a
/// small, easily hashable value. It is thus ideal for caching rastered glyphs
/// in a `HashMap`.
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
pub struct SpriteDescriptor(u64);

impl std::fmt::Debug for SpriteDescriptor {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let dpem_steps = ((self.0 & 0x00FF_FFFF_0000_0000) >> 32) as u32;
        let x_steps = ((self.0 & 0x0F00_0000_0000_0000) >> 56) as u8;
        let y_steps = ((self.0 & 0xF000_0000_0000_0000) >> 60) as u8;
        f.debug_struct("SpriteDescriptor")
            .field("face", &self.face())
            .field("glyph", &self.glyph())
            .field("dpem_steps", &dpem_steps)
            .field("offset_steps", &(x_steps, y_steps))
            .finish()
    }
}

impl SpriteDescriptor {
    /// Choose a sub-pixel precision multiplier based on scale (pixels per Em)
    ///
    /// Must return an integer between 1 and 16.
    fn sub_pixel_x_steps(config: &Config, dpem: f32) -> u8 {
        if dpem < config.subpixel_threshold {
            config.subpixel_x_steps
        } else {
            1
        }
    }

    /// Construct
    pub fn new(config: &Config, face: FaceId, glyph: Glyph, dpem: f32) -> Self {
        let face: u16 = face.get().cast();
        let glyph_id: u16 = glyph.id.0;

        let steps = Self::sub_pixel_x_steps(config, dpem);
        let mult = f32::conv(steps);
        let dpem = u32::conv_trunc(dpem * SCALE_STEPS + 0.5);
        let x_off = u8::conv_trunc(glyph.position.0.fract() * mult) % steps;
        // y-offset serves little purpose since we don't support vertical text
        // and kas-text already rounds the v-caret to the nearest pixel.
        let y_off = 0;

        assert!(dpem & 0xFF00_0000 == 0 && x_off & 0xF0 == 0 && y_off & 0xF0 == 0);
        let packed = face as u64
            | ((glyph_id as u64) << 16)
            | ((dpem as u64) << 32)
            | ((x_off as u64) << 56)
            | ((y_off as u64) << 60);
        SpriteDescriptor(packed)
    }

    /// Get `FaceId` descriptor
    pub fn face(self) -> FaceId {
        FaceId::from((self.0 & 0x0000_0000_0000_FFFF) as u32)
    }

    /// Get `GlyphId` descriptor
    pub fn glyph(self) -> GlyphId {
        GlyphId(((self.0 & 0x0000_0000_FFFF_0000) >> 16).cast())
    }

    /// Get scale (pixels per Em)
    pub fn dpem(self) -> f32 {
        let dpem_steps = ((self.0 & 0x00FF_FFFF_0000_0000) >> 32) as u32;
        f32::conv(dpem_steps) / SCALE_STEPS
    }

    /// Get fractional position
    ///
    /// This may optionally be used (depending on [`Config`]) to improve letter
    /// spacing at small font sizes. Returns the `(x, y)` offsets in the range
    /// `0.0 ≤ x < 1.0` (and the same for `y`).
    pub fn fractional_position(self, config: &Config) -> (f32, f32) {
        let mult = 1.0 / f32::conv(Self::sub_pixel_x_steps(config, self.dpem()));
        let x_steps = ((self.0 & 0x0F00_0000_0000_0000) >> 56) as u8;
        let x = f32::conv(x_steps) * mult;
        let y = 0.0;
        (x, y)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SpriteType {
    /// 8-bit coverage mask
    Mask,
    /// 32-bit RGBA coverage mask
    RgbaMask,
    /// 32-bit RGBA bitmap
    Bitmap,
}

/// A Sprite
///
/// A "sprite" is a glyph rendered to a texture with fixed properties. This
/// struct contains everything needed to draw from the sprite.
#[derive(Clone, Debug, Default)]
pub struct Sprite {
    pub atlas: u32,
    pub ty: Option<SpriteType>,
    pub size: Vec2,
    pub offset: Vec2,
    pub tex_quad: Quad,
}

/// A sprite pending upload to the GPU texture
#[derive(Debug)]
pub struct UnpreparedSprite {
    pub atlas: u32,
    pub ty: SpriteType,
    pub origin: (u32, u32),
    pub size: (u32, u32),
    pub data: Vec<u8>,
}

/// A pipeline for rendering text
#[derive(Default)]
pub struct State {
    rasterer: Rasterer,
    #[allow(unused)]
    sb_align: bool,
    #[allow(unused)]
    hint: bool,
    config: Config,
    glyphs: HashMap<SpriteDescriptor, Sprite>,
    prepare: Vec<UnpreparedSprite>,
    scale_cx: swash::scale::ScaleContext,
}

impl State {
    /// Assign raster configuration
    pub fn set_raster_config(&mut self, config: &RasterConfig) {
        match config.mode {
            #[cfg(feature = "ab_glyph")]
            0 | 1 => self.rasterer = Rasterer::AbGlyph,
            3 | 4 => self.rasterer = Rasterer::Swash,
            x => log::warn!("raster mode {x} unavailable; falling back to default"),
        };

        self.sb_align = config.mode == 1;
        self.hint = config.mode == 4;

        self.config = Config {
            subpixel_threshold: config.subpixel_threshold.cast(),
            subpixel_x_steps: config.subpixel_x_steps.clamp(1, 16),
            subpixel_format: match config.subpixel_mode {
                SubpixelMode::None => Format::Alpha,
                SubpixelMode::HorizontalRGB => Format::Subpixel,
            },
        };

        // NOTE: possibly this should force re-drawing of all glyphs, but for
        // now that is out of scope
    }
    /*
    /// Access configuration data
    pub fn config(&self) -> &Config {
        &self.config
    }*/

    /// Returns access to the queue of unprepared sprites
    #[inline]
    pub fn unprepared_sprites(&mut self) -> &mut Vec<UnpreparedSprite> {
        &mut self.prepare
    }

    #[cfg(feature = "ab_glyph")]
    fn raster_ab_glyph(
        &mut self,
        allocator: &mut dyn SpriteAllocator,
        face_id: FaceId,
        dpem: f32,
        glyphs: &mut dyn Iterator<Item = Glyph>,
    ) {
        use ab_glyph::Font;

        let face_store = fonts::library().get_face_store(face_id);

        for glyph in glyphs {
            let desc = SpriteDescriptor::new(&self.config, face_id, glyph, dpem);
            if self.glyphs.contains_key(&desc) {
                continue;
            }

            let (mut x, y) = desc.fractional_position(&self.config);
            if self.sb_align && desc.dpem(&self.config) >= self.config.subpixel_threshold {
                let sf = face_store.face_ref().scale_by_dpem(dpem);
                x -= sf.h_side_bearing(glyph.id);
            }

            let font = face_store.ab_glyph();
            let scale = dpem * font.height_unscaled() / font.units_per_em().unwrap();
            let glyph = ab_glyph::Glyph {
                id: ab_glyph::GlyphId(glyph.id.0),
                scale: scale.into(),
                position: ab_glyph::point(x, y),
            };
            let Some(outline) = font.outline_glyph(glyph) else {
                log::warn!("raster_glyphs failed: unable to outline glyph");
                self.glyphs.insert(desc, Sprite::default());
                continue;
            };

            let bounds = outline.px_bounds();
            let offset: (i32, i32) = (bounds.min.x.cast_trunc(), bounds.min.y.cast_trunc());
            let size = bounds.max - bounds.min;
            let size = (u32::conv_trunc(size.x), u32::conv_trunc(size.y));
            if size.0 == 0 || size.1 == 0 {
                // Ignore this common error
                self.glyphs.insert(desc, Sprite::default());
                continue;
            }

            let mut data = vec![0; usize::conv(size.0 * size.1)];
            outline.draw(|x, y, c| {
                // Convert to u8 with saturating conversion, rounding down:
                data[usize::conv((y * size.0) + x)] = (c * 256.0) as u8;
            });

            let Ok(alloc) = allocator.alloc_a(size) else {
                log::warn!("raster_glyphs failed: unable to allocate");
                self.glyphs.insert(desc, Sprite::default());
                continue;
            };

            self.prepare.push(UnpreparedSprite {
                atlas: alloc.atlas,
                color: false,
                origin: alloc.origin,
                size,
                data,
            });

            self.glyphs.insert(desc, Sprite {
                atlas: alloc.atlas,
                color: false,
                valid: true,
                size: Vec2(size.0.cast(), size.1.cast()),
                offset: Vec2(offset.0.cast(), offset.1.cast()),
                tex_quad: alloc.tex_quad,
            });
        }
    }

    // NOTE: using dyn Iterator over impl Iterator is slightly slower but saves 2-4kB
    fn raster_swash(
        &mut self,
        allocator: &mut dyn SpriteAllocator,
        face_id: FaceId,
        dpem: f32,
        glyphs: &mut dyn Iterator<Item = Glyph>,
    ) {
        use swash::scale::{Render, Source, StrikeWith, image::Content};
        use swash::zeno::{Angle, Transform};

        let face = fonts::library().get_face_store(face_id);
        let font = face.swash();
        let synthesis = face.synthesis();

        let mut scaler = self
            .scale_cx
            .builder(font)
            .size(dpem)
            .hint(self.hint)
            .variations(
                synthesis
                    .variation_settings()
                    .iter()
                    .map(|(tag, value)| (swash::tag_from_bytes(&tag.to_be_bytes()), *value)),
            )
            .build();

        let sources = &[
            // TODO: Support coloured rendering? These can replace Source::Bitmap
            Source::ColorOutline(0),
            Source::ColorBitmap(StrikeWith::BestFit),
            Source::Bitmap(StrikeWith::BestFit),
            Source::Outline,
        ];

        let mut format = self.config.subpixel_format;
        if format != Format::Alpha && allocator.query_subpixel_rendering() == false {
            format = Format::Alpha;
        }

        // Faux italic skew:
        let transform = synthesis
            .skew()
            .map(|angle| Transform::skew(Angle::from_degrees(angle), Angle::ZERO));
        // Faux bold:
        let embolden = if synthesis.embolden() { dpem * 0.02 } else { 0.0 };

        for glyph in glyphs {
            let desc = SpriteDescriptor::new(&self.config, face_id, glyph, dpem);
            if self.glyphs.contains_key(&desc) {
                continue;
            }

            let Some(image) = Render::new(sources)
                .format(format)
                .offset(desc.fractional_position(&self.config).into())
                .transform(transform)
                .embolden(embolden)
                .render(&mut scaler, desc.glyph().0)
            else {
                log::warn!("raster_glyphs failed: unable to construct renderer");
                self.glyphs.insert(desc, Sprite::default());
                continue;
            };

            let offset = (image.placement.left, -image.placement.top);
            let size = (image.placement.width, image.placement.height);
            if size.0 == 0 || size.1 == 0 {
                // Ignore this common error
                self.glyphs.insert(desc, Sprite::default());
                continue;
            }

            let sprite = match image.content {
                Content::Mask => {
                    let Ok(alloc) = allocator.alloc_mask(size) else {
                        log::warn!("raster_glyphs failed: unable to allocate");
                        self.glyphs.insert(desc, Sprite::default());
                        continue;
                    };

                    self.prepare.push(UnpreparedSprite {
                        atlas: alloc.atlas,
                        ty: SpriteType::Mask,
                        origin: alloc.origin,
                        size,
                        data: image.data,
                    });

                    Sprite {
                        atlas: alloc.atlas,
                        ty: Some(SpriteType::Mask),
                        size: Vec2(size.0.cast(), size.1.cast()),
                        offset: Vec2(offset.0.cast(), offset.1.cast()),
                        tex_quad: alloc.tex_quad,
                    }
                }
                Content::SubpixelMask => {
                    let Ok(alloc) = allocator.alloc_rgba_mask(size) else {
                        log::warn!("raster_glyphs failed: unable to allocate");
                        self.glyphs.insert(desc, Sprite::default());
                        continue;
                    };

                    self.prepare.push(UnpreparedSprite {
                        atlas: alloc.atlas,
                        ty: SpriteType::RgbaMask,
                        origin: alloc.origin,
                        size,
                        data: image.data,
                    });

                    Sprite {
                        atlas: alloc.atlas,
                        ty: Some(SpriteType::RgbaMask),
                        size: Vec2(size.0.cast(), size.1.cast()),
                        offset: Vec2(offset.0.cast(), offset.1.cast()),
                        tex_quad: alloc.tex_quad,
                    }
                }
                Content::Color => {
                    let Ok(alloc) = allocator.alloc_rgba(size) else {
                        log::warn!("raster_glyphs failed: unable to allocate");
                        self.glyphs.insert(desc, Sprite::default());
                        continue;
                    };

                    self.prepare.push(UnpreparedSprite {
                        atlas: alloc.atlas,
                        ty: SpriteType::Bitmap,
                        origin: alloc.origin,
                        size,
                        data: image.data,
                    });

                    Sprite {
                        atlas: alloc.atlas,
                        ty: Some(SpriteType::Bitmap),
                        size: Vec2(size.0.cast(), size.1.cast()),
                        offset: Vec2(offset.0.cast(), offset.1.cast()),
                        tex_quad: alloc.tex_quad,
                    }
                }
            };

            self.glyphs.insert(desc, sprite);
        }
    }

    /// Raster a sequence of glyphs
    #[inline]
    pub fn raster_glyphs(
        &mut self,
        allocator: &mut dyn SpriteAllocator,
        face_id: FaceId,
        dpem: f32,
        mut glyphs: impl Iterator<Item = Glyph>,
    ) {
        match self.rasterer {
            #[cfg(feature = "ab_glyph")]
            Rasterer::AbGlyph => self.raster_ab_glyph(allocator, face_id, dpem, &mut glyphs),
            Rasterer::Swash => self.raster_swash(allocator, face_id, dpem, &mut glyphs),
        }
    }

    /// Draw text as a sequence of sprites
    pub fn text(
        &mut self,
        allocator: &mut dyn SpriteAllocator,
        queue: &mut dyn RenderQueue,
        pass: PassId,
        pos: Vec2,
        bb: Quad,
        text: &TextDisplay,
        col: Rgba,
    ) {
        for run in text.runs(pos.into(), &[]) {
            let face = run.face_id();
            let dpem = run.dpem();
            for glyph in run.glyphs() {
                let desc = SpriteDescriptor::new(&self.config, face, glyph, dpem);
                let sprite = match self.glyphs.get(&desc) {
                    Some(sprite) => sprite,
                    None => {
                        self.raster_glyphs(allocator, face, dpem, run.glyphs());
                        match self.glyphs.get(&desc) {
                            Some(sprite) => sprite,
                            None => continue,
                        }
                    }
                };
                queue.push_sprite(pass, Vec2::from(glyph.position), bb, col, sprite);
            }
        }
    }

    /// Draw text with effects as a sequence of sprites
    #[allow(clippy::too_many_arguments)]
    pub fn text_effects(
        &mut self,
        allocator: &mut dyn SpriteAllocator,
        queue: &mut dyn RenderQueue,
        pass: PassId,
        pos: Vec2,
        bb: Quad,
        text: &TextDisplay,
        colors: &[Rgba],
        effects: &[Effect],
        mut draw_quad: impl FnMut(Quad, Rgba),
    ) {
        // Optimisation: use cheaper TextDisplay::runs method
        if effects.len() <= 1
            && effects
                .first()
                .map(|e| e.flags == Default::default())
                .unwrap_or(true)
        {
            let col = colors.first().cloned().unwrap_or(Rgba::BLACK);
            self.text(allocator, queue, pass, pos, bb, text, col);
            return;
        }

        for run in text.runs(pos.into(), effects) {
            let face = run.face_id();
            let dpem = run.dpem();
            let for_glyph = |glyph: Glyph, e: u16| {
                let desc = SpriteDescriptor::new(&self.config, face, glyph, dpem);
                let sprite = match self.glyphs.get(&desc) {
                    Some(sprite) => sprite,
                    None => {
                        self.raster_glyphs(allocator, face, dpem, run.glyphs());
                        match self.glyphs.get(&desc) {
                            Some(sprite) => sprite,
                            None => return,
                        }
                    }
                };
                let col = colors.get(usize::conv(e)).cloned().unwrap_or(Rgba::BLACK);
                queue.push_sprite(pass, glyph.position.into(), bb, col, sprite);
            };

            let for_rect = |x1, x2, y: f32, h: f32, e: u16| {
                let y = y.ceil();
                let y2 = y + h.ceil();
                if let Some(quad) = Quad::from_coords(Vec2(x1, y), Vec2(x2, y2)).intersection(&bb) {
                    let col = colors.get(usize::conv(e)).cloned().unwrap_or(Rgba::BLACK);
                    draw_quad(quad, col);
                }
            };

            run.glyphs_with_effects(for_glyph, for_rect);
        }
    }
}