klyff 0.1.3

Text rendering library for games with MSDF support
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
use super::{DecodedGlyph, Rect, Text, TextStyle};

pub type GlyphStyleMap = Box<dyn Fn(DecodedGlyph, TextStyle) -> TextStyle>;

/// A styled text. Construct one with [`StyledTextBuilder`]
///
/// Each text object may have different styling per span, each span is assigned a metadata
/// index which is propagated through `cosmic_text` attrs onto every [`DecodedGlyph::metadata`]
/// produced from this text. Use [`StyledText::style_at`] to resolve a metadata value back to its
/// [`TextStyle`].
///
/// Note that styles not enabled in [`crate::Features`] are ignored at render time.
pub struct StyledText {
    pub(crate) buf: cosmic_text::Buffer,
    pub(crate) first_style: TextStyle,
    pub(crate) other_style: Vec<TextStyle>,
    pub region: Rect,
    pub scale: f32,
    pub custom_padding: Option<(usize, usize)>,
    /// Screen-space rectangle used to normalise gradient positions. Vertex positions are mapped
    /// so that vertex at the the rect's top-left corner is `(0, 0)` and its bottom-right corner is
    /// `(1, 1)`.
    ///
    /// When `None`, [`StyledText::region`] is used instead. Set this explicitly when multiple
    /// `StyledText` objects should share a single gradient that spans all of them.
    pub gradient_region: Option<Rect>,
}

impl StyledText {
    /// Borrow this styled text as a low-level [`Text`] for [`crate::MeshEncoder::encode`].
    ///
    /// `id` is supplied by the caller (e.g. [`crate::TextRenderer::prepare`] passes the
    /// enumeration index) and surfaces on every produced [`DecodedGlyph::text_id`].
    pub fn as_text(&self, id: u64) -> Text<'_> {
        Text {
            id,
            text_buffer: &self.buf,
            region: self.region,
            scale: self.scale,
            custom_padding: self.custom_padding,
        }
    }

    /// Resolve a `metadata` value back to its [`TextStyle`].
    pub fn style_at(&self, metadata: usize) -> &TextStyle {
        if metadata == 0 {
            &self.first_style
        } else {
            self.other_style
                .get(metadata - 1)
                .unwrap_or(&self.first_style)
        }
    }

    /// Iterate over all styles in this text.
    pub fn styles(&self) -> impl Iterator<Item = &TextStyle> {
        std::iter::once(&self.first_style).chain(self.other_style.iter())
    }

    /// Returns the underlying `cosmic_text::Buffer`.
    pub fn buffer(&self) -> &cosmic_text::Buffer {
        &self.buf
    }
}

// TODO: This allocates two vecs. Avoidable?
/// Builder for [`StyledText`].
///
/// Spans are pushed via [`StyledTextBuilder::push_text`] (always allocates a new style slot).
pub struct StyledTextBuilder {
    inner: StyledText,
    spans: Vec<(String, cosmic_text::AttrsOwned)>,
    /// All styles indexed by metadata. Split into `first_style` + `other_style` on `finish`.
    styles: Vec<TextStyle>,
    shaping: cosmic_text::Shaping,
    align: Option<cosmic_text::Align>,
}

impl StyledTextBuilder {
    /// Create a new builder for styled text within `region`.
    ///
    /// `metrics` sets the default font size and line height for the text buffer.
    pub fn new(
        region: Rect,
        font_system: &mut cosmic_text::FontSystem,
        metrics: cosmic_text::Metrics,
    ) -> Self {
        let mut buf = cosmic_text::Buffer::new(font_system, metrics);
        buf.set_size(font_system, Some(region.width()), Some(region.height()));
        Self {
            inner: StyledText {
                buf,
                first_style: TextStyle::default(),
                other_style: Vec::new(),
                region,
                scale: 1.0,
                custom_padding: None,
                gradient_region: None,
            },
            spans: Vec::new(),
            styles: Vec::new(),
            shaping: cosmic_text::Shaping::Advanced,
            align: None,
        }
    }

    /// Set the scale factor applied to all glyphs.
    pub fn set_scale(&mut self, scale: f32) {
        self.inner.scale = scale;
    }

    /// Set the region used for gradient UV normalization.
    pub fn set_gradient_region(&mut self, region: Option<Rect>) {
        self.inner.gradient_region = region;
    }

