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
use crate::{
    CustomGlyph, CustomGlyphFont, DecodedGlyph, EncoderContext, Features, GlyphMaterial,
    MaterialEncoder, MeshEncoder, MsdfTextPipeline, RasterizedTextPipeline, Rect,
    ScreenSizeUniform, StyledText, TextStyle, TextureAtlas,
};

/// A single MSDF sub-pass — the material encoder that feeds the shared pipeline.
struct MsdfPass {
    encoder: MaterialEncoder,
    material_builder: fn(&TextStyle, &DecodedGlyph, Option<Rect>) -> GlyphMaterial,
}

struct MsdfMultiPass {
    fill: MsdfPass,
    stroke_in: Option<MsdfPass>,
    glow_in: Option<MsdfPass>,
    stroke_out: Option<MsdfPass>,
    glow_out: Option<MsdfPass>,
    shadow: Option<MsdfPass>,
}

/// Passes for rendering MSDF path, either single pass or layered multi pass.
enum MsdfPasses {
    Single(MsdfPass),
    Multi(Box<MsdfMultiPass>),
}

/// Text renderer with MSDF.
///
/// Convenient wrapper for rendering [`StyledText`]. Allows drawing glyphs with outline, glow and
/// shadow.
///
/// For more control, or if you want to draw with custom shader, consider using the lower-level API
/// ([`MeshEncoder`], [`MaterialEncoder`], [`MsdfTextPipeline`], [`RasterizedTextPipeline`]).
pub struct TextRenderer {
    #[allow(dead_code)]
    enabled_features: Features,
    msdf_generator: klyff_msdf::MsdfGenerator,
    mesh_encoder: MeshEncoder,
    msdf_passes: Box<MsdfPasses>,
    msdf_pipeline: MsdfTextPipeline,
    rasterized_pipeline: RasterizedTextPipeline,
    screen_size_uniform: ScreenSizeUniform,
}

impl TextRenderer {
    pub fn new(device: &wgpu::Device, surface_format: wgpu::TextureFormat) -> Self {
        let rasterized_pipeline = RasterizedTextPipeline::new(device, surface_format);
        let msdf_pipeline = MsdfTextPipeline::new(device, surface_format);
        Self::with_custom_pipeline(device, msdf_pipeline, rasterized_pipeline)
    }

    pub fn with_custom_pipeline(
        device: &wgpu::Device,
        msdf_pipeline: MsdfTextPipeline,
        rasterized_pipeline: RasterizedTextPipeline,
    ) -> Self {
        let mesh_encoder = MeshEncoder::new(device);
        Self {
            enabled_features: Features::empty(),
            msdf_generator: klyff_msdf::MsdfGenerator::new(),
            mesh_encoder,
            msdf_passes: Box::new(MsdfPasses::Single(MsdfPass {
                encoder: MaterialEncoder::new(device),
                material_builder: material_fill,
            })),
            msdf_pipeline,
            rasterized_pipeline,
            screen_size_uniform: ScreenSizeUniform::new(device),
        }
    }

    /// Creates a renderer that draws styled text.
    ///
    /// Glyph styling only works for glyphs with single-color outlined glyphs. Bitmap glyphs,
    /// colored glyphs and such are rasterized and can not be drawn with styling.
    ///
    /// Each component of the styled text is drawn in one separate draw call, back to front
    /// (shadow -> outer glow -> outer stroke -> body -> inner stroke -> inner glow).
    pub fn with_styling(
        features: Features,
        device: &wgpu::Device,
        surface_format: wgpu::TextureFormat,
    ) -> Self {
        let mesh_encoder = MeshEncoder::new(device);
        let rasterized_pipeline = RasterizedTextPipeline::new(device, surface_format);
        let msdf_pipeline = MsdfTextPipeline::new(device, surface_format);

        let make_pass =
            |builder: fn(&TextStyle, &DecodedGlyph, Option<Rect>) -> GlyphMaterial| -> MsdfPass {
                MsdfPass {
                    encoder: MaterialEncoder::new(device),
                    material_builder: builder,
                }
            };

        let multi = MsdfPasses::Multi(Box::new(MsdfMultiPass {
            fill: make_pass(material_fill),
            stroke_in: features
                .contains(Features::STROKE_IN)
                .then(|| make_pass(material_stroke_in)),
            glow_in: features
                .contains(Features::GLOW_IN)
                .then(|| make_pass(material_glow_in)),
            stroke_out: features
                .contains(Features::STROKE_OUT)
                .then(|| make_pass(material_stroke_out)),
            glow_out: features
                .contains(Features::GLOW_OUT)
                .then(|| make_pass(material_glow_out)),
            shadow: features
                .contains(Features::SHADOW)
                .then(|| make_pass(material_shadow)),
        }));

        Self {
            enabled_features: features,
            msdf_generator: klyff_msdf::MsdfGenerator::new(),
            mesh_encoder,
            msdf_passes: Box::new(multi),
            msdf_pipeline,
            rasterized_pipeline,
            screen_size_uniform: ScreenSizeUniform::new(device),
        }
    }

    pub fn msdf_generator(&mut self) -> &mut klyff_msdf::MsdfGenerator {
        &mut self.msdf_generator
    }

    /// Prepare the renderer for rendering a set of text instances. Call once per frame.
    pub fn prepare(
        &mut self,
        ctx: EncoderContext<'_>,
        surface_size: (u32, u32),
        styled_texts: &[StyledText],
    ) {
        self.prepare_with_glyph_transform(ctx, surface_size, styled_texts, |_, _| {}, |_, _| {});
    }

    /// Same as [`Self::prepare`] but allows modifying on a per-glyph granurality.
    pub fn prepare_with_glyph_transform(
        &mut self,
        context: EncoderContext<'_>,
        surface_size: (u32, u32),
        styled_texts: &[StyledText],
        per_glyph_transform: impl FnMut(&DecodedGlyph, &mut [glam::Vec2; 4]),
        mut per_glyph_styling: impl FnMut(&DecodedGlyph, &mut TextStyle),
    ) {
        profiling::scope!("TextRenderer::prepare_with_glyph_transform");
        let ctx = EncoderContext {
            atlas: &mut *context.atlas,
            device: context.device,
            queue: context.queue,
            cmd_encoder: context.cmd_encoder,
            font_system: context.font_system,
        };
        self.mesh_encoder.encode(
            ctx,
            &mut self.msdf_generator,
            styled_texts
                .iter()
                .enumerate()
                .map(|(i, st)| st.as_text(i as u64)),
            per_glyph_transform,
        );
        self.screen_size_uniform
            .encode(context.queue, surface_size.0, surface_size.1);

        let fallback_style = TextStyle::default();
        let mesh_encoder = &self.mesh_encoder;

        Self::passes_mut(&mut self.msdf_passes, |pass| {
            profiling::scope!("TextRenderer::msdf_pass");
            let ctx = EncoderContext {
                atlas: &mut *context.atlas,
                device: context.device,
                queue: context.queue,
                cmd_encoder: context.cmd_encoder,
                font_system: context.font_system,
            };
            let builder = pass.material_builder;
            pass.encoder.encode(ctx, mesh_encoder, |glyph| {
                let st = styled_texts.get(glyph.text_id as usize);
                let mut style = st
                    .map(|st| *st.style_at(glyph.metadata))
                    .unwrap_or(fallback_style);
                per_glyph_styling(glyph, &mut style);
                let style = style.clamped_to_msdf_range(glyph.font_size_px);
                let gradient_region = st.and_then(|st| st.gradient_region);
                builder(&style, glyph, gradient_region)
            });
        });
    }

    /// Register the font whose glyphs should be treated as custom glyphs.
    ///
    /// Pass the handle returned by [`crate::setup_custom_glyph_font`]. After registering, custom
    /// glyphs inserted via [`crate::StyledTextBuilder::push_custom_glyph`] are detected during
    /// [`Self::prepare`] and surfaced by [`Self::custom_glyphs`]. Pass `None` to disable detection.
    pub fn set_custom_glyph_font(&mut self, font: Option<CustomGlyphFont>) {
        self.mesh_encoder.set_custom_glyph_font(font);
    }

    /// Custom glyphs detected during the last call to [`Self::prepare`].
    ///
    /// Empty unless a custom-glyph font was registered with [`Self::set_custom_glyph_font`]. klyff
    /// does not render these; use their positions to draw application-specific content.
    pub fn custom_glyphs(&self) -> &[CustomGlyph] {
        self.mesh_encoder.custom_glyphs()
    }

    /// Submit draw calls for the prepared frame into a [`wgpu::RenderPass<'a>].
    pub fn render<'a>(&'a self, pass: &mut wgpu::RenderPass<'a>, atlas: &'a TextureAtlas) {
        profiling::scope!("TextRenderer::render");
        self.rasterized_pipeline
            .render(pass, atlas, &self.screen_size_uniform, &self.mesh_encoder);

        match self.msdf_passes.as_ref() {
            MsdfPasses::Single(p) => {
                self.msdf_pipeline.render(
                    pass,
                    atlas,
                    &self.screen_size_uniform,
                    &self.mesh_encoder,
                    &p.encoder,
                );
            }
            MsdfPasses::Multi(multi_pass) => {
                let MsdfMultiPass {
                    fill,
                    stroke_in,
                    glow_in,
                    stroke_out,
                    glow_out,
                    shadow,
                } = multi_pass.as_ref();
                // Back-to-front draw order so alpha blending composites correctly.
                for p in [
                    shadow.as_ref(),
                    glow_out.as_ref(),
                    stroke_out.as_ref(),
                    Some(fill),
                    glow_in.as_ref(),
                    stroke_in.as_ref(),
                ]
                .into_iter()
                .flatten()
                {
                    self.msdf_pipeline.render(
                        pass,
                        atlas,
                        &self.screen_size_uniform,
                        &self.mesh_encoder,
                        &p.encoder,
                    );
                }
            }
        }
    }

    fn passes_mut(p: &mut MsdfPasses, mut f: impl FnMut(&mut MsdfPass)) {
        match p {
            MsdfPasses::Single(pass) => f(pass),
            MsdfPasses::Multi(multi_pass) => {
                let MsdfMultiPass {
                    fill,
                    stroke_in,
                    glow_in,
                    stroke_out,
                    glow_out,
                    shadow,
                } = multi_pass.as_mut();
                f(fill);
                if let Some(p) = stroke_in {
                    f(p);
                }
                if let Some(p) = glow_in {
                    f(p);
                }
                if let Some(p) = stroke_out {
                    f(p);
                }
                if let Some(p) = glow_out {
                    f(p);
                }
                if let Some(p) = shadow {
                    f(p);
                }
            }
        }
    }
}

// Width of the AA transition at a hard edge, in screen pixels.
const AA: f32 = 1.0;

// Large distance that covers the entire glyph interior.
const LARGE_DIST: f32 = 10000.0;

fn material_fill(
    style: &TextStyle,
    _glyph: &DecodedGlyph,
    gradient_region: Option<Rect>,
) -> GlyphMaterial {
    GlyphMaterial {
        render_dist_range: (-AA, LARGE_DIST),
        max_alpha_dist_range: (0.0, LARGE_DIST),
        color: style.color,
        offset: glam::Vec2::ZERO,
        gradient_region,
        roundness: 0.0,
    }
}

fn aa_max_alpha_range(from: f32, to: f32, aa: f32) -> (f32, f32) {
    if to - from > aa * 2.0 {
        (from + aa, to - aa)
    } else {
        (from + (to - from) * 0.25, from + (to - from) * 0.75)
    }
}

fn material_stroke_in(
    style: &TextStyle,
    _glyph: &DecodedGlyph,
    gradient_region: Option<Rect>,
) -> GlyphMaterial {
    let w = style.stroke_in.width;
    GlyphMaterial {
        render_dist_range: (-AA, w - AA),
        max_alpha_dist_range: aa_max_alpha_range(-AA, w - AA, AA),
        color: style.stroke_in.color,
        offset: glam::Vec2::ZERO,
        gradient_region,
        roundness: style.stroke_in.roundness,
    }
}

fn material_stroke_out(
    style: &TextStyle,
    _glyph: &DecodedGlyph,
    gradient_region: Option<Rect>,
) -> GlyphMaterial {
    let w = style.stroke_out.width;
    GlyphMaterial {
        render_dist_range: (-w, AA),
        max_alpha_dist_range: aa_max_alpha_range(-w, AA, AA),
        color: style.stroke_out.color,
        offset: glam::Vec2::ZERO,
        gradient_region,
        roundness: style.stroke_out.roundness,
    }
}

fn material_glow_in(
    style: &TextStyle,
    _glyph: &DecodedGlyph,
    gradient_region: Option<Rect>,
) -> GlyphMaterial {
    let s = style.glow_in.width;
    let p = style.glow_in.spread;
    // Start the glow at the inner stroke's inner edge (shift inward by stroke_in.width)
    // so the glow doesn't render underneath the inner stroke.
    let shift = style.stroke_in.width;
    GlyphMaterial {
        render_dist_range: (-AA + shift - AA, s + shift - AA),
        max_alpha_dist_range: (shift, (s * p).min((s - AA).max(0.0)) + shift),
        color: style.glow_in.color,
        offset: glam::Vec2::ZERO,
        gradient_region,
        roundness: style.glow_in.roundness,
    }
}

fn material_glow_out(
    style: &TextStyle,
    _glyph: &DecodedGlyph,
    gradient_region: Option<Rect>,
) -> GlyphMaterial {
    let s = style.glow_out.width;
    let p = style.glow_out.spread;
    // Start the glow at the outer stroke's outer edge (shift outward by stroke_out.width)
    // so the glow doesn't render underneath the outer stroke.
    let shift = -style.stroke_out.width;
    GlyphMaterial {
        render_dist_range: (-s + shift + AA, shift + AA),
        max_alpha_dist_range: ((-s * p).max((-s + AA).min(0.0)) + shift, shift),
        color: style.glow_out.color,
        offset: glam::Vec2::ZERO,
        gradient_region,
        roundness: style.glow_out.roundness,
    }
}

fn material_shadow(
    style: &TextStyle,
    _glyph: &DecodedGlyph,
    gradient_region: Option<Rect>,
) -> GlyphMaterial {
    let s = style.shadow.additional_width;
    let p = style.shadow.spread;
    GlyphMaterial {
        render_dist_range: (-s, LARGE_DIST),
        max_alpha_dist_range: (-s * p + AA, LARGE_DIST),
        color: style.shadow.color,
        offset: style.shadow.direction,
        gradient_region,
        roundness: style.shadow.roundness,
    }
}