hephaestus 0.2.0

Backend-agnostic 2D scene renderer for data visualization.
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
//! A `SceneBuilder` that records every call into an owned op list.
//!
//! Used to replay scenes into vector backends (SVG, PDF) that don't fit the
//! "render to RGBA8 buffer" shape. The op enum is intentionally exhaustive —
//! adding a new variant means SVG/PDF emitters need to handle it.

use super::{Glyph, GlyphRun, SceneBuilder};
use crate::blend::BlendMode;
use crate::brush::{Brush, Image, Sampling};
use crate::geometry::Affine;
use crate::mesh::Mesh;
use crate::path::{FillRule, Path};
use crate::pick::PickId;
use crate::stroke::Stroke;

/// One captured draw operation.
#[derive(Debug, Clone, PartialEq)]
pub enum Op {
    Fill {
        rule: FillRule,
        transform: Affine,
        brush: Brush,
        brush_transform: Option<Affine>,
        path: Path,
        pick_id: PickId,
    },
    Stroke {
        stroke: Stroke,
        transform: Affine,
        brush: Brush,
        brush_transform: Option<Affine>,
        path: Path,
        pick_id: PickId,
    },
    DrawImage {
        image: Image,
        transform: Affine,
        sampling: Sampling,
        alpha: f32,
        pick_id: PickId,
    },
    DrawGlyphs(OwnedGlyphRun),
    DrawMesh {
        mesh: Mesh,
        transform: Affine,
        pick_id: PickId,
    },
    PushLayer {
        blend: BlendMode,
        alpha: f32,
        transform: Affine,
        clip: Path,
    },
    PopLayer,
}

/// Owned counterpart of `GlyphRun<'_>` for storage in `Op::DrawGlyphs`.
#[derive(Debug, Clone, PartialEq)]
pub struct OwnedGlyphRun {
    pub font: super::Font,
    pub font_size: f32,
    pub transform: Affine,
    pub glyph_transform: Option<Affine>,
    pub brush: Brush,
    pub brush_alpha: f32,
    pub hint: bool,
    pub glyphs: Vec<Glyph>,
    /// `None` means fill the glyph outlines; `Some(stroke)` means
    /// stroke them.
    pub style: Option<crate::stroke::Stroke>,
    pub pick_id: PickId,
}

/// Recording scene: appends every call to an op list.
///
/// Equality is op-for-op, which is what lets two scenes be compared as
/// *drawing* rather than as pixels — useful when the rasteriser is the
/// variable you want to hold still.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct RecordingScene {
    pub ops: Vec<Op>,
}

impl RecordingScene {
    /// Construct an empty recording scene.
    pub fn new() -> Self {
        Self::default()
    }

    /// Issue every recorded op against `scene`, in order.
    ///
    /// The inverse of recording. A backend whose rasteriser needs the
    /// frame's dimensions before it will accept draws records first and
    /// replays once the size is known; a backend that rasterises a second
    /// scene from the same draws (a pick pass) replays twice.
    pub fn replay(&self, scene: &mut dyn SceneBuilder) {
        for op in &self.ops {
            match op {
                Op::Fill {
                    rule,
                    transform,
                    brush,
                    brush_transform,
                    path,
                    pick_id,
                } => scene.fill(*rule, *transform, brush, *brush_transform, path, *pick_id),
                Op::Stroke {
                    stroke,
                    transform,
                    brush,
                    brush_transform,
                    path,
                    pick_id,
                } => scene.stroke(stroke, *transform, brush, *brush_transform, path, *pick_id),
                Op::DrawImage {
                    image,
                    transform,
                    sampling,
                    alpha,
                    pick_id,
                } => scene.draw_image(image, *transform, *sampling, *alpha, *pick_id),
                Op::DrawGlyphs(run) => scene.draw_glyphs(
                    &GlyphRun {
                        font: &run.font,
                        font_size: run.font_size,
                        transform: run.transform,
                        glyph_transform: run.glyph_transform,
                        brush: &run.brush,
                        brush_alpha: run.brush_alpha,
                        hint: run.hint,
                        glyphs: &run.glyphs,
                        style: run.style.as_ref(),
                    },
                    run.pick_id,
                ),
                Op::DrawMesh {
                    mesh,
                    transform,
                    pick_id,
                } => scene.draw_mesh(mesh, *transform, *pick_id),
                Op::PushLayer {
                    blend,
                    alpha,
                    transform,
                    clip,
                } => scene.push_layer(*blend, *alpha, *transform, clip),
                Op::PopLayer => scene.pop_layer(),
            }
        }
    }
}

impl SceneBuilder for RecordingScene {
    fn clear(&mut self) {
        self.ops.clear();
    }