    /// Set the text alignment.
    pub fn set_align(&mut self, align: Option<cosmic_text::Align>) {
        self.align = align;
    }

    /// Set the text shaping mode.
    pub fn set_shaping(&mut self, shaping: cosmic_text::Shaping) {
        self.shaping = shaping;
    }

    /// Append `content` as a new span with its own style slot.
    ///
    /// The span's `cosmic_text::Attrs::metadata` is set to the new style's index, so glyphs from
    /// this span will surface that metadata value on [`DecodedGlyph::metadata`].
    pub fn push_text(
        &mut self,
        content: &str,
        attrs: &cosmic_text::Attrs<'_>,
        style: TextStyle,
    ) -> usize {
        let metadata = self.styles.len();
        self.styles.push(style);
        let mut owned = cosmic_text::AttrsOwned::new(attrs);
        owned.metadata = metadata;
        self.spans.push((content.to_owned(), owned));
        metadata
    }

    /// Append a custom glyph placeholder.
    ///
    /// Inserts [`crate::CUSTOM_GLYPH_CHAR`] shaped with the bundled PUA font (load it once with
    /// [`crate::setup_custom_glyph_font`]). The glyph is empty, so klyff never draws it; instead it
    /// reserves a `width` x `height` box in the layout (`width` becomes the glyph's advance via its
    /// font size, `height` its line height) and is surfaced afterwards via
    /// [`crate::MeshEncoder::custom_glyphs`] / [`crate::TextRenderer::custom_glyphs`], keyed by
    /// `id`.
    ///
    /// `width` and `height` are in the same logical units as the buffer metrics (i.e. before
    /// [`StyledText::scale`] is applied).
    pub fn push_custom_glyph(&mut self, id: u64, width: f32, height: f32) {
        let attrs = cosmic_text::Attrs::new()
            .family(cosmic_text::Family::Name(super::CUSTOM_GLYPH_FAMILY))
            .metadata(id as usize)
            .metrics(cosmic_text::Metrics::new(width, height));
        // Custom glyphs are detected by font id and never reach style routing, so this span does
        // not allocate a style slot; its `metadata` carries the custom-glyph `id` instead.
        self.spans.push((
            super::CUSTOM_GLYPH_CHAR.to_string(),
            cosmic_text::AttrsOwned::new(&attrs),
        ));
    }

    /// Finalise the buffer (rich-text layout + shape) and return the [`StyledText`].
    pub fn finish(
        mut self,
        font_system: &mut cosmic_text::FontSystem,
        default_attrs: &cosmic_text::Attrs<'_>,
    ) -> StyledText {
        // Split styles into (first_style, other_style).
        if let Some(first) = self.styles.first().copied() {
            self.inner.first_style = first;
            self.inner.other_style = self.styles[1..].to_vec();
        }

        let owned_default = cosmic_text::AttrsOwned::new(default_attrs);
        let spans = self.spans.iter().map(|(s, a)| (s.as_str(), a.as_attrs()));
        self.inner.buf.set_rich_text(
            font_system,
            spans,
            &owned_default.as_attrs(),
            self.shaping,
            self.align,
        );
        self.inner.buf.shape_until_scroll(font_system, false);

        // Find the minimum font size across all laid-out glyphs. Effects are specified in screen
        // pixels, so smaller fonts need proportionally more atlas padding to cover the same
        // screen-space extent.
        let min_font_size = self
            .inner
            .buf
            .layout_runs()
            .flat_map(|run| run.glyphs.iter().map(|g| g.font_size))
            .reduce(f32::min)
            .unwrap_or(crate::atlas::DEFAULT_PPEM);

        // Atlas padding must cover the largest outer extent across all styles, scaled by the
        // ratio of atlas ppem to minimum font size.
        self.inner.custom_padding = self
            .styles
            .iter()
            .filter_map(|s| style_padding(s, min_font_size))
            .max_by_key(|(x, _)| *x);

        self.inner
    }
}

