viewport-lib-types 0.4.0

Pure-data types for viewport-lib: submission payloads, handles, and frame config, free of any GPU dependency.
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
//! Polyline overlay geometry and its join and cap styles.

use crate::colour::Colour;
use crate::overlay::*;

/// How an [`OverlayPolylineItem`] handles each joint between segments.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LineJoin {
    /// Mitre join: extend both segment edges until they meet. Falls back to
    /// `Bevel` automatically when the join would exceed `mitre_limit`.
    /// Default.
    #[default]
    Mitre,
    /// Bevel join: cut the outer corner flat between the two segments.
    Bevel,
    /// Round join: an arc of the stroke's half-width round the outer corner.
    Round,
}

/// End-cap style for a stroke: an open [`OverlayPolylineItem`], a stroked
/// vector path, the ends of each dash, and the analytic
/// [`OverlayShape::Line`](crate::overlay::OverlayShape).
///
/// The meanings follow every 2D drawing API: `Butt` stops at the end point,
/// `Square` runs on half the stroke width past it, and `Round` ends in a
/// half-disc of the stroke's half-width centred on it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LineCap {
    /// Flat cut flush with the end point. Default.
    #[default]
    Butt,
    /// Flat cut extended half the stroke width beyond the end point.
    Square,
    /// Semicircular cap centred on the end point.
    Round,
}

/// Stroke pattern for a polyline.
///
/// Dash and dot placement is measured in accumulated arc length along the
/// path. The unit depends on the item: logical pixels for the screen-space
/// [`OverlayPolylineItem`], world-space units for the 3-D
/// [`OverlayPolylineItem`](crate::overlay::OverlayPolylineItem) (measured along the
/// line in its input space). On closed overlay polylines the pattern continues
/// across the final-to-first segment.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum StrokePattern {
    /// Continuous stroke (default).
    #[default]
    Solid,
    /// Dashes of `dash_length` pixels separated by `gap_length` pixels.
    Dashed {
        /// Length of each visible dash, in pixels of arc length.
        dash_length: f32,
        /// Length of each gap between dashes, in pixels of arc length.
        gap_length: f32,
        /// Shifts the pattern backwards along the path; animating this
        /// upwards produces a marching-ants effect.
        offset: f32,
    },
    /// Discs of the stroke thickness placed along the path.
    Dotted {
        /// Distance between dot centres, in pixels of arc length.
        spacing: f32,
        /// Shifts the first dot along the path.
        offset: f32,
    },
}

/// The stroke of an [`OverlayPolylineItem`] or of a vector path
/// ([`OverlayShape::Vector`]): everything about the line itself.
///
/// This is the item's own geometry, not a band drawn around some other shape,
/// so it lives here rather than on [`OverlayStyle`]. An analytic overlay shape
/// has no stroke: an edge band on one is a [`ShadowLayer`] with no blur and a
/// spread.
///
/// A width of `0.0` is a hairline: a line one device pixel wide at any scale,
/// group transform, or pixels per point.
///
/// [`OverlayShape::Vector`]: crate::overlay::OverlayShape::Vector
/// [`OverlayStyle`]: crate::overlay::OverlayStyle
/// [`ShadowLayer`]: crate::overlay::ShadowLayer
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct OverlayStroke {
    /// Stroke width in logical pixels. `0.0` draws a one-device-pixel
    /// hairline; a negative width draws nothing.
    pub width: f32,
    /// RGBA colour in linear float format.
    pub colour: crate::colour::Colour,
    /// Solid, dashed, or dotted.
    pub pattern: StrokePattern,
    /// How segment joints are drawn.
    pub join: LineJoin,
    /// Mitre limit: when the mitre extension exceeds this multiple of `width`,
    /// the joint auto-falls back to a bevel.
    pub mitre_limit: f32,
    /// End-cap style for open polylines and dash ends. Closed solid polylines
    /// have no free ends, so caps are ignored there.
    pub cap: LineCap,
}