    fn fill(
        &mut self,
        rule: FillRule,
        transform: Affine,
        brush: &Brush,
        brush_transform: Option<Affine>,
        path: &Path,
        pick_id: PickId,
    ) {
        self.ops.push(Op::Fill {
            rule,
            transform,
            brush: brush.clone(),
            brush_transform,
            path: path.clone(),
            pick_id,
        });
    }

    fn stroke(
        &mut self,
        stroke: &Stroke,
        transform: Affine,
        brush: &Brush,
        brush_transform: Option<Affine>,
        path: &Path,
        pick_id: PickId,
    ) {
        self.ops.push(Op::Stroke {
            stroke: stroke.clone(),
            transform,
            brush: brush.clone(),
            brush_transform,
            path: path.clone(),
            pick_id,
        });
    }

    fn draw_image(
        &mut self,
        image: &Image,
        transform: Affine,
        sampling: Sampling,
        alpha: f32,
        pick_id: PickId,
    ) {
        self.ops.push(Op::DrawImage {
            image: image.clone(),
            transform,
            sampling,
            alpha,
            pick_id,
        });
    }

    fn draw_glyphs(&mut self, run: &GlyphRun<'_>, pick_id: PickId) {
        self.ops.push(Op::DrawGlyphs(OwnedGlyphRun {
            font: run.font.clone(),
            font_size: run.font_size,
            transform: run.transform,
            glyph_transform: run.glyph_transform,
            brush: run.brush.clone(),
            brush_alpha: run.brush_alpha,
            hint: run.hint,
            glyphs: run.glyphs.to_vec(),
            style: run.style.cloned(),
            pick_id,
        }));
    }

    fn draw_mesh(&mut self, mesh: &Mesh, transform: Affine, pick_id: PickId) {
        self.ops.push(Op::DrawMesh {
            mesh: mesh.clone(),
            transform,
            pick_id,
        });
    }

    fn push_layer(&mut self, blend: BlendMode, alpha: f32, transform: Affine, clip: &Path) {
        self.ops.push(Op::PushLayer {
            blend,
            alpha,
            transform,
            clip: clip.clone(),
        });
    }

    fn pop_layer(&mut self) {
        self.ops.push(Op::PopLayer);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::blend::{Compose, Mix};
    use crate::brush::{Blob, ImageAlphaType, ImageFormat};
    use crate::color::Color;
    use crate::geometry::Point;
    use crate::mesh::Mesh;
    use crate::scene::{Font, Glyph, GlyphRun};

    fn solid(r: f32, g: f32, b: f32) -> Brush {
        Brush::Solid(Color::new([r, g, b, 1.0]))
    }

    /// A unit square, enough to tell one recorded path from another.
    fn square(side: f64) -> Path {
        let mut p = Path::new();
        p.move_to(Point::new(0.0, 0.0));
        p.line_to(Point::new(side, 0.0));
        p.line_to(Point::new(side, side));
        p.close_path();
        p
    }

    /// A 2×1 RGBA8 image — the payload is never decoded, only carried.
    fn test_image() -> Image {
        Image {
            data: Blob::from(vec![1u8, 2, 3, 4, 5, 6, 7, 8]),
            format: ImageFormat::Rgba8,
            alpha_type: ImageAlphaType::Alpha,
            width: 2,
            height: 1,
        }
    }

    #[test]
    fn records_fill_with_its_arguments_intact() {
        let mut scene = RecordingScene::new();
        let brush = solid(1.0, 0.0, 0.0);
        let path = square(3.0);
        scene.fill(
            FillRule::EvenOdd,
            Affine::translate((5.0, 6.0)),
            &brush,
            Some(Affine::scale(2.0)),
            &path,
            PickId::Id(11),
        );
        match &scene.ops[..] {
            [Op::Fill {
                rule,
                transform,
                brush: b,
                brush_transform,
                path: p,
                pick_id,
            }] => {
                assert_eq!(*rule, FillRule::EvenOdd);
                assert_eq!(*transform, Affine::translate((5.0, 6.0)));
                assert_eq!(*b, brush);
                assert_eq!(*brush_transform, Some(Affine::scale(2.0)));
                assert_eq!(p.elements(), path.elements());
                assert_eq!(*pick_id, PickId::Id(11));
            }
            other => panic!("expected a single Fill, got {other:?}"),
        }
    }

    #[test]
    fn records_stroke_with_its_pen_and_pick_id() {
        let mut scene = RecordingScene::new();
        let brush = solid(0.0, 0.0, 1.0);
        let path = square(4.0);
        let stroke = Stroke::new(2.5).with_caps(crate::stroke::Cap::Square);
        scene.stroke(
            &stroke,
            Affine::IDENTITY,
            &brush,
            None,
            &path,
            PickId::Block,
        );
        match &scene.ops[..] {
            [Op::Stroke {
                stroke: s,
                brush: b,
                brush_transform,
                path: p,
                pick_id,
                ..
            }] => {
                assert_eq!(s.width, 2.5);
                assert_eq!(s.start_cap, crate::stroke::Cap::Square);
                assert_eq!(*b, brush);
                assert!(brush_transform.is_none());
                assert_eq!(p.elements(), path.elements());
                assert_eq!(*pick_id, PickId::Block);
            }
            other => panic!("expected a single Stroke, got {other:?}"),
        }
    }

    #[test]
    fn records_draw_image_with_its_sampling_and_alpha() {
        let mut scene = RecordingScene::new();
        let image = test_image();
        scene.draw_image(
            &image,
            Affine::scale(3.0),
            Sampling::Nearest,
            0.25,
            PickId::Id(9),
        );
        match &scene.ops[..] {
            [Op::DrawImage {
                image: i,
                transform,
                sampling,
                alpha,
                pick_id,
            }] => {
                assert_eq!(i.width, 2);
                assert_eq!(i.height, 1);
                assert_eq!(i.data.as_ref(), image.data.as_ref());
                assert_eq!(*transform, Affine::scale(3.0));
                assert_eq!(*sampling, Sampling::Nearest);
                assert_eq!(*alpha, 0.25);
                assert_eq!(*pick_id, PickId::Id(9));
            }
            other => panic!("expected a single DrawImage, got {other:?}"),
        }
    }

    #[test]
    fn records_draw_glyphs_as_an_owned_run() {
        let font = Font::new(Blob::from(vec![0u8; 4]), 1);
        let brush = solid(0.0, 1.0, 0.0);
        let glyphs = [
            Glyph {
                id: 3,
                x: 0.0,
                y: 1.0,
            },
            Glyph {
                id: 4,
                x: 10.0,
                y: 1.0,
            },
        ];
        let stroke = Stroke::new(0.5);
        let run = GlyphRun {
            font: &font,
            font_size: 14.0,
            transform: Affine::translate((2.0, 3.0)),
            glyph_transform: Some(Affine::scale(0.5)),
            brush: &brush,
            brush_alpha: 0.75,
            hint: true,
            glyphs: &glyphs,
            style: Some(&stroke),
        };
        let mut scene = RecordingScene::new();
        scene.draw_glyphs(&run, PickId::Id(21));

        match &scene.ops[..] {
            [Op::DrawGlyphs(owned)] => {
                assert_eq!(owned.font_size, 14.0);
                assert_eq!(owned.transform, Affine::translate((2.0, 3.0)));
                assert_eq!(owned.glyph_transform, Some(Affine::scale(0.5)));
                assert_eq!(owned.brush, brush);
                assert_eq!(owned.brush_alpha, 0.75);
                assert!(owned.hint);
                assert_eq!(owned.glyphs.len(), 2);
                assert_eq!(owned.glyphs[1].id, 4);
                assert_eq!(owned.glyphs[1].x, 10.0);
                assert_eq!(owned.style.as_ref().map(|s| s.width), Some(0.5));
                assert_eq!(owned.pick_id, PickId::Id(21));
            }
            other => panic!("expected a single DrawGlyphs, got {other:?}"),
        }
    }

    #[test]
    fn records_glyph_runs_that_fill_without_a_stroke_style() {
        let font = Font::new(Blob::from(vec![0u8; 4]), 0);
        let brush = solid(0.0, 0.0, 0.0);
        let run = GlyphRun {
            font: &font,
            font_size: 10.0,
            transform: Affine::IDENTITY,
            glyph_transform: None,
            brush: &brush,
            brush_alpha: 1.0,
            hint: false,
            glyphs: &[],
            style: None,
        };
        let mut scene = RecordingScene::new();
        scene.draw_glyphs(&run, PickId::Skip);
        match &scene.ops[..] {
            [Op::DrawGlyphs(owned)] => {
                assert!(owned.style.is_none());
                assert!(owned.glyphs.is_empty());
                assert_eq!(owned.pick_id, PickId::Skip);
            }
            other => panic!("expected a single DrawGlyphs, got {other:?}"),
        }
    }

    #[test]
    fn records_layer_pushes_and_pops_in_order() {
        let mut scene = RecordingScene::new();
        let clip = square(8.0);
        let blend = BlendMode::new(Mix::Multiply, Compose::SrcOver);
        scene.push_layer(blend, 0.5, Affine::translate((1.0, 2.0)), &clip);
        scene.pop_layer();
        match &scene.ops[..] {
            [Op::PushLayer {
                blend: b,
                alpha,
                transform,
                clip: c,
            }, Op::PopLayer] => {
                assert_eq!(*b, blend);
                assert_eq!(*alpha, 0.5);
                assert_eq!(*transform, Affine::translate((1.0, 2.0)));
                assert_eq!(c.elements(), clip.elements());
            }
            other => panic!("expected PushLayer then PopLayer, got {other:?}"),
        }
    }

    #[test]
    fn clear_drops_everything_recorded_so_far() {
        let mut scene = RecordingScene::new();
        let brush = solid(1.0, 1.0, 1.0);
        scene.fill(
            FillRule::NonZero,
            Affine::IDENTITY,
            &brush,
            None,
            &square(1.0),
            PickId::Skip,
        );
        scene.pop_layer();
        assert_eq!(scene.ops.len(), 2);
        scene.clear();
        assert!(scene.ops.is_empty());
        // Still usable for the next frame.
        scene.pop_layer();
        assert_eq!(scene.ops.len(), 1);
    }

    #[test]
    fn ops_accumulate_in_call_order() {
        let mut scene = RecordingScene::new();
        let brush = solid(1.0, 1.0, 1.0);
        scene.push_layer(BlendMode::NORMAL, 1.0, Affine::IDENTITY, &square(1.0));
        scene.fill(
            FillRule::NonZero,
            Affine::IDENTITY,
            &brush,
            None,
            &square(1.0),
            PickId::Skip,
        );
        scene.pop_layer();
        let kinds: Vec<&str> = scene
            .ops
            .iter()
            .map(|op| match op {
                Op::PushLayer { .. } => "push",
                Op::Fill { .. } => "fill",
                Op::PopLayer => "pop",
                _ => "other",
            })
            .collect();
        assert_eq!(kinds, ["push", "fill", "pop"]);
    }

    /// Two recordings of the same glyph run compare equal even when font
    /// resolution handed each one its own blob for the same file.
    ///
    /// This is what makes op-for-op comparison usable as a test oracle:
    /// without it, any scene containing text compares unequal to an
    /// identical scene whenever the font file happened to be loaded
    /// twice.
    #[test]
    fn identical_glyph_runs_compare_equal_across_separate_font_blobs() {
        let bytes = vec![0u8, 1, 2, 3];
        let brush = solid(0.0, 0.0, 0.0);
        let glyphs = [Glyph {
            id: 12,
            x: 1.5,
            y: 2.5,
        }];

        let record_with = |font: &Font| {
            let run = GlyphRun {
                font,
                font_size: 12.0,
                transform: Affine::IDENTITY,
                glyph_transform: None,
                brush: &brush,
                brush_alpha: 1.0,
                hint: false,
                glyphs: &glyphs,
                style: None,
            };
            let mut scene = RecordingScene::new();
            scene.draw_glyphs(&run, PickId::Skip);
            scene
        };

        let a = record_with(&Font::new(Blob::from(bytes.clone()), 0));
        let b = record_with(&Font::new(Blob::from(bytes), 0));
        assert_eq!(a, b);
    }

    /// The counterpart: a genuinely different face is still caught.
    #[test]
    fn glyph_runs_over_different_faces_are_not_equal() {
        let brush = solid(0.0, 0.0, 0.0);
        let glyphs = [Glyph {
            id: 12,
            x: 1.5,
            y: 2.5,
        }];

        let record_with = |font: &Font| {
            let run = GlyphRun {
                font,
                font_size: 12.0,
                transform: Affine::IDENTITY,
                glyph_transform: None,
                brush: &brush,
                brush_alpha: 1.0,
                hint: false,
                glyphs: &glyphs,
                style: None,
            };
            let mut scene = RecordingScene::new();
            scene.draw_glyphs(&run, PickId::Skip);
            scene
        };

        let a = record_with(&Font::new(Blob::from(vec![0u8, 1, 2, 3]), 0));
        let b = record_with(&Font::new(Blob::from(vec![9u8, 9, 9, 9]), 0));
        assert_ne!(a, b);
    }

    #[test]
    fn records_draw_mesh() {
        let mesh = Mesh::new(
            vec![
                Point::new(0.0, 0.0),
                Point::new(10.0, 0.0),
                Point::new(0.0, 10.0),
            ],
            vec![
                Color::new([1.0, 0.0, 0.0, 1.0]),
                Color::new([0.0, 1.0, 0.0, 1.0]),
                Color::new([0.0, 0.0, 1.0, 1.0]),
            ],
            vec![0, 1, 2],
        );
        let mut scene = RecordingScene::default();
        scene.draw_mesh(&mesh, Affine::IDENTITY, PickId::Id(42));
        assert_eq!(scene.ops.len(), 1);
        match &scene.ops[0] {
            Op::DrawMesh {
                mesh: m,
                transform,
                pick_id,
            } => {
                assert_eq!(m.vertex_count(), 3);
                assert_eq!(m.triangle_count(), 1);
                assert_eq!(*transform, Affine::IDENTITY);
                assert!(matches!(pick_id, PickId::Id(42)));
            }
            other => panic!("expected DrawMesh, got {other:?}"),
        }
    }
}