/// Compute the atlas padding (in texels) required to render all outer effects in `style`.
///
/// Outer effects (stroke_out, glow_out, shadow) extend beyond the glyph boundary, so the
/// MSDF atlas needs enough border to encode those distances. The `min_font_size` is the
/// smallest font size in the text; when it is smaller than the atlas ppem, we need
/// proportionally more padding texels to cover the same screen-pixel extent.
fn style_padding(style: &TextStyle, min_font_size: f32) -> Option<(usize, usize)> {
    let outer_extent_px = f32::max(
        style.stroke_out.width + style.glow_out.width,
        style.shadow.additional_width,
    );
    // Scale padding by ppem / min_font_size so that smaller fonts get more padding.
    // At render time, padding is converted back to screen pixels via:
    //   expand = padding / ppem * font_size
    // For this to equal outer_extent_px, we need:
    //   padding = outer_extent_px * ppem / font_size
    let ppem = crate::atlas::DEFAULT_PPEM;
    let needed = (outer_extent_px * ppem / min_font_size).ceil() as usize;
    (needed > crate::atlas::DEFAULT_PADDING).then_some((needed, needed))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Outline, Rect, TextStyle};
    use cosmic_text::{Attrs, FontSystem, Metrics};

    fn font_system() -> FontSystem {
        FontSystem::new()
    }

    fn region() -> Rect {
        Rect::from_xywh(0.0, 0.0, 800.0, 600.0)
    }

    fn metrics() -> Metrics {
        Metrics::new(16.0, 20.0)
    }

    fn style_with_stroke(width: f32) -> TextStyle {
        TextStyle {
            stroke_out: Outline {
                width,
                ..Default::default()
            },
            ..Default::default()
        }
    }

    #[test]
    fn new_default_val() {
        let mut fs = font_system();
        let r = region();
        let text = StyledTextBuilder::new(r, &mut fs, metrics()).finish(&mut fs, &Attrs::new());
        assert_eq!(text.region, r);
        assert_eq!(text.scale, 1.0);
        assert_eq!(text.gradient_region, None);
    }

    #[test]
    fn set_scale_reflected_on_finish() {
        let mut fs = font_system();
        let mut builder = StyledTextBuilder::new(region(), &mut fs, metrics());
        builder.set_scale(2.5);
        let text = builder.finish(&mut fs, &Attrs::new());
        assert_eq!(text.scale, 2.5);
    }

    #[test]
    fn set_gradient_region_some() {
        let mut fs = font_system();
        let grad = Rect::from_xywh(10.0, 10.0, 400.0, 300.0);
        let mut builder = StyledTextBuilder::new(region(), &mut fs, metrics());
        builder.set_gradient_region(Some(grad));
        let text = builder.finish(&mut fs, &Attrs::new());
        assert_eq!(text.gradient_region, Some(grad));
    }

    #[test]
    fn set_gradient_region_none_clears() {
        let mut fs = font_system();
        let mut builder = StyledTextBuilder::new(region(), &mut fs, metrics());
        builder.set_gradient_region(Some(region()));
        builder.set_gradient_region(None);
        let text = builder.finish(&mut fs, &Attrs::new());
        assert_eq!(text.gradient_region, None);
    }

    #[test]
    fn push_text_first_index_is_zero() {
        let mut fs = font_system();
        let mut builder = StyledTextBuilder::new(region(), &mut fs, metrics());
        let idx = builder.push_text("hello", &Attrs::new(), TextStyle::default());
        assert_eq!(idx, 0);
    }

    #[test]
    fn push_text_indices_increment() {
        let mut fs = font_system();
        let mut builder = StyledTextBuilder::new(region(), &mut fs, metrics());
        let a = builder.push_text("a", &Attrs::new(), TextStyle::default());
        let b = builder.push_text("b", &Attrs::new(), TextStyle::default());
        let c = builder.push_text("c", &Attrs::new(), TextStyle::default());
        assert_eq!((a, b, c), (0, 1, 2));
    }

    #[test]
    fn push_custom_glyph_does_not_consume_style_slot() {
        let mut fs = font_system();
        let mut builder = StyledTextBuilder::new(region(), &mut fs, metrics());
        let before = builder.push_text("a", &Attrs::new(), TextStyle::default());
        builder.push_custom_glyph(42, 16.0, 16.0);
        let after = builder.push_text("b", &Attrs::new(), TextStyle::default());
        assert_eq!((before, after), (0, 1));
    }

    #[test]
    fn finish_no_spans_has_default_first_style() {
        let mut fs = font_system();
        let text =
            StyledTextBuilder::new(region(), &mut fs, metrics()).finish(&mut fs, &Attrs::new());
        assert_eq!(*text.style_at(0), TextStyle::default());
    }

    #[test]
    fn finish_no_spans_styles_yields_one_item() {
        let mut fs = font_system();
        let text =
            StyledTextBuilder::new(region(), &mut fs, metrics()).finish(&mut fs, &Attrs::new());
        assert_eq!(text.styles().count(), 1);
    }

    #[test]
    fn style_at_single_span() {
        let mut fs = font_system();
        let mut builder = StyledTextBuilder::new(region(), &mut fs, metrics());
        builder.push_text("hello", &Attrs::new(), style_with_stroke(3.0));
        let text = builder.finish(&mut fs, &Attrs::new());
        assert_eq!(text.style_at(0).stroke_out.width, 3.0);
    }

    #[test]
    fn style_at_multiple_spans() {
        let mut fs = font_system();
        let mut builder = StyledTextBuilder::new(region(), &mut fs, metrics());
        builder.push_text("a", &Attrs::new(), style_with_stroke(1.0));
        builder.push_text("b", &Attrs::new(), style_with_stroke(2.0));
        builder.push_text("c", &Attrs::new(), style_with_stroke(3.0));
        let text = builder.finish(&mut fs, &Attrs::new());
        assert_eq!(text.style_at(0).stroke_out.width, 1.0);
        assert_eq!(text.style_at(1).stroke_out.width, 2.0);
        assert_eq!(text.style_at(2).stroke_out.width, 3.0);
    }

    #[test]
    fn style_at_out_of_range_falls_back_to_first() {
        let mut fs = font_system();
        let mut builder = StyledTextBuilder::new(region(), &mut fs, metrics());
        builder.push_text("a", &Attrs::new(), style_with_stroke(1.0));
        builder.push_text("b", &Attrs::new(), style_with_stroke(2.0));
        let text = builder.finish(&mut fs, &Attrs::new());
        assert_eq!(text.style_at(99).stroke_out.width, 1.0);
    }

    #[test]
    fn styles_yields_all_in_push_order() {
        let mut fs = font_system();
        let mut builder = StyledTextBuilder::new(region(), &mut fs, metrics());
        builder.push_text("a", &Attrs::new(), style_with_stroke(1.0));
        builder.push_text("b", &Attrs::new(), style_with_stroke(2.0));
        builder.push_text("c", &Attrs::new(), style_with_stroke(3.0));
        let text = builder.finish(&mut fs, &Attrs::new());
        let widths: Vec<f32> = text.styles().map(|s| s.stroke_out.width).collect();
        assert_eq!(widths, [1.0, 2.0, 3.0]);
    }

    #[test]
    fn styles_count_matches_span_count() {
        let mut fs = font_system();
        let mut builder = StyledTextBuilder::new(region(), &mut fs, metrics());
        builder.push_text("a", &Attrs::new(), TextStyle::default());
        builder.push_text("b", &Attrs::new(), TextStyle::default());
        let text = builder.finish(&mut fs, &Attrs::new());
        assert_eq!(text.styles().count(), 2);
    }

    #[test]
    fn buffer_accessible() {
        let mut fs = font_system();
        let text =
            StyledTextBuilder::new(region(), &mut fs, metrics()).finish(&mut fs, &Attrs::new());
        let _ = text.buffer();
    }

    #[test]
    fn as_text_id_propagated() {
        let mut fs = font_system();
        let text =
            StyledTextBuilder::new(region(), &mut fs, metrics()).finish(&mut fs, &Attrs::new());
        assert_eq!(text.as_text(99).id, 99);
    }

    #[test]
    fn as_text_region_propagated() {
        let mut fs = font_system();
        let r = region();
        let text = StyledTextBuilder::new(r, &mut fs, metrics()).finish(&mut fs, &Attrs::new());
        assert_eq!(text.as_text(0).region, r);
    }

    #[test]
    fn as_text_scale_propagated() {
        let mut fs = font_system();
        let mut builder = StyledTextBuilder::new(region(), &mut fs, metrics());
        builder.set_scale(3.0);
        let text = builder.finish(&mut fs, &Attrs::new());
        assert_eq!(text.as_text(0).scale, 3.0);
    }
}