impl Default for OverlayStroke {
    fn default() -> Self {
        Self {
            width: 2.0,
            colour: Colour::linear(1.0, 1.0, 1.0, 1.0),
            pattern: StrokePattern::Solid,
            join: LineJoin::Mitre,
            mitre_limit: 4.0,
            cap: LineCap::Butt,
        }
    }
}

impl OverlayStroke {
    /// A solid stroke of `width` logical pixels in `colour`, with the default
    /// join, mitre limit, and cap.
    pub fn new(width: f32, colour: impl Into<crate::colour::Colour>) -> Self {
        Self {
            width,
            colour: colour.into(),
            ..Default::default()
        }
    }

    /// A hairline in `colour`: one device pixel wide whatever the scale.
    pub fn hairline(colour: impl Into<crate::colour::Colour>) -> Self {
        Self::new(0.0, colour)
    }

    /// Set the dash or dot pattern.
    pub fn with_pattern(mut self, pattern: StrokePattern) -> Self {
        self.pattern = pattern;
        self
    }

    /// Set how segment joints are drawn.
    pub fn with_join(mut self, join: LineJoin) -> Self {
        self.join = join;
        self
    }

    /// Set the mitre limit as a multiple of `width`.
    pub fn with_mitre_limit(mut self, mitre_limit: f32) -> Self {
        self.mitre_limit = mitre_limit;
        self
    }

    /// Set the end-cap style.
    pub fn with_cap(mut self, cap: LineCap) -> Self {
        self.cap = cap;
        self
    }
}

/// A stroked polyline rendered as a screen-space overlay.
///
/// Constructed from a list of waypoints in logical pixels. Tessellated on
/// the CPU into a triangle list each frame; rendered through the same
/// pipeline as overlay rects and labels (no SDF, no shader changes).
///
/// Use `OverlayPolylineItem::from_path` to construct from a closure that
/// samples a curve at N points (Bezier traces, lissajous, custom paths).
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct OverlayPolylineItem {
    /// Waypoints in logical pixels, relative to the resolved `anchor` origin.
    /// With the default anchor (viewport top-left) and a zero `position` these
    /// are absolute screen coordinates.
    pub points: Vec<[f32; 2]>,
    /// Where the item hangs from and which point of its own box lands there.
    ///
    /// `transform.translate` is a nudge from the resolved origin, and a world
    /// origin behind the camera or off screen culls the item for the frame.
    pub anchoring: OverlayAnchoring,
    /// Translate, rotate, and scale, in logical pixels and radians.
    ///
    /// `translate` is the nudge from the resolved `anchor` origin, so with the
    /// default anchor and alignment it is the absolute screen placement.
    /// Rotation turns the item inside its extent box, which stays
    /// axis-aligned, so `anchoring.align` places the unrotated box and the
    /// content turns within it. See [`OverlayTransform`] for how an item's
    /// transform composes with the transform of a retained group containing
    /// it.
    pub transform: OverlayTransform,
    /// Baked appearance: fill, shadow layers, and backdrop effects.
    ///
    /// Shared across the overlay item types, so a field can be present and
    /// inert here. Ask
    /// [`OverlayStyleSupport`](crate::overlay::OverlayStyleSupport) for what
    /// this family draws.
    pub style: OverlayStyle,
    /// Animation tracks resolved each frame against `OverlayFrame::time`.
    ///
    /// Boxed and `None` for a static item: the track block is several times
    /// the size of the rest of the item, so only items that animate pay for
    /// it. See [`OverlayAnimations`] for why the channel list is what it is.
    pub animations: Option<Box<OverlayAnimations>>,
    /// What this item is clipped to: an axis-aligned box, a mask shape, or
    /// both. The default clips nothing.
    pub clip: OverlayClip,
    /// The line itself: width, colour, pattern, joins and caps.
    ///
    /// `None` draws no line at all, which is what a closed polyline with a
    /// fill and no outline wants.
    pub stroke: Option<OverlayStroke>,
    /// Optional stroke width per point, in logical pixels, replacing the
    /// stroke's own `width` along the line.
    ///
    /// When set, this must have the same length as `points`; otherwise the
    /// stroke's width applies. The width runs linearly between points, so a
    /// brush stroke tapers by giving its ends a small width. Shadow layers
    /// still follow the stroke's own `width`.
    pub widths: Option<Vec<f32>>,
    /// When `true`, the last point connects back to the first.
    pub closed: bool,
    /// Optional per-point UVs for textured interiors.
    ///
    /// When set, this must have the same length as `points`. Otherwise the
    /// renderer falls back to bounds-mapped UVs.
    pub uvs: Option<Vec<[f32; 2]>>,
    /// Draw order relative to other overlay rects, polylines, and labels.
    /// Lower values render first (further back).
    pub z_order: i32,
}

impl Default for OverlayPolylineItem {
    fn default() -> Self {
        Self {
            points: Vec::new(),
            anchoring: crate::overlay::OverlayAnchoring::default(),
            transform: OverlayTransform::IDENTITY,
            style: OverlayStyle::default(),
            animations: None,
            clip: OverlayClip::default(),
            stroke: Some(OverlayStroke::default()),
            widths: None,
            closed: false,
            uvs: None,
            z_order: 0,
        }
    }
}

impl OverlayPolylineItem {
    /// Create a polyline from `points` (waypoints in logical pixels from the
    /// viewport top-left). All other fields take their defaults; set them with
    /// the `with_*` methods below.
    pub fn new(points: Vec<[f32; 2]>) -> Self {
        Self {
            points,
            ..Default::default()
        }
    }

    /// Set the origin the path hangs from (a viewport corner or a world point).
    pub fn with_anchor(mut self, anchor: OverlayOrigin) -> Self {
        self.anchoring.origin = anchor;
        self
    }

    /// Pin the path to a world-space position, reprojected each frame. Sugar for
    /// `with_anchor(OverlayOrigin::World(pos))`.
    pub fn with_world_anchor(mut self, pos: impl crate::scene::IntoWorldPosition) -> Self {
        self.anchoring.origin = OverlayOrigin::World(pos.into_world_position());
        self
    }

    /// Set the placement in logical pixels relative to the resolved anchor
    /// origin, added to every point.
    pub fn with_position(mut self, position: [f32; 2]) -> Self {
        self.transform.translate = position;
        self
    }

    /// Set how the path's bounding box aligns onto the resolved anchor origin.
    pub fn with_align(mut self, align: Alignment) -> Self {
        self.anchoring.align = align;
        self
    }

    /// Resolve the screen-pixel offset added to every point for a frame: the
    /// origin, plus `position`, shifted by `anchoring.align` for the
    /// path's bounding box. Returns `None` when a `World` anchor projects behind
    /// the camera or off-screen (the path is skipped that frame). The default
    /// anchor with a zero `position` and `Left` / `Top` alignment resolves to
    /// `[0, 0]`, so absolute points are drawn unchanged.
    pub fn resolve_offset(
        &self,
        viewport_size: [f32; 2],
        view: &glam::Mat4,
        proj: &glam::Mat4,
    ) -> Option<[f32; 2]> {
        self.resolve_offset_at(viewport_size, view, proj, glam::DVec3::ZERO)
    }

    /// [`resolve_offset`](Self::resolve_offset) for a camera drawn relative
    /// to `world_origin`; see
    /// [`resolve_anchor_origin_at`](crate::overlay::resolve_anchor_origin_at).
    pub fn resolve_offset_at(
        &self,
        viewport_size: [f32; 2],
        view: &glam::Mat4,
        proj: &glam::Mat4,
        world_origin: glam::DVec3,
    ) -> Option<[f32; 2]> {
        let origin = crate::overlay::resolve_anchor_origin_at(
            &self.anchoring.origin,
            viewport_size,
            view,
            proj,
            world_origin,
        )?;
        let (mut min_x, mut min_y, mut max_x, mut max_y) = (0.0, 0.0, 0.0, 0.0);
        if let Some((first, rest)) = self.points.split_first() {
            min_x = first[0];
            min_y = first[1];
            max_x = first[0];
            max_y = first[1];
            for p in rest {
                min_x = min_x.min(p[0]);
                min_y = min_y.min(p[1]);
                max_x = max_x.max(p[0]);
                max_y = max_y.max(p[1]);
            }
        }
        Some([
            origin[0]
                + self.transform.translate[0]
                + self.anchoring.align.x.align_shift(max_x - min_x),
            origin[1]
                + self.transform.translate[1]
                + self.anchoring.align.y.align_shift(max_y - min_y, None),
        ])
    }

    /// Set the whole baked appearance at once: fill, shadow layers, backdrop,
    /// tint and opacity. The escape hatch for any cell without a dedicated
    /// builder.
    pub fn with_style(mut self, style: crate::overlay::OverlayStyle) -> Self {
        self.style = style;
        self
    }

    /// Set the stacked inner (inset) shadow layers, drawn over the item and
    /// eroding inward from its boundary.
    pub fn with_inner_shadows(mut self, shadows: Vec<crate::overlay::ShadowLayer>) -> Self {
        self.style.inner_shadows = shadows;
        self
    }

    /// Add one inner shadow layer, over any already set.
    pub fn with_inner_shadow(mut self, shadow: crate::overlay::ShadowLayer) -> Self {
        self.style.inner_shadows.push(shadow);
        self
    }

    /// Pin the item to a fixed screen position in logical pixels from the
    /// top-left. Sugar for the default viewport origin with `position` set to
    /// `pos`.
    pub fn with_screen_anchor(mut self, pos: [f32; 2]) -> Self {
        self.anchoring =
            crate::overlay::OverlayAnchoring::default().with_align(self.anchoring.align);
        self.transform.translate = pos;
        self
    }

    /// Set the whole stroke at once.
    pub fn with_stroke(mut self, stroke: OverlayStroke) -> Self {
        self.stroke = Some(stroke);
        self
    }

    /// Draw no line, leaving only the interior fill of a closed polyline.
    pub fn without_stroke(mut self) -> Self {
        self.stroke = None;
        self
    }

    /// The stroke, inserting the default one if the item currently has none, so
    /// a single-field setter can be called on a bare item.
    fn stroke_mut(&mut self) -> &mut OverlayStroke {
        self.stroke.get_or_insert_with(OverlayStroke::default)
    }

    /// Set a stroke width per point, in logical pixels. Must have one entry
    /// per point.
    pub fn with_widths(mut self, widths: Vec<f32>) -> Self {
        self.widths = Some(widths);
        self
    }

    /// Set the stroke width in logical pixels. `0.0` draws a one-device-pixel
    /// hairline.
    pub fn with_thickness(mut self, thickness: f32) -> Self {
        self.stroke_mut().width = thickness;
        self
    }

    /// Set the stroke colour.
    pub fn with_colour(mut self, colour: impl Into<crate::colour::Colour>) -> Self {
        self.stroke_mut().colour = colour.into();
        self
    }

    /// Set how segment joints are drawn.
    pub fn with_join(mut self, join: LineJoin) -> Self {
        self.stroke_mut().join = join;
        self
    }

    /// Set the mitre limit as a multiple of the stroke width before a mitre
    /// joint falls back to a bevel.
    pub fn with_mitre_limit(mut self, mitre_limit: f32) -> Self {
        self.stroke_mut().mitre_limit = mitre_limit;
        self
    }

    /// Set the end-cap style for open polylines and dash ends.
    pub fn with_cap(mut self, cap: LineCap) -> Self {
        self.stroke_mut().cap = cap;
        self
    }

    /// Set the stroke pattern (solid, dashed, or dotted).
    pub fn with_stroke_pattern(mut self, stroke_pattern: StrokePattern) -> Self {
        self.stroke_mut().pattern = stroke_pattern;
        self
    }

    /// Set whether the last point connects back to the first.
    pub fn with_closed(mut self, closed: bool) -> Self {
        self.closed = closed;
        self
    }

    /// Set the interior fill. Only used when the polyline is closed. The
    /// interior is taken under the non-zero rule, so an outline that touches or
    /// crosses itself fills like the same path in SVG.
    pub fn with_fill(mut self, fill: OverlayFill) -> Self {
        self.style.fill = fill;
        self
    }

    /// Set the interior texture fill. Only used when the polyline is closed.
    /// Replaces any colour or gradient fill: an item has one fill.
    pub fn with_texture(mut self, texture: OverlayTextureId) -> Self {
        self.style.fill = OverlayFill::texture(texture);
        self
    }

    /// Set per-point UVs for a textured interior. Must have one entry per point.
    pub fn with_uvs(mut self, uvs: Vec<[f32; 2]>) -> Self {
        self.uvs = Some(uvs);
        self
    }

    /// Set the overall opacity multiplier (0.0 to 1.0).
    pub fn with_opacity(mut self, opacity: f32) -> Self {
        self.style.opacity = opacity;
        self
    }

    /// Set how the item combines with what is drawn under it.
    pub fn with_blend(mut self, blend: crate::overlay::OverlayBlend) -> Self {
        self.style.blend = blend;
        self
    }

    /// Set the draw order. Lower values render first (further back).
    pub fn with_z_order(mut self, z_order: i32) -> Self {
        self.z_order = z_order;
        self
    }

    /// Clip the path to the mask shape with this id (registered via
    /// [`OverlayShapeItem::provides_mask`](crate::overlay::OverlayShapeItem::provides_mask)).
    /// Fragments outside the mask are discarded, so a path drawn inside a
    /// scrolling region is contained.
    pub fn with_clip(mut self, clip_id: u32) -> Self {
        self.clip.mask = Some(clip_id);
        self
    }

    /// Construct a polyline by sampling the given closure at `samples + 1`
    /// evenly-spaced parameter values across `[0, 1]`. The closure is called
    /// once per sample at construction time; the resulting points are stored
    /// in `self.points`.
    ///
    /// Consumers wanting non-uniform sample density (denser around tight
    /// curvature) should sample manually and build the item via the regular
    /// struct literal.
    pub fn from_path(
        path: impl Fn(f32) -> [f32; 2],
        samples: u32,
        thickness: f32,
        colour: impl Into<crate::colour::Colour>,
    ) -> Self {
        Self {
            points: sample_open_path(path, samples),
            stroke: Some(OverlayStroke::new(thickness, colour)),
            ..Default::default()
        }
    }

    /// Construct a closed, filled polygon by sampling `path` at `samples + 1`
    /// evenly-spaced values across `[0, 1)`. The last sample stops short of
    /// `t = 1` so the closing segment (last point back to the first) does not
    /// double up the start point.
    ///
    /// Sets `closed = true` and applies the given fill and stroke. Pass
    /// [`OverlayFill::none`] to draw the outline only.
    pub fn closed_from_path(
        path: impl Fn(f32) -> [f32; 2],
        samples: u32,
        fill: OverlayFill,
        stroke_colour: impl Into<crate::colour::Colour>,
        thickness: f32,
    ) -> Self {
        Self {
            points: sample_closed_path(path, samples),
            stroke: Some(OverlayStroke::new(thickness, stroke_colour)),
            closed: true,
            style: OverlayStyle {
                fill,
                ..Default::default()
            },
            ..Default::default()
        }
    }

    /// Replace `points` by resampling `path`. Honours the item's `closed`
    /// flag: closed items sample `[0, 1)` so the closing segment is not
    /// duplicated, open items sample `[0, 1]` inclusive.
    ///
    /// Call this during frame building to animate a function-generated path.
    /// Nothing else on the item changes, and no renderer state is cached, so
    /// the resampled points take effect on the next prepared frame.
    pub fn set_points_from_path(&mut self, path: impl Fn(f32) -> [f32; 2], samples: u32) {
        self.points = if self.closed {
            sample_closed_path(path, samples)
        } else {
            sample_open_path(path, samples)
        };
    }

    /// Set the stacked shadow layers drawn behind this item.
    pub fn with_shadows(mut self, shadows: Vec<crate::overlay::ShadowLayer>) -> Self {
        self.style.shadows = shadows;
        self
    }

    /// Add one shadow layer, in front of any already set.
    pub fn with_shadow(mut self, shadow: crate::overlay::ShadowLayer) -> Self {
        self.style.shadows.push(shadow);
        self
    }

    /// Add an outline: a band of `width` logical pixels on the item's edge,
    /// placed by `mode`. A width of `0.0` adds nothing.
    ///
    /// An outline is a shadow layer with no blur, so this pushes one (or two,
    /// for [`OutlineMode::Centre`]) onto the style's shadow lists, and costs a
    /// layer out of [`OVERLAY_MAX_SHADOW_LAYERS`] per list.
    ///
    /// [`OutlineMode::Centre`]: crate::overlay::OutlineMode::Centre
    /// [`OVERLAY_MAX_SHADOW_LAYERS`]: crate::overlay::OVERLAY_MAX_SHADOW_LAYERS
    pub fn with_outline(
        mut self,
        colour: impl Into<crate::colour::Colour>,
        width: f32,
        mode: crate::overlay::OutlineMode,
    ) -> Self {
        if width <= 0.0 {
            return self;
        }
        let colour = colour.into();
        let band = |spread: f32| {
            crate::overlay::ShadowLayer::new(colour, 0.0, [0.0, 0.0]).with_spread(spread)
        };
        match mode {
            crate::overlay::OutlineMode::Inset => self.style.inner_shadows.push(band(width)),
            crate::overlay::OutlineMode::Outer => self.style.shadows.push(band(width)),
            crate::overlay::OutlineMode::Centre => {
                self.style.inner_shadows.push(band(width * 0.5));
                self.style.shadows.push(band(width * 0.5));
            }
        }
        self
    }

    /// Set the transform: translate, rotate, scale, and pivot at once.
    pub fn with_transform(mut self, transform: OverlayTransform) -> Self {
        self.transform = transform;
        self
    }

    /// Set the rotation in radians about the pivot.
    ///
    /// The points are the caller's, so a consumer drawing immediately could
    /// always rotate them itself. Under retention it could not: the points are
    /// baked into the compiled buffer, and turning them means re-compiling.
    pub fn with_rotation(mut self, radians: f32) -> Self {
        self.transform.rotation = radians;
        self
    }

    /// Set the point to rotate and scale around, in logical pixels from the
    /// centre of the path's bounding box.
    pub fn with_rotation_pivot(mut self, pivot: [f32; 2]) -> Self {
        self.transform.pivot = pivot;
        self
    }

    /// Set the uniform scale about the transform pivot.
    pub fn with_scale(mut self, scale: f32) -> Self {
        self.transform.scale = scale;
        self
    }

    /// Set the per-frame colour multiplier (identity `[1, 1, 1, 1]`).
    pub fn with_tint(mut self, tint: [f32; 4]) -> Self {
        self.style.tint = tint;
        self
    }

    /// Set the animation tracks.
    pub fn with_animations(mut self, animations: OverlayAnimations) -> Self {
        self.animations = Some(Box::new(animations));
        self
    }

    /// Clip to an axis-aligned box in logical pixels `[x0, y0, x1, y1]`.
    pub fn with_clip_rect(mut self, clip_rect: [f32; 4]) -> Self {
        self.clip.rect = Some(clip_rect);
        self
    }
}

/// Sample `path` at `samples + 1` values across `[0, 1]` inclusive.
fn sample_open_path(path: impl Fn(f32) -> [f32; 2], samples: u32) -> Vec<[f32; 2]> {
    let n = samples.max(1);
    (0..=n).map(|i| path(i as f32 / n as f32)).collect()
}

/// Sample `path` at `samples + 1` values across `[0, 1)`. The final sample
/// lands at `samples / (samples + 1)`, so a closed polyline's wrap-around
/// segment does not repeat the start point.
fn sample_closed_path(path: impl Fn(f32) -> [f32; 2], samples: u32) -> Vec<[f32; 2]> {
    let n = samples.max(1);
    let divisor = (n + 1) as f32;
    (0..=n).map(|i| path(i as f32 / divisor)).collect()
}

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

    // A unit circle: path(0) == path(1), so an inclusive sample would repeat
    // the start point at the end.
    fn circle(t: f32) -> [f32; 2] {
        let a = t * std::f32::consts::TAU;
        [a.cos(), a.sin()]
    }

    #[test]
    fn from_path_samples_endpoint_inclusive() {
        let item = OverlayPolylineItem::from_path(circle, 4, 2.0, Colour::WHITE);
        // 5 points, first and last both at the t=0 position.
        assert_eq!(item.points.len(), 5);
        assert!((item.points[0][0] - item.points[4][0]).abs() < 1e-5);
        assert!((item.points[0][1] - item.points[4][1]).abs() < 1e-5);
    }

    #[test]
    fn closed_from_path_skips_duplicate_endpoint() {
        let fill = OverlayFill::Solid(Colour::linear(0.2, 0.4, 0.6, 1.0));
        let item =
            OverlayPolylineItem::closed_from_path(circle, 4, fill.clone(), Colour::WHITE, 3.0);
        assert!(item.closed);
        assert_eq!(item.style.fill, fill);
        assert_eq!(item.stroke.as_ref().unwrap().width, 3.0);
        // 5 points spanning [0, 1); the last is at 4/5, not back at the start.
        assert_eq!(item.points.len(), 5);
        assert!((item.points[0][0] - item.points[4][0]).abs() > 1e-3);
        let expected_last = circle(4.0 / 5.0);
        assert!((item.points[4][0] - expected_last[0]).abs() < 1e-5);
    }

    #[test]
    fn resolve_offset_default_is_zero() {
        // Default anchor + zero position + Left/Top align resolves to no offset,
        // so absolute points draw unchanged, with no camera needed.
        let p = OverlayPolylineItem::new(vec![[10.0, 20.0], [30.0, 40.0]]);
        let off = p
            .resolve_offset([800.0, 600.0], &glam::Mat4::IDENTITY, &glam::Mat4::IDENTITY)
            .unwrap();
        assert_eq!(off, [0.0, 0.0]);
    }

    #[test]
    fn resolve_offset_pins_bottom_right() {
        // A path spanning [0,0]..[40,20], anchored and aligned bottom-right, has
        // its bounding-box bottom-right corner pinned to the viewport corner.
        let p = OverlayPolylineItem::new(vec![[0.0, 0.0], [40.0, 20.0]])
            .with_anchor(OverlayOrigin::Viewport(Alignment::new(
                AnchorX::Right,
                AnchorY::Bottom,
            )))
            .with_align(Alignment::new(AnchorX::Right, AnchorY::Bottom));
        let off = p
            .resolve_offset([800.0, 600.0], &glam::Mat4::IDENTITY, &glam::Mat4::IDENTITY)
            .unwrap();
        // origin [800, 600], align shifts by -(width), -(height) = -40, -20.
        assert_eq!(off, [760.0, 580.0]);
    }

    #[test]
    fn set_points_from_path_follows_closed_flag() {
        let mut open = OverlayPolylineItem {
            closed: false,
            ..Default::default()
        };
        open.set_points_from_path(circle, 4);
        assert!((open.points[0][0] - open.points[4][0]).abs() < 1e-5);

        let mut closed = OverlayPolylineItem {
            closed: true,
            ..Default::default()
        };
        closed.set_points_from_path(circle, 4);
        assert!((closed.points[0][0] - closed.points[4][0]).abs() > 1e-3);
    }
}