dfui 0.1.0

Declarative UI framework that draws shapes, text and icons analytically in one wgpu shader
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
//! Glyph outlines as monotonic quadratic Béziers plus per-glyph band lists; the
//! fragment shader evaluates glyph coverage directly from these curves.

use std::ops::Range;

use read_fonts::model::Font;
use read_fonts::model::glyph::outline::{DrawMemory, DrawOptions, PathSink};
use read_fonts::types::GlyphId;

use crate::path::{Point as P, Quad, line};

/// Where a glyph's data lives in the shared buffers. Coordinates are em, y up.
#[derive(Clone, Copy, Debug)]
pub(crate) struct OutlineGlyph {
    pub header: u32,
    pub bands_h: u32,
    pub bands_v: u32,
    pub bbox: [f32; 4],
}

/// Where a stored shape's data sits, to hand back to [`Outlines::free`].
pub(crate) struct Block {
    curves: Range<usize>,
    bands: Range<usize>,
}

/// Freed spans of a buffer, sorted and merged.
#[derive(Default)]
struct FreeList(Vec<Range<usize>>);

impl FreeList {
    /// Start of a span of `n` taken from the first one big enough.
    fn take(&mut self, n: usize) -> Option<usize> {
        let i = self.0.iter().position(|r| r.len() >= n)?;
        let at = self.0[i].start;
        self.0[i].start += n;
        if self.0[i].is_empty() {
            self.0.remove(i);
        }
        Some(at)
    }

    fn give(&mut self, r: Range<usize>) {
        let i = self.0.partition_point(|f| f.start < r.start);
        self.0.insert(i, r);
        if i + 1 < self.0.len() && self.0[i].end == self.0[i + 1].start {
            self.0[i].end = self.0.remove(i + 1).end;
        }
        if i > 0 && self.0[i - 1].end == self.0[i].start {
            self.0[i - 1].end = self.0.remove(i).end;
        }
    }
}

/// Curves and band entries reserved at the front of the buffers for shapes
/// that change every frame (`PaintCx::polygon`); glyphs are stored after them,
/// and a frame that outgrows the reserve continues after the glyphs.
const TRANSIENT_CURVES: usize = 512;
const TRANSIENT_BANDS: usize = 4096;

/// GPU-bound storage: each curve is two vec4s `(p0, p1), (p2, 0, 0)`; `bands` holds
/// per-glyph `[start, count]` headers (horizontal then vertical) and curve indices.
pub(crate) struct Outlines {
    pub curves: Vec<[f32; 4]>,
    pub bands: Vec<u32>,
    /// Glyphs were added: upload everything.
    pub dirty: bool,
    /// Only the transient region changed.
    pub transient_dirty: bool,
    /// Next free curve and band entry in the transient region.
    transient: (usize, usize),
    /// Where stored data ends and this frame's overflow begins, as buffer lengths.
    stored: (usize, usize),
    free_curves: FreeList,
    free_bands: FreeList,
}

impl Default for Outlines {
    fn default() -> Self {
        Outlines {
            curves: vec![[0.0; 4]; 2 * TRANSIENT_CURVES],
            bands: vec![0; TRANSIENT_BANDS],
            dirty: true,
            transient_dirty: false,
            transient: (0, 0),
            stored: (2 * TRANSIENT_CURVES, TRANSIENT_BANDS),
            free_curves: FreeList::default(),
            free_bands: FreeList::default(),
        }
    }
}

impl Outlines {
    pub fn add(&mut self, font: &Font, id: GlyphId) -> Option<OutlineGlyph> {
        let quads = contours(font, id)?.into_iter().flatten().collect();
        self.insert(quads, 0.0, false)
    }

    /// Stores closed contours (y up) until the returned block is freed,
    /// reusing freed space when there is enough.
    pub fn store(&mut self, raw: Vec<Quad>, pad: f32) -> Option<(OutlineGlyph, Block)> {
        let quads = monotonic(raw)?;
        let (_, sized) = build(&quads, pad, 0, 0);
        let c = self.free_curves.take(quads.len());
        let b = self.free_bands.take(sized.len());
        let first = c.unwrap_or(self.curves.len() / 2);
        let header = b.unwrap_or(self.bands.len());
        let (glyph, bands) = build(&quads, pad, first as u32, header as u32);
        let block = Block {
            curves: first..first + quads.len(),
            bands: header..header + bands.len(),
        };
        match c {
            Some(_) => {
                let dst = &mut self.curves[2 * block.curves.start..2 * block.curves.end];
                for (d, s) in dst.iter_mut().zip(encode(&quads).flatten()) {
                    *d = s;
                }
            }
            None => self.curves.extend(encode(&quads).flatten()),
        }
        match b {
            Some(_) => self.bands[block.bands.clone()].copy_from_slice(&bands),
            None => self.bands.extend(bands),
        }
        if c.is_none() || b.is_none() {
            self.stored = (self.curves.len(), self.bands.len());
        }
        self.dirty = true;
        Some((glyph, block))
    }

    /// Makes a stored shape's space reusable; nothing may draw it afterwards.
    pub fn free(&mut self, block: Block) {
        self.free_curves.give(block.curves);
        self.free_bands.give(block.bands);
    }

    /// Frees the transient region; the runtime calls this before painting.
    pub fn begin_frame(&mut self) {
        self.transient = (0, 0);
        self.curves.truncate(self.stored.0);
        self.bands.truncate(self.stored.1);
    }

    /// Stores closed contours (y up) until the next `begin_frame`. `pad` widens
    /// the box so antialiasing on its edges isn't cut off.
    pub fn transient(&mut self, quads: Vec<Quad>, pad: f32) -> Option<OutlineGlyph> {
        self.insert(quads, pad, true)
    }

    fn insert(&mut self, raw: Vec<Quad>, pad: f32, transient: bool) -> Option<OutlineGlyph> {
        let quads = monotonic(raw)?;
        if transient {
            let (c, b) = self.transient;
            let (glyph, bands) = build(&quads, pad, c as u32, b as u32);
            let (c_end, b_end) = (c + quads.len(), b + bands.len());
            if c_end <= TRANSIENT_CURVES && b_end <= TRANSIENT_BANDS {
                for (dst, src) in self.curves[2 * c..2 * c_end]
                    .iter_mut()
                    .zip(encode(&quads).flatten())
                {
                    *dst = src;
                }
                self.bands[b..b_end].copy_from_slice(&bands);
                self.transient = (c_end, b_end);
                self.transient_dirty = true;
                return Some(glyph);
            }
        }
        let first = (self.curves.len() / 2) as u32;
        let (glyph, bands) = build(&quads, pad, first, self.bands.len() as u32);
        self.curves.extend(encode(&quads).flatten());
        self.bands.extend(bands);
        self.dirty = true;
        if !transient {
            // ponytail: overflow from this frame sitting before the glyph stays allocated; only a glyph first seen during an overflow frame leaks any.
            self.stored = (self.curves.len(), self.bands.len());
        }
        Some(glyph)
    }

    /// The transient region's slices, to upload when only it changed.
    pub fn transient_data(&self) -> (&[[f32; 4]], &[u32]) {
        (
            &self.curves[..2 * TRANSIENT_CURVES],
            &self.bands[..TRANSIENT_BANDS],
        )
    }
}

/// `raw` split into monotonic pieces; `None` if nothing is left.
fn monotonic(raw: Vec<Quad>) -> Option<Vec<Quad>> {
    let mut quads = Vec::new();
    for q in raw {
        split_monotonic(q, &mut quads);
    }
    (!quads.is_empty()).then_some(quads)
}

fn encode(quads: &[Quad]) -> impl Iterator<Item = [[f32; 4]; 2]> + '_ {
    quads.iter().map(|q| {
        [
            [q[0][0], q[0][1], q[1][0], q[1][1]],
            [q[2][0], q[2][1], 0.0, 0.0],
        ]
    })
}

/// The glyph and its band data, for curves stored from index `first` and bands from `header`.
fn build(quads: &[Quad], pad: f32, first: u32, header: u32) -> (OutlineGlyph, Vec<u32>) {
    let (mut lo, mut hi) = ([f32::MAX; 2], [f32::MIN; 2]);
    for q in quads {
        for p in q {
            for a in 0..2 {
                lo[a] = lo[a].min(p[a] - pad);
                hi[a] = hi[a].max(p[a] + pad);
            }
        }
    }

    let n = ((quads.len() as f32 / 2.0).ceil() as u32).clamp(1, 32);
    let mut bands = vec![0u32; 4 * n as usize];
    // Horizontal bands slice y and are scanned by +x rays; vertical bands the reverse.
    for (axis, base) in [(1usize, 0u32), (0, n)] {
        let size = (hi[axis] - lo[axis]) / n as f32;
        for i in 0..n {
            let (b0, b1) = (lo[axis] + i as f32 * size, lo[axis] + (i + 1) as f32 * size);
            let start = header + bands.len() as u32;
            let mut members: Vec<usize> = (0..quads.len())
                .filter(|&k| {
                    let q = &quads[k];
                    q[0][axis].min(q[2][axis]) <= b1 && q[0][axis].max(q[2][axis]) >= b0
                })
                .collect();
            // Furthest reach along the ray first, so the shader can stop at the
            // first curve lying entirely behind the pixel.
            let ray = 1 - axis;
            members.sort_by(|&a, &b| {
                let reach = |k: usize| quads[k][0][ray].max(quads[k][2][ray]);
                reach(b).total_cmp(&reach(a))
            });
            bands.extend(members.iter().map(|&k| first + k as u32));
            let h = 2 * (base + i) as usize;
            bands[h] = start;
            bands[h + 1] = header + bands.len() as u32 - start;
        }
    }
    let glyph = OutlineGlyph {
        header,
        bands_h: n,
        bands_v: n,
        bbox: [lo[0], lo[1], hi[0], hi[1]],
    };
    (glyph, bands)
}

/// A glyph's closed contours in em units, y up.
pub(crate) fn contours(font: &Font, id: GlyphId) -> Option<Vec<Vec<Quad>>> {
    let mut b = Builder {
        em: font.units_per_em() as f32,
        start: [0.0; 2],
        cur: [0.0; 2],
        contours: Vec::new(),
    };
    let glyph = font.outline_glyphs().get(id)?;
    glyph
        .draw(&DrawOptions::new(), DrawMemory::Scratch, &mut b)
        .ok()?;
    b.close();
    b.contours.retain(|c| !c.is_empty());
    Some(b.contours)
}

struct Builder {
    em: f32,
    start: P,
    cur: P,
    contours: Vec<Vec<Quad>>,
}

impl Builder {
    fn p(&self, x: f32, y: f32) -> P {
        [x / self.em, y / self.em]
    }

    fn push(&mut self, q: Quad) {
        if let Some(c) = self.contours.last_mut() {
            c.push(q);
        }
    }
}

impl PathSink for Builder {
    fn move_to(&mut self, x: f32, y: f32) {
        self.close();
        self.contours.push(Vec::new());
        self.start = self.p(x, y);
        self.cur = self.start;
    }

    fn line_to(&mut self, x: f32, y: f32) {
        let p = self.p(x, y);
        self.push(line(self.cur, p));
        self.cur = p;
    }

    fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
        let (c, p) = (self.p(x1, y1), self.p(x, y));
        self.push([self.cur, c, p]);
        self.cur = p;
    }

    fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
        // ponytail: fixed 4-way split per cubic (CFF fonts); adaptive error bound if accuracy matters.
        let cubic = [self.cur, self.p(x1, y1), self.p(x2, y2), self.p(x, y)];
        let at = |t: f32| -> P {
            let u = 1.0 - t;
            let w = [u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t];
            [0, 1].map(|a| (0..4).map(|i| w[i] * cubic[i][a]).sum())
        };
        let d = |t: f32| -> P {
            let u = 1.0 - t;
            let w = [
                -3.0 * u * u,
                3.0 * u * u - 6.0 * u * t,
                6.0 * u * t - 3.0 * t * t,
                3.0 * t * t,
            ];
            [0, 1].map(|a| (0..4).map(|i| w[i] * cubic[i][a]).sum())
        };
        for i in 0..4 {
            let (t0, t1) = (i as f32 / 4.0, (i + 1) as f32 / 4.0);
            let (p0, p2) = (at(t0), at(t1));
            let (d0, d2) = (d(t0), d(t1));
            let h = (t1 - t0) / 2.0;
            // Average of the two tangent-implied control points.
            let c = [0, 1].map(|a| (p0[a] + d0[a] * h + p2[a] - d2[a] * h) / 2.0);
            self.push([p0, c, p2]);
        }
        self.cur = cubic[3];
    }

    fn close(&mut self) {
        if self.cur != self.start {
            self.line_to(self.start[0] * self.em, self.start[1] * self.em);
        }
    }
}

fn lerp(a: P, b: P, t: f32) -> P {
    [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
}

/// Splits at x/y extrema so each piece crosses any axis-aligned line at most once,
/// which lets the shader count crossings from endpoints alone.
fn split_monotonic(q: Quad, out: &mut Vec<Quad>) {
    let mut ts: Vec<f32> = (0..2)
        .filter_map(|a| {
            let d = q[0][a] - 2.0 * q[1][a] + q[2][a];
            let t = (q[0][a] - q[1][a]) / d;
            (d.abs() > 1e-9 && t > 1e-4 && t < 1.0 - 1e-4).then_some(t)
        })
        .collect();
    ts.sort_by(f32::total_cmp);
    let mut rest = q;
    let mut done = 0.0;
    for t in ts {
        let t = (t - done) / (1.0 - done);
        let (a, b) = (lerp(rest[0], rest[1], t), lerp(rest[1], rest[2], t));
        let m = lerp(a, b, t);
        push_clamped([rest[0], a, m], out);
        rest = [m, b, rest[2]];
        done += (1.0 - done) * t;
    }
    push_clamped(rest, out);
}

fn push_clamped(mut q: Quad, out: &mut Vec<Quad>) {
    if q[0] == q[2] {
        return;
    }
    // Float error after splitting can leave the control point just outside the
    // endpoint range, breaking monotonicity.
    q[1] = [0, 1].map(|a| q[1][a].clamp(q[0][a].min(q[2][a]), q[0][a].max(q[2][a])));
    out.push(q);
}

#[cfg(test)]
mod tests {
    use super::*;

    /// CPU mirror of the shader's horizontal-ray winding count.
    fn winding(o: &Outlines, g: &OutlineGlyph, p: P) -> i32 {
        let band = (((p[1] - g.bbox[1]) / (g.bbox[3] - g.bbox[1]) * g.bands_h as f32) as u32)
            .min(g.bands_h - 1);
        let h = (g.header + 2 * band) as usize;
        let (start, count) = (o.bands[h] as usize, o.bands[h + 1] as usize);
        let mut w = 0;
        for &ci in &o.bands[start..start + count] {
            let (a, b) = (o.curves[2 * ci as usize], o.curves[2 * ci as usize + 1]);
            let (p0, p1, p2) = ([a[0], a[1]], [a[2], a[3]], [b[0], b[1]]);
            if (p0[1] <= p[1]) == (p2[1] <= p[1]) {
                continue;
            }
            let (qa, qb, qc) = (
                p0[1] - 2.0 * p1[1] + p2[1],
                2.0 * (p1[1] - p0[1]),
                p0[1] - p[1],
            );
            let t = if qa.abs() < 1e-7 {
                -qc / qb
            } else {
                let d = (qb * qb - 4.0 * qa * qc).max(0.0).sqrt();
                let t1 = (-qb + d) / (2.0 * qa);
                if (-1e-4..=1.0 + 1e-4).contains(&t1) {
                    t1
                } else {
                    (-qb - d) / (2.0 * qa)
                }
            };
            let x = lerp(lerp(p0, p1, t), lerp(p1, p2, t), t)[0];
            if x > p[0] {
                w += if p2[1] > p0[1] { 1 } else { -1 };
            }
        }
        w
    }

    #[test]
    fn o_has_a_hole() {
        let font = Font::new(&include_bytes!("../assets/DejaVuSans.ttf")[..], 0).unwrap();
        let mut o = Outlines::default();
        let id = font.charmap().map_unicode('O').unwrap();
        let g = o.add(&font, id).unwrap();
        let [x0, y0, x1, y1] = g.bbox;
        let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
        assert_eq!(winding(&o, &g, [cx, cy]), 0, "center of O is the hole");
        assert_ne!(winding(&o, &g, [x0 + 0.02, cy]), 0, "left stroke is inside");
        assert_eq!(
            winding(&o, &g, [x0 - 0.1, cy]),
            0,
            "left of glyph is outside"
        );
        assert_ne!(winding(&o, &g, [cx, y1 - 0.02]), 0, "top stroke is inside");
    }

    #[test]
    fn transient_shapes_past_the_reserved_region_still_draw() {
        let square =
            crate::path::Path::polygon(&[[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0]]);
        let quads: Vec<Quad> = square.contours.concat();
        let font = Font::new(&include_bytes!("../assets/DejaVuSans.ttf")[..], 0).unwrap();
        let mut o = Outlines::default();
        let shapes: Vec<_> = (0..TRANSIENT_CURVES)
            .map(|_| o.transient(quads.clone(), 1.0).unwrap())
            .collect();
        for g in [&shapes[0], shapes.last().unwrap()] {
            assert_ne!(winding(&o, g, [5.0, 5.0]), 0);
        }
        assert!(o.dirty, "the overflow needs uploading");

        let (curves, bands) = (o.curves.len(), o.bands.len());
        o.begin_frame();
        o.transient(quads.clone(), 1.0).unwrap();
        assert!(
            o.curves.len() < curves && o.bands.len() < bands,
            "overflow freed"
        );

        // A glyph stored behind this frame's overflow has to survive it.
        for _ in 0..TRANSIENT_CURVES {
            o.transient(quads.clone(), 1.0).unwrap();
        }
        let g = o
            .add(&font, font.charmap().map_unicode('O').unwrap())
            .unwrap();
        o.begin_frame();
        let [x0, y0, _, y1] = g.bbox;
        assert_ne!(winding(&o, &g, [x0 + 0.02, (y0 + y1) / 2.0]), 0);
    }

    #[test]
    fn transient_shapes_fill_and_recycle_each_frame() {
        let square =
            crate::path::Path::polygon(&[[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0]]);
        let quads: Vec<Quad> = square.contours.concat();
        let mut o = Outlines::default();
        let g = o.transient(quads.clone(), 1.0).unwrap();
        assert_eq!(g.header, 0);
        assert_ne!(winding(&o, &g, [5.0, 5.0]), 0);
        assert_eq!(winding(&o, &g, [10.5, 5.0]), 0, "padding is outside");
        let second = o.transient(quads.clone(), 1.0).unwrap();
        assert_ne!(second.header, 0);
        o.begin_frame();
        assert_eq!(o.transient(quads, 1.0).unwrap().header, 0);
    }
}