Skip to main content

emblema_core/
canvas.rs

1//! The recording surface.
2//!
3//! A canvas is where drawing is expressed. It holds a transform stack and
4//! accumulates shapes into a batch, which is what a backend is eventually
5//! handed. Recording is separate from submitting so that a whole frame can be
6//! described before any of it reaches the GPU — that separation is what lets
7//! draws be batched into one pass rather than submitted one at a time.
8
9use crate::paint::{GradientStop, ImageFilter, MaskBlurStyle, Paint, Shader, Style};
10use crate::ramp::Ramp;
11use crate::vertices::{Sprite, VertexMode, Vertices};
12use crate::Color;
13use emblema_geometry::stroke::{LineCap, LineJoin, StrokeStyle};
14use emblema_geometry::transform::{
15    invert_to_local, max_scale, preserves_axis_alignment, to_local_columns, transformed_bounds,
16    unbounded, viewport_projection, Transform2D,
17};
18use emblema_geometry::{FillRule, Path, PathBuilder, Rect as GeometryRect};
19use emblema_hal::{
20    Batch, BlendMode, ClipState, ColorFilter, Error, Extent2D, Material, PassDescriptor,
21    PassViewport, Result, Sampling, Scissor, Stop, TileMode, Vertex, MAX_STOPS, MORPHOLOGY_TAPS,
22};
23use emblema_renderer::{Paint as RenderPaint, Renderer, TOLERANCE};
24use emblema_text::{Atlas, PositionedGlyph};
25use glam::{Affine2, Mat2, Vec2};
26
27/// A rectangle in user coordinates.
28#[derive(Debug, Clone, Copy, PartialEq)]
29pub struct Rect {
30    pub left: f32,
31    pub top: f32,
32    pub right: f32,
33    pub bottom: f32,
34}
35
36impl Rect {
37    pub fn new(left: f32, top: f32, right: f32, bottom: f32) -> Self {
38        Self {
39            left,
40            top,
41            right,
42            bottom,
43        }
44    }
45
46    pub fn from_size(width: f32, height: f32) -> Self {
47        Self::new(0.0, 0.0, width, height)
48    }
49
50    pub fn width(&self) -> f32 {
51        self.right - self.left
52    }
53
54    pub fn height(&self) -> f32 {
55        self.bottom - self.top
56    }
57
58    pub fn is_empty(&self) -> bool {
59        self.width() <= 0.0 || self.height() <= 0.0
60    }
61
62    /// The same rectangle, grown by `reach` on every side.
63    ///
64    /// What a blur needs from the bounds of what it blurs: the result spreads
65    /// outward, so a target sized to the content alone cuts the halo off square
66    /// at the edge -- the failure looking exactly like a shadow with a straight
67    /// side. Written once because it was written out twice, four lines at a
68    /// time, and a third place needs it with one side extended further.
69    pub fn outset(self, reach: f32) -> Self {
70        Self::new(
71            self.left - reach,
72            self.top - reach,
73            self.right + reach,
74            self.bottom + reach,
75        )
76    }
77
78    fn to_path(self) -> Path {
79        let mut b = PathBuilder::new();
80        b.move_to(Vec2::new(self.left, self.top))
81            .line_to(Vec2::new(self.right, self.top))
82            .line_to(Vec2::new(self.right, self.bottom))
83            .line_to(Vec2::new(self.left, self.bottom))
84            .close();
85        // A rectangle is a rounded one whose corners are not rounded, and
86        // recording it as such is what lets a blurred rectangle be evaluated
87        // rather than blurred. Not a special case in the expression that draws
88        // it: a corner radius of zero is where that approximation is at its
89        // most accurate, since there is no corner to approximate.
90        b.as_rounded_rect(
91            GeometryRect::new(
92                Vec2::new(self.left, self.top),
93                Vec2::new(self.right, self.bottom),
94            ),
95            0.0,
96        );
97        b.build()
98    }
99
100    /// This rectangle with its corners rounded to `radius`.
101    ///
102    /// The radius is clamped to half the shorter side. Larger is not an error
103    /// worth refusing -- a caller asking for a fully rounded end usually says
104    /// so by passing something enormous -- and left unclamped the corner arcs
105    /// would overlap and the outline would cross itself, which fills as
106    /// something nobody asked for. Clamped, the shape degenerates to a stadium
107    /// and then a circle, which is what asking for a huge radius means.
108    ///
109    /// A radius at or below zero gives the plain rectangle, so a caller can
110    /// pass a radius that happens to be zero without special-casing it.
111    pub fn to_rounded_path(self, radius: f32) -> Path {
112        if self.is_empty() {
113            return Path::default();
114        }
115        // NaN is checked before clamping rather than after, because `f32::min`
116        // ignores a NaN operand: clamping first turns it into half the shorter
117        // side, so arithmetic that went wrong would come back as a large
118        // rounded rectangle instead of as the plain one asked for.
119        //
120        // An infinite radius is not rejected with it. It clamps like any other
121        // large number, because a caller who writes one means the roundest
122        // shape available rather than none at all, and answering with a square
123        // would be the opposite of what was asked.
124        if radius.is_nan() || radius <= 0.0 {
125            return self.to_path();
126        }
127        let mut path = PathBuilder::new();
128        self.add_rounded_contour(&mut path, radius);
129        // Recorded beside the drawing rather than inferred later, so a route
130        // that wants the shape rather than the outline can have it -- a mask
131        // blur on this is evaluated in the fragment stage and needs a rect and
132        // a radius, which eight cubics cannot give back.
133        path.as_rounded_rect(
134            GeometryRect::new(
135                Vec2::new(self.left, self.top),
136                Vec2::new(self.right, self.bottom),
137            ),
138            radius.min(self.width() / 2.0).min(self.height() / 2.0),
139        );
140        path.build()
141    }
142
143    /// This rectangle with each corner rounded to its own pair of radii.
144    ///
145    /// The eight numbers `dart:ui`'s `RRect` carries, in upstream's order:
146    /// top-left, top-right, bottom-left, bottom-right, each an x radius and a
147    /// y radius. [`Self::to_rounded_path`] is this with all four the same and
148    /// circular, and goes through the same code.
149    pub fn to_rounded_path_with_radii(self, radii: RoundingRadii) -> Path {
150        if self.is_empty() {
151            return Path::default();
152        }
153        let radii = self.fitted_radii(radii);
154        if radii.iter().flatten().all(|v| *v <= 0.0) {
155            return self.to_path();
156        }
157        let mut path = PathBuilder::new();
158        self.add_rounded_contour_with_radii(&mut path, radii);
159        path.build()
160    }
161
162    /// Add this rectangle's rounded outline to a path already being built.
163    ///
164    /// [`Self::to_rounded_path_with_radii`] is this and nothing else when the
165    /// path holds one contour. It is public for the case that one cannot
166    /// serve: a shape made of two of these -- the ring `drawDRRect` fills, or a
167    /// caller's own compound outline -- needs both contours in one path, and a
168    /// path built from two paths is not something this crate offers.
169    ///
170    /// The radii are fitted on the way in, so a
171    /// caller passing radii that overrun a side gets the same scaling
172    /// `drawRRect` would apply rather than an outline that crosses itself.
173    pub fn add_rounded_outline(self, path: &mut PathBuilder, radii: RoundingRadii) {
174        if self.is_empty() {
175            return;
176        }
177        let radii = self.fitted_radii(radii);
178        self.add_rounded_contour_with_radii(path, radii);
179    }
180
181    /// The radii this rectangle can actually carry, made finite and made to fit.
182    ///
183    /// The fitting is `dart:ui`'s rule: find the edge whose two radii overrun
184    /// it worst, and scale *every* radius by that one ratio. Scaling only the
185    /// offending pair would also keep the outline from crossing itself, and
186    /// would change the shape's proportions -- the difference between a rounded
187    /// rectangle whose corners all got smaller and one that came back with a
188    /// lopsided pair nobody asked for.
189    ///
190    /// It is applied to the radii as given, which is the part that has to be
191    /// resisted tidying. Holding each radius to the side it runs along first
192    /// looks like a harmless guard and is not: it changes the ratios the rule
193    /// then works from, so a circular radius larger than the rectangle comes
194    /// back elliptical -- half the width across and half the height down,
195    /// instead of the round end the caller asked for.
196    ///
197    /// Which leaves the two values the rule cannot divide by. NaN and anything
198    /// at or below zero become zero, so a corner whose arithmetic went wrong is
199    /// square rather than enormous. An infinity becomes the longer side, which
200    /// is not arbitrary: once a uniform radius is large enough to bind, the
201    /// result stops depending on how large it was -- the ratio shrinks exactly
202    /// as fast as the radius grows -- so any sufficiently large stand-in gives
203    /// the same shape a huge finite radius gives, which is what an infinite one
204    /// has always meant here.
205    fn fitted_radii(self, radii: RoundingRadii) -> RoundingRadii {
206        let (w, h) = (self.width(), self.height());
207        let mut r = radii;
208        for corner in r.iter_mut() {
209            for value in corner.iter_mut() {
210                *value = if value.is_nan() || *value <= 0.0 {
211                    0.0
212                } else if value.is_infinite() {
213                    w.max(h)
214                } else {
215                    *value
216                };
217            }
218        }
219        let [tl, tr, bl, br] = r;
220        // Each edge against the two radii that meet along it. A sum of zero
221        // cannot bind, and is skipped rather than divided by.
222        let mut scale = 1.0f32;
223        for (side, sum) in [
224            (w, tl[0] + tr[0]),
225            (h, tr[1] + br[1]),
226            (w, bl[0] + br[0]),
227            (h, tl[1] + bl[1]),
228        ] {
229            if sum > side {
230                scale = scale.min(side / sum);
231            }
232        }
233        if scale < 1.0 {
234            for corner in r.iter_mut() {
235                for value in corner.iter_mut() {
236                    *value *= scale;
237                }
238            }
239        }
240        r
241    }
242
243    /// Append this rectangle's rounded outline to a builder, as one contour.
244    ///
245    /// Separate from [`Self::to_rounded_path`] because a shape made of two of
246    /// these -- a ring between an outer rectangle and an inner one -- needs
247    /// both in one path, and a path built from two paths is not something this
248    /// crate offers.
249    fn add_rounded_contour(self, path: &mut PathBuilder, radius: f32) {
250        let radii = self.fitted_radii([[radius; 2]; 4]);
251        self.add_rounded_contour_with_radii(path, radii);
252    }
253
254    /// The same, for radii that have already been fitted by `fitted_radii`.
255    fn add_rounded_contour_with_radii(self, path: &mut PathBuilder, radii: RoundingRadii) {
256        let [tl, tr, bl, br] = radii;
257        // The same constant that makes four cubics a circle. A corner here is a
258        // quarter *ellipse* rather than a quarter circle, and the constant
259        // carries over unchanged: an ellipse is a circle scaled along each axis
260        // independently, and scaling a cubic's control points by the same
261        // factors scales the curve they describe.
262        let k = |v: f32| KAPPA * v;
263        let (l, t, r, b) = (self.left, self.top, self.right, self.bottom);
264        path.move_to(Vec2::new(l + tl[0], t))
265            .line_to(Vec2::new(r - tr[0], t))
266            .cubic_to(
267                Vec2::new(r - tr[0] + k(tr[0]), t),
268                Vec2::new(r, t + tr[1] - k(tr[1])),
269                Vec2::new(r, t + tr[1]),
270            )
271            .line_to(Vec2::new(r, b - br[1]))
272            .cubic_to(
273                Vec2::new(r, b - br[1] + k(br[1])),
274                Vec2::new(r - br[0] + k(br[0]), b),
275                Vec2::new(r - br[0], b),
276            )
277            .line_to(Vec2::new(l + bl[0], b))
278            .cubic_to(
279                Vec2::new(l + bl[0] - k(bl[0]), b),
280                Vec2::new(l, b - bl[1] + k(bl[1])),
281                Vec2::new(l, b - bl[1]),
282            )
283            .line_to(Vec2::new(l, t + tl[1]))
284            .cubic_to(
285                Vec2::new(l, t + tl[1] - k(tl[1])),
286                Vec2::new(l + tl[0] - k(tl[0]), t),
287                Vec2::new(l + tl[0], t),
288            )
289            .close();
290    }
291}
292
293/// The single radius these corners all are, if they are all the same one.
294///
295/// `None` for anything the fragment-evaluated route cannot describe: a corner
296/// that differs from another, or one whose two radii differ from each other.
297fn uniform_circular_radius(radii: RoundingRadii) -> Option<f32> {
298    let radius = radii[0][0];
299    radii
300        .iter()
301        .flatten()
302        .all(|v| *v == radius)
303        .then_some(radius)
304}
305
306/// A rounded rectangle's four corners, each with an x and a y radius.
307///
308/// In upstream's order -- top-left, top-right, bottom-left, bottom-right --
309/// rather than in the order the outline is traced, so that a caller porting
310/// from `RoundingRadii` or from `dart:ui`'s `RRect` can copy the four across
311/// without reordering them. The tracing order is the contour's business.
312pub type RoundingRadii = [[f32; 2]; 4];
313
314/// The outline of a rounded superellipse in `rect` with the given radii.
315///
316/// Here rather than on `Rect` beside `to_rounded_path_with_radii`, because a
317/// superellipse is not a rounded rectangle with a different corner and putting
318/// it there would suggest the two are interchangeable. They take the same four
319/// numbers and draw measurably different shapes.
320fn rsuperellipse_path(rect: Rect, radii: RoundingRadii) -> Path {
321    use emblema_geometry::superellipse::{CornerRadii, RoundSuperellipse};
322    let bounds = GeometryRect::new(
323        Vec2::new(rect.left, rect.top),
324        Vec2::new(rect.right, rect.bottom),
325    );
326    RoundSuperellipse::new(
327        bounds,
328        CornerRadii {
329            top_left: Vec2::new(radii[0][0], radii[0][1]),
330            top_right: Vec2::new(radii[1][0], radii[1][1]),
331            bottom_left: Vec2::new(radii[2][0], radii[2][1]),
332            bottom_right: Vec2::new(radii[3][0], radii[3][1]),
333        },
334    )
335    .to_path()
336}
337
338/// Where a pass's texture slot gets its content.
339///
340/// A recording is produced without touching a device, so it can name neither a
341/// texture nor an allocation. It names either an image the caller will supply
342/// or an earlier pass in the same recording, and whoever executes it resolves
343/// both.
344#[derive(Debug, Clone, Copy, PartialEq, Eq)]
345pub enum TextureSource {
346    /// The caller's image at this index in the table given at draw time.
347    Image(u32),
348    /// The output of the pass at this index in [`Recording::passes`].
349    Layer(usize),
350    /// The baked gradient at this index in [`Recording::ramps`].
351    ///
352    /// Unlike the other two this names something the recorder made rather than
353    /// something it was given or rendered, so it is uploaded at submission and
354    /// discarded with the frame.
355    Ramp(usize),
356}
357
358/// One target's worth of drawing.
359///
360/// Cloneable so that a finished recording can be drawn into another one: the
361/// passes are taken as they are, and the recording being drawn keeps its own
362/// copy for a caller who draws it more than once.
363#[derive(Clone)]
364pub struct Pass {
365    pub batch: Batch,
366    pub descriptor: PassDescriptor,
367    /// What each texture slot this pass samples refers to, in slot order.
368    pub sources: Vec<TextureSource>,
369    /// The size of the target this pass renders into.
370    ///
371    /// Per pass rather than per recording, because a layer given bounds
372    /// renders into a target the size of those bounds. The root pass always
373    /// carries the recording's extent, since that is the caller's surface.
374    pub extent: Extent2D,
375}
376
377/// How a run of points is joined up.
378#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
379pub enum PointMode {
380    /// Each point on its own, drawn as the stroke's cap.
381    #[default]
382    Points,
383    /// Each pair a segment, and an odd point at the end drawn as nothing.
384    Lines,
385    /// One open run through all of them.
386    Polygon,
387}
388
389/// A finished recording, ready to submit.
390///
391/// More than one pass where the recording used layers. A layer is drawn into a
392/// target of its own and then composited back, which cannot happen in the same
393/// pass that samples it: reading an attachment being written needs machinery
394/// this does not have, and the separation is what makes group opacity mean
395/// "make this subtree, then fade it" rather than "fade each shape in it".
396pub struct Recording {
397    /// Layers first, each before whatever samples it; the root target last.
398    ///
399    /// The order falls out of how they are recorded rather than being sorted:
400    /// a layer is finished when it is restored, which is necessarily before the
401    /// draw that composites it.
402    pub passes: Vec<Pass>,
403    /// The size of the caller's surface, which is what the root pass renders
404    /// at. A layer pass may be smaller; see [`Pass::extent`].
405    pub extent: Extent2D,
406    /// Gradients whose colors were too many to carry in a material, tabulated.
407    ///
408    /// Recorded here rather than per pass because a slot table is per pass and
409    /// this is not: the same gradient drawn into a layer and again over it is
410    /// one ramp named twice.
411    pub ramps: Vec<Ramp>,
412}
413
414impl Recording {
415    pub fn draw_count(&self) -> usize {
416        self.passes.iter().map(|p| p.batch.draw_count()).sum()
417    }
418
419    pub fn is_empty(&self) -> bool {
420        self.passes.iter().all(|p| p.batch.is_empty())
421    }
422
423    /// The pass drawn into the caller's surface.
424    pub fn root(&self) -> &Pass {
425        self.passes.last().expect("a recording always has a root")
426    }
427
428    /// How many offscreen targets executing this needs.
429    pub fn layer_count(&self) -> usize {
430        self.passes.len() - 1
431    }
432}
433
434/// The target a pass renders into, placed within the frame.
435///
436/// A layer with bounds renders into a target the size of those bounds rather
437/// than the size of the frame, which is most of the point of giving bounds: a
438/// layer covering a tenth of the frame costs a tenth of the memory and a tenth
439/// of the fill. Everything that turns a device position into a clip position
440/// has to know where that target sits, which is what `origin` carries.
441#[derive(Debug, Clone, Copy, PartialEq)]
442struct Target {
443    /// Where this target's top-left corner sits in the frame, in device pixels.
444    /// Whole pixels, so that the composite samples texel centers exactly.
445    origin: Vec2,
446    extent: Extent2D,
447}
448
449impl Target {
450    fn frame(extent: Extent2D) -> Self {
451        Self {
452            origin: Vec2::ZERO,
453            extent,
454        }
455    }
456
457    /// Device position to clip position for this target.
458    ///
459    /// Affine, and stays so: a viewport is a scale, a flip and an offset. It is
460    /// lifted here because everything it composes with may not be.
461    fn projection(&self) -> Transform2D {
462        (viewport_projection(self.extent.width, self.extent.height)
463            * Affine2::from_translation(-self.origin))
464        .into()
465    }
466
467    /// The whole target, in the device space the projection expects.
468    fn path(&self) -> Path {
469        Rect::new(
470            self.origin.x,
471            self.origin.y,
472            self.origin.x + self.extent.width as f32,
473            self.origin.y + self.extent.height as f32,
474        )
475        .to_path()
476    }
477}
478
479/// One stencil clip in force, kept so it can be made again.
480///
481/// A stencil clip is a *draw*: it steps the stencil forward where the shape
482/// covers, and every content draw after it tests against what that draw left.
483/// A pass cut starts a new pass, whose stencil attachment begins cleared -- so
484/// unless the narrowing draws are made again, every draw after the cut tests a
485/// buffer nothing wrote and lands nowhere.
486///
487/// Kept as the shape rather than as the draw, because the shape is what
488/// `clip_path` needs to make one and the draw lives in a batch that the cut has
489/// already taken away.
490#[derive(Debug, Clone)]
491struct StencilClip {
492    path: Path,
493    /// The transform the shape was stated in. `clip_out_rect` builds its
494    /// contours in device pixels and passes the identity; `clip_path` passes
495    /// whatever was in force.
496    transform: Transform2D,
497    /// The scissor in force when it was made, which narrows the narrowing.
498    scissor: Option<Scissor>,
499}
500
501/// Transform and clip, saved together.
502///
503/// One stack rather than two: a `save` and its `restore` bracket a subtree, and
504/// letting the two pieces of state unwind independently would mean a caller
505/// could balance one while leaving the other adrift.
506#[derive(Debug)]
507struct SavedState {
508    transform: Transform2D,
509    clip: Option<Scissor>,
510    clip_bounds: Rect,
511    depth: u32,
512    /// How many stencil clips were in force, so `restore` can drop the ones
513    /// this save added. Redundant with `depth` and kept beside it for the same
514    /// reason the bounds are kept beside the scissor: one of them is the truth
515    /// the device holds and the other is what would be needed to rebuild it.
516    clips: usize,
517    /// Set where this save opened a layer, holding what the layer displaced.
518    layer: Option<LayerFrame>,
519}
520
521/// A layer in progress: the parent's recording, set aside until it returns.
522#[derive(Debug)]
523struct LayerFrame {
524    batch: Batch,
525    sources: Vec<TextureSource>,
526    /// The stencil clips in force on the parent, set aside with its batch.
527    ///
528    /// A layer starts unclipped -- the composite that returns it is subject to
529    /// the parent's clip instead -- so it needs a list of its own, and the
530    /// parent's has to come back when it does. Held here rather than as a
531    /// length in `SavedState`, because unlike every other save this one does
532    /// not *extend* the list it found.
533    clips: Vec<StencilClip>,
534    paint: Layer,
535    /// An image filter to run over the finished layer, if one was asked for.
536    ///
537    /// Beside the layer rather than inside it, because [`Layer`] is `Copy` and
538    /// small and is copied at every `save_layer`, while a filter can hold a
539    /// composition or a program's sixty-four uniform floats. The fields on the
540    /// layer cover the four kinds that fit in one; this covers the rest, and
541    /// the two orders a composition can take.
542    filter: Option<ImageFilter>,
543    /// The target the parent was drawing into, restored when the layer closes.
544    parent: Target,
545    /// Whether the parent's own batch had asked for antialiasing yet.
546    ///
547    /// Displaced with the batch and for the same reason: the sample count
548    /// describes a pass, and a layer's draws belong to the layer's pass. A
549    /// parent that has drawn nothing needing multisampling does not start
550    /// needing it because something inside a layer did.
551    anti_alias: bool,
552    /// Whether the parent's batch began by redrawing the whole target.
553    ///
554    /// Displaced with the batch, like `anti_alias` and for the same reason: a
555    /// layer's own batch starts empty and is seeded by nothing, while the parent's
556    /// may have been cut before the layer opened.
557    seeded_by_redraw: bool,
558    /// The directions this layer's blur runs along.
559    ///
560    /// Taken from the transform in force when the layer opened, for the same
561    /// reason its sigma is: the transform that decides them may be gone by the
562    /// time the layer is composited, and both halves of a blur -- how far it
563    /// reaches and which way -- have to be settled together or a target is
564    /// sized for one blur and filled by another.
565    blur_basis: BlurBasis,
566}
567
568/// The two directions a blur runs along, in device pixels.
569///
570/// A blur is two separable passes, and which directions they take is the whole
571/// of the difference between a blur that turns with the caller's transform and
572/// one that does not. `dart:ui` states a deviation per axis in the space the
573/// caller was drawing in; if that space is turned relative to the target, the
574/// passes have to turn with it or a horizontal smear stays horizontal on
575/// screen while the thing it is smearing rotates underneath.
576///
577/// **This is not how upstream does it, and the difference is worth stating.**
578/// `GaussianBlurFilterContents` removes the rotation instead: it re-renders its
579/// input into what its own comment calls "un-rotated local space", scaled by
580/// the transform but not turned by it, blurs along that space's own axes, and
581/// applies the rotation to the *result*. Its reason is quality rather than
582/// correctness -- the comment says the un-rotated space "is a requirement for
583/// text to be rendered correctly", because taps landing on texel centers is
584/// what keeps a glyph sharp.
585///
586/// That arrangement is not available here. A layer is a recorded pass with a
587/// device-space target, a device-space scissor and a stencil buffer to match,
588/// so its content cannot be drawn into a space of its own choosing after the
589/// fact. What *is* available is the pass's `step`, which was already a free
590/// two-vector rather than an axis flag -- the shader walks its taps along
591/// whatever direction it is given. So the passes turn instead of the space.
592///
593/// The two are the same Gaussian. A blur with deviations along orthogonal
594/// directions is separable along exactly those directions, so the picture is
595/// upstream's; what differs is that a tap here lands between texels and is
596/// resolved by the sampler, which costs a little sharpness that upstream's
597/// arrangement does not.
598#[derive(Debug, Clone, Copy, PartialEq)]
599struct BlurBasis {
600    /// Unit vectors in device space, in the order the deviations are stated.
601    directions: [Vec2; 2],
602}
603
604impl BlurBasis {
605    /// The target's own axes, which is what every blur used before this and
606    /// what a transform this cannot decompose still gets.
607    const AXES: Self = Self {
608        directions: [Vec2::X, Vec2::Y],
609    };
610
611    /// Where the caller's axes point once the transform has been applied.
612    ///
613    /// Refused rather than approximated in two cases. A transform with
614    /// perspective has no single basis -- the directions would differ per
615    /// fragment, which a pass walking a constant step cannot express. And a
616    /// transform whose image axes are not perpendicular, which is a shear,
617    /// leaves a Gaussian that two separable passes cannot state at all:
618    /// separability is a property of orthogonal directions, and running the
619    /// passes along oblique ones would not be a wrong blur so much as not a
620    /// blur. Upstream is no better off here -- its `ExtractScale` takes the
621    /// lengths of the image axes and drops the shear entirely.
622    fn of(transform: Transform2D) -> Self {
623        let Some(affine) = transform.to_affine() else {
624            return Self::AXES;
625        };
626        let (x, y) = (affine.matrix2.x_axis, affine.matrix2.y_axis);
627        let (lx, ly) = (x.length(), y.length());
628        if !lx.is_finite() || !ly.is_finite() || lx <= 0.0 || ly <= 0.0 {
629            return Self::AXES;
630        }
631        let directions = [x / lx, y / ly];
632        // The cosine of the angle between them, both being unit vectors. A
633        // thousandth is well inside what a rotation composed with a scale
634        // produces and well outside anything a shear does.
635        if directions[0].dot(directions[1]).abs() > 1e-3 {
636            return Self::AXES;
637        }
638        Self { directions }
639    }
640
641    /// Whether these are the target's own axes, which several things below can
642    /// take shortcuts for.
643    fn is_axis_aligned(&self) -> bool {
644        *self == Self::AXES
645    }
646
647    /// How far past its content a blur along these directions carries, as an
648    /// outset on each of the target's axes.
649    ///
650    /// The bounding box of the two reaches laid along the two directions,
651    /// which for the target's own axes is the pair of reaches unchanged.
652    fn reach(&self, sigma: Vec2) -> Vec2 {
653        self.box_of(Vec2::new(blur_reach(sigma.x), blur_reach(sigma.y)))
654    }
655
656    /// The target-axis bounding box of two distances laid along these directions.
657    ///
658    /// Shared with the morphology reach rather than written twice, because the
659    /// two have to agree with the passes to the pixel: a pass walks `u` and `v`
660    /// and whatever room is reserved has to contain where that walk ends. It was
661    /// written twice for a while, and the morphology copy did not turn -- so a
662    /// rotated dilation ran along the caller's axes and was clipped by an outset
663    /// laid along the target's.
664    fn box_of(&self, along: Vec2) -> Vec2 {
665        let [u, v] = self.directions;
666        Vec2::new(
667            u.x.abs() * along.x + v.x.abs() * along.y,
668            u.y.abs() * along.x + v.y.abs() * along.y,
669        )
670    }
671}
672
673/// Spreading or shrinking a finished layer, one axis at a time.
674///
675/// The pair `dart:ui` calls `ImageFilter.dilate` and `ImageFilter.erode`: each
676/// output pixel takes the largest, or the smallest, of the input within a
677/// rectangle around it. The rectangle is why the radii are per axis and why the
678/// filter is separable at all.
679#[derive(Debug, Clone, Copy, PartialEq)]
680pub struct Morphology {
681    /// How far the structuring element reaches along each axis, in device
682    /// pixels.
683    pub radius: [f32; 2],
684    /// Take the largest sample in reach rather than the smallest.
685    pub dilate: bool,
686}
687
688impl Morphology {
689    /// Spread the layer: each pixel becomes the largest within the radii.
690    pub fn dilate(x: f32, y: f32) -> Self {
691        Self {
692            radius: Self::sane(x, y),
693            dilate: true,
694        }
695    }
696
697    /// Shrink the layer: each pixel becomes the smallest within the radii.
698    pub fn erode(x: f32, y: f32) -> Self {
699        Self {
700            radius: Self::sane(x, y),
701            dilate: false,
702        }
703    }
704
705    /// Not negative, and finite.
706    ///
707    /// No longer rounded here, and the reason is the whole of the change that
708    /// made the radius a local length. A structuring element is a set of sample
709    /// positions and there is no half of one to keep -- but the positions are
710    /// *device* texels, and this runs on the caller's number before any
711    /// transform has been applied to it. Rounding a local length rounds the
712    /// wrong quantity: at a scale of three, a radius of 1.5 rounded here becomes
713    /// two and then six, where the sample positions it is naming are four and a
714    /// half. `applied_radius` rounds instead, where the device radius is known.
715    fn sane(x: f32, y: f32) -> [f32; 2] {
716        let one = |v: f32| if v.is_finite() { v.max(0.0) } else { 0.0 };
717        [one(x), one(y)]
718    }
719
720    /// Whether this would leave every pixel where it was.
721    pub fn is_identity(&self) -> bool {
722        self.radius == [0.0, 0.0]
723    }
724
725    /// The radius worth applying on a target this size, per axis.
726    ///
727    /// A window reaching `extent` texels along an axis already spans the whole
728    /// of it, so every output pixel is the extreme over the entire row or
729    /// column and a wider one cannot change a single pixel. Dilating takes the
730    /// largest sample and eroding the smallest; either way the taps a larger
731    /// radius adds are all outside the image, and whatever the sampler returns
732    /// there is already in the window. So this clamp is picture-preserving
733    /// rather than a limit on the filter, which is what makes it safe to apply
734    /// without the caller having asked.
735    ///
736    /// **Why it has to exist.** `sane` bounds the radius below and
737    /// rejects what is not finite, and nothing bounded it above -- so the pass
738    /// loop, which emits one pass per [`MORPHOLOGY_TAPS`] texels, turned a
739    /// caller's float into that many passes. A radius of a million asked for
740    /// sixty-two thousand of them and a radius of `1e20` exhausted memory,
741    /// through the documented constructor and with no unsafe input anywhere:
742    /// the value is finite, positive and whole. That is a recording's size made
743    /// proportional to a scalar, which is the defect this closes.
744    ///
745    /// Non-finite gives zero, on the same terms as `sane` and for the same
746    /// reason a non-finite sigma gives no blur. Checked before the `min` rather
747    /// than after, because [`f32::min`] returns the other operand when one side
748    /// is NaN -- the trap `Layer::with_blur_xy` and `Rect::outset` both name,
749    /// and the one that would turn a NaN radius into a full-width dilation.
750    /// It also has to be handled here rather than left to the loop: the loop's
751    /// condition is false for NaN, so NaN was already harmless, but infinity
752    /// entered it and never left, since subtracting the taps from infinity
753    /// leaves infinity.
754    pub fn applied_radius(&self, extent: Extent2D) -> [f32; 2] {
755        let one = |radius: f32, along: u32| {
756            if radius.is_finite() {
757                // Rounded here rather than at construction, because this is the
758                // first point at which the number is in device texels: the
759                // caller states a local length and `Layer::scaled_by` converts
760                // it. A structuring element is a set of sample positions and
761                // there is no half of one, so the rounding still happens -- just
762                // where the positions are.
763                radius.max(0.0).min(along as f32).round()
764            } else {
765                0.0
766            }
767        };
768        [
769            one(self.radius[0], extent.width),
770            one(self.radius[1], extent.height),
771        ]
772    }
773}
774
775/// What a mask blur is blurring: a shape, or a run of glyphs.
776///
777/// An enum rather than a closure because every style draws its content two or
778/// three times and a closure taking `&mut Canvas` cannot be called twice while
779/// the canvas is borrowed. Two variants is also the whole set: a mask blur
780/// needs the content's coverage times one solid color, which a mesh's per-vertex
781/// colors rule out and an image's texels rule out.
782#[derive(Clone, Copy)]
783enum Masked<'a> {
784    Path(&'a Path),
785    /// A mesh carrying no per-vertex colors, so the paint supplies the color
786    /// the way it does for a path. One that carries them is refused before it
787    /// reaches here: see `draw_vertices`.
788    Mesh(&'a Vertices),
789    Glyphs {
790        glyphs: &'a [PositionedGlyph],
791        atlas: &'a Atlas,
792        slot: u32,
793    },
794}
795
796/// How a layer is composited back onto what was underneath it.
797///
798/// A separate type from [`Paint`] rather than a reuse of it, because only two
799/// of a paint's parts mean anything here — there is no shape to fill and no
800/// geometry to stroke — and a caller handed a `Paint` would reasonably expect
801/// its shader to matter.
802#[derive(Debug, Clone, Copy, PartialEq)]
803pub struct Layer {
804    /// Blur the group before compositing it, with this standard deviation per
805    /// axis in device pixels.
806    ///
807    /// Zero on both for no blur, which is the default and costs nothing: the
808    /// extra passes are only recorded where a caller asked for one, and an
809    /// axis whose deviation is zero costs no pass of its own.
810    ///
811    /// Two deviations rather than one because `dart:ui`'s `ImageFilter.blur`
812    /// states `sigmaX` and `sigmaY` separately, and because the blur is two
813    /// separable passes here regardless -- so the second is a field rather
814    /// than a mechanism. [`Self::with_blur`] sets both.
815    ///
816    /// On the group rather than on a paint, because a blur is a function of a
817    /// finished image and a paint describes one shape. Blurring each shape and
818    /// compositing the results is a different picture from blurring the
819    /// composite, and the second is what a shadow or a frosted panel means.
820    pub blur: Vec2,
821    /// Scales the whole layer on the way back. This is what makes group opacity
822    /// differ from per-shape opacity: two overlapping half-transparent shapes
823    /// in a layer show one blended edge, where the same shapes drawn directly
824    /// show where they cross.
825    pub alpha: f32,
826    /// How the finished layer meets what was underneath it.
827    pub blend: BlendMode,
828    /// Transform the finished layer on the way back, in device pixels.
829    ///
830    /// Distinct from transforming what goes into it, which the canvas's own
831    /// transform already does. This resamples the finished image: magnifying
832    /// through it gives the layer's own pixels enlarged, where drawing the
833    /// same shapes under a larger transform would give them redrawn at the
834    /// larger size. That difference is the whole of what a matrix image filter
835    /// means -- a caller wanting the sharp one already has the transform
836    /// stack.
837    ///
838    /// It resamples what the layer *captured*, and a layer captures no more
839    /// than its target holds. So a matrix moves an image and cannot recover
840    /// what fell outside the layer to begin with: a shape drawn past the edge
841    /// of the frame is gone before this runs, where upstream sizes the layer
842    /// through the filter and brings it back. `docs/non-parity.md` §12 has the
843    /// case and what fixing it would cost.
844    ///
845    /// `None` composites the layer where it was drawn, which is what every
846    /// layer did before this existed.
847    pub matrix: Option<Transform2D>,
848    /// Blur what is already on the target before the layer draws over it.
849    ///
850    /// This is the other blur, and the difference is which image is filtered.
851    /// [`Self::blur`] softens the layer's own content, which is what a shadow
852    /// is. This softens what is *behind* it and hands the result to the layer
853    /// as its starting content, which is what frosted glass is: a panel that
854    /// obscures rather than one that is itself indistinct.
855    ///
856    /// Zero for none, and it costs nothing when zero. When it is not zero it
857    /// costs a copy of the target and two blur passes over it, because reading
858    /// what a pass is writing is not something this renderer can do -- see the
859    /// architecture note on cutting a pass.
860    ///
861    /// # Bounds stop being an optimization
862    ///
863    /// For every other layer, [`Canvas::save_layer_bounds`] only says where the
864    /// content is, and the picture is the same either way. For this one the
865    /// bounds are the region that gets filtered: a frosted panel is a bounded
866    /// layer, and the same layer without bounds blurs the whole frame and
867    /// composites the whole frame back. Both are meaningful and they are
868    /// different pictures, so state the bounds when you mean a panel.
869    pub backdrop_blur: f32,
870    /// Which captured backdrop this layer filters, if it shares one.
871    ///
872    /// `dart:ui`'s `pushBackdropFilter` takes a `backdropId` and says what it
873    /// means: "when the first backdrop filter with a given id is processed
874    /// during rasterization, the state of the backdrop is recorded and cached.
875    /// All subsequent backdrop filters with the same identifier will apply
876    /// their filter to the cached backdrop." So it is a different picture, not
877    /// only a faster one -- overlapping panels sharing an id each filter what
878    /// was behind all of them, rather than each filtering the one before it.
879    ///
880    /// That is the case it exists for. A list of frosted rows over one
881    /// background wants each row to show the background, and without the id
882    /// the second row shows the first row's blur blurred again. With it, the
883    /// capture happens once and each row filters it: the picture the caller
884    /// meant, and one pass cut instead of one per row.
885    ///
886    /// An id keys a captured image and nothing more. A layer naming one from
887    /// inside another layer still filters what the id captured rather than its
888    /// own target's content, which is upstream's reading and is the point of
889    /// the case it tests with each panel wrapped in a save layer of its own.
890    ///
891    /// `None` captures afresh, which is what every layer did before this
892    /// existed and is right whenever the backdrops genuinely differ.
893    pub backdrop_id: Option<i64>,
894    /// Spread or shrink the group before compositing it. See [`Morphology`].
895    ///
896    /// On the group for the same reason [`Self::blur`] is: a maximum over a
897    /// window is a function of a finished image. Dilating each shape and then
898    /// compositing is a different picture from dilating the composite wherever
899    /// two shapes overlap.
900    ///
901    /// `None` for no morphology, which is the default and costs nothing.
902    pub morphology: Option<Morphology>,
903    /// Recolor the finished group on its way back.
904    ///
905    /// What `dart:ui` means by the `colorFilter` on the paint `saveLayer`
906    /// takes, and the same distinction group opacity has: filtering each shape
907    /// and compositing the results differs from filtering the composite
908    /// wherever two of them overlap, because a filter is not linear in general.
909    ///
910    /// It is also the only way to filter what a caller's own fragment program
911    /// drew. A runtime effect is a whole pipeline rather than a material this
912    /// renderer's shader evaluates, so there is nowhere in it to apply a
913    /// matrix -- the filter has to act on the image the program produced.
914    pub color_filter: ColorFilter,
915}
916
917impl Default for Layer {
918    fn default() -> Self {
919        Self {
920            blur: Vec2::ZERO,
921            alpha: 1.0,
922            blend: BlendMode::SrcOver,
923            matrix: None,
924            backdrop_blur: 0.0,
925            backdrop_id: None,
926            morphology: None,
927            color_filter: ColorFilter::None,
928        }
929    }
930}
931
932impl Layer {
933    /// Transform the finished layer on the way back. See [`Self::matrix`].
934    ///
935    /// Takes an affine or a projective transform, the same as `concat`. A layer
936    /// moved by one of these is a finished image being placed, so perspective
937    /// here gives the image seen at an angle rather than the content redrawn at
938    /// one -- which is the whole distinction this filter exists to make, and it
939    /// survives the widening unchanged.
940    pub fn with_matrix(mut self, matrix: impl Into<Transform2D>) -> Self {
941        self.matrix = Some(matrix.into());
942        self
943    }
944
945    pub fn opacity(alpha: f32) -> Self {
946        Self {
947            alpha,
948            ..Self::default()
949        }
950    }
951
952    pub fn with_blend(mut self, blend: BlendMode) -> Self {
953        self.blend = blend;
954        self
955    }
956
957    /// Recolor the finished group on its way back. See [`Self::color_filter`].
958    pub fn with_color_filter(mut self, filter: ColorFilter) -> Self {
959        self.color_filter = filter;
960        self
961    }
962
963    /// Spread or shrink the finished group. See [`Morphology`].
964    ///
965    /// A morphology that would move nothing becomes `None`, on the same
966    /// reasoning as a blur of zero: a caller animating a radius down to nothing
967    /// should get the unfiltered thing at the end, not two passes that copy the
968    /// image twice to say so.
969    pub fn with_morphology(mut self, morphology: Morphology) -> Self {
970        self.morphology = if morphology.is_identity() {
971            None
972        } else {
973            Some(morphology)
974        };
975        self
976    }
977
978    /// How far past the content this layer's filters reach, per axis, in device
979    /// pixels.
980    ///
981    /// A blur carries color outward and so does a dilation; an erosion only
982    /// eats inward and needs no room. The two can be asked for together, so
983    /// this is their sum rather than whichever is larger -- the passes run one
984    /// after the other, and the second reaches out from where the first put
985    /// things.
986    /// The same layer with its lengths converted into device pixels.
987    ///
988    /// A sigma reaches the caller in the space they were drawing in and every
989    /// pass that acts on it works on a target, so one of the two has to move.
990    /// This is that move, and it happens once at `save_layer` rather than at
991    /// each use -- the transform that decides it is the one in force when the
992    /// layer is opened, and it may be gone by the time the layer is composited.
993    ///
994    /// **Every length stated per axis takes the axis factors, and the one stated
995    /// as a single number is converted elsewhere.** A blur's deviations and a
996    /// morphology's radii are pairs, and each component takes the length of its
997    /// own transformed basis vector -- which is what upstream's `ExtractScale`
998    /// and `TransformDirection` take.
999    ///
1000    /// `backdrop_blur` is deliberately *not* converted here, and the reason is
1001    /// that it cannot be. It is one number, so a caller states a blur that is
1002    /// round in their own space -- and a round blur under an anisotropic scale is
1003    /// an oval in device space, which one number cannot hold. Multiplying it by a
1004    /// single factor here is what used to happen and is what made a frosted panel
1005    /// stay round under `scale(2, 3)` while the same deviations on the layer
1006    /// itself stretched. So the field stays in the caller's space and
1007    /// `open_layer` converts it per axis at the point it becomes an
1008    /// `ImageFilter::Blur`, which has two components to put the answer in.
1009    ///
1010    /// Nothing between here and there reads it as a length: the two other uses
1011    /// are `> 0.0` tests asking whether a backdrop is wanted at all.
1012    fn scaled_by(self, scale: f32, axes: Vec2) -> Self {
1013        if !scale.is_finite() || scale <= 0.0 {
1014            return self;
1015        }
1016        Self {
1017            blur: self.blur * axes,
1018            backdrop_blur: self.backdrop_blur,
1019            // A morphology radius is a length in the caller's space too, and was
1020            // the one filter left out of this conversion -- on the stated
1021            // grounds that upstream had no morphology to be in parity with,
1022            // which was wrong. See `non-parity.md` 17.
1023            morphology: self.morphology.map(|m| Morphology {
1024                radius: [m.radius[0] * axes.x, m.radius[1] * axes.y],
1025                ..m
1026            }),
1027            ..self
1028        }
1029    }
1030
1031    fn reach(&self, basis: BlurBasis) -> Vec2 {
1032        let blur = basis.reach(self.blur);
1033        match self.morphology {
1034            // Turned with the same basis the passes walk. An axis-aligned outset
1035            // would be the right box only while the directions are the axes, and
1036            // a rotated dilation would lose its corners to the scissor.
1037            Some(m) if m.dilate => blur + basis.box_of(Vec2::new(m.radius[0], m.radius[1])),
1038            _ => blur,
1039        }
1040    }
1041
1042    /// Blur the finished group, with `sigma` in device pixels.
1043    ///
1044    /// Anything at or below zero, or not a number, means no blur rather than an
1045    /// error: a caller animating a shadow's softness to nothing should get the
1046    /// sharp thing, not a refusal at the end of the animation.
1047    /// Blur the backdrop this layer is drawn over.
1048    ///
1049    /// Ignored unless finite and positive, on the same terms as
1050    /// [`Self::with_blur`]: a sigma that is not a length describes no blur.
1051    pub fn with_backdrop_blur(mut self, sigma: f32) -> Self {
1052        self.backdrop_blur = if sigma.is_finite() && sigma > 0.0 {
1053            sigma
1054        } else {
1055            0.0
1056        };
1057        self
1058    }
1059
1060    /// Share one captured backdrop with every layer naming the same `id`.
1061    ///
1062    /// See [`Self::backdrop_id`] for what is shared and why it changes the
1063    /// picture rather than only the cost. The id is the caller's, and means
1064    /// nothing beyond identity: any two values that differ keep their
1065    /// backdrops apart.
1066    ///
1067    /// The id outlives the target it captured. A layer naming one from inside
1068    /// another layer is seeded with the captured image placed where that
1069    /// layer's target sits within it, which is the same arithmetic a bounded
1070    /// layer is already seeded by.
1071    pub fn with_backdrop_id(mut self, id: i64) -> Self {
1072        self.backdrop_id = Some(id);
1073        self
1074    }
1075
1076    pub fn with_blur(self, sigma: f32) -> Self {
1077        self.with_blur_xy(sigma, sigma)
1078    }
1079
1080    /// Blur the finished group by a deviation per axis, in device pixels.
1081    ///
1082    /// Two, because `dart:ui`'s `ImageFilter.blur` states `sigmaX` and
1083    /// `sigmaY` separately. A blur here is two separable passes already, one
1084    /// along each axis, so each simply uses its own -- and a pass whose
1085    /// deviation is zero is skipped rather than run, which is what keeps a
1086    /// blur along one axis from resampling the other for nothing.
1087    pub fn with_blur_xy(mut self, sigma_x: f32, sigma_y: f32) -> Self {
1088        // Clamped to upstream's `kMaxSigma`, and clamped *after* the check
1089        // rather than before it: `f32::min` returns the other operand when one
1090        // is NaN, so clamping first turns a NaN into five hundred and asks for
1091        // the widest blur there is. The same trap is named at `Rect::outset`,
1092        // which is where this was learned the first time.
1093        let one = |sigma: f32| {
1094            if sigma.is_finite() && sigma > 0.0 {
1095                sigma.min(MAX_SIGMA)
1096            } else {
1097                0.0
1098            }
1099        };
1100        self.blur = Vec2::new(one(sigma_x), one(sigma_y));
1101        self
1102    }
1103}
1104
1105/// Records drawing commands for one frame.
1106pub struct Canvas {
1107    /// Blend the advanced modes in the shader, against a copy of what is
1108    /// under each such draw, rather than in the device's blend unit. See
1109    /// [`Canvas::with_advanced_blends_in_shader`].
1110    advanced_blends_in_shader: bool,
1111    renderer: Renderer,
1112    batch: Batch,
1113    transform: Transform2D,
1114    /// The region drawing is confined to, or `None` for the whole target.
1115    ///
1116    /// Kept in device pixels rather than user space because that is what it
1117    /// means: a clip is fixed at the moment it is applied, and a later
1118    /// transform moves the shapes drawn inside it without moving the clip.
1119    clip: Option<Scissor>,
1120    /// A rectangle around everything the clip still admits, in device pixels.
1121    ///
1122    /// Kept beside the scissor rather than derived from it, because a path
1123    /// clip narrows what may be drawn without narrowing the scissor at all --
1124    /// it goes to the stencil instead. A caller asking what is still reachable
1125    /// wants both accounted for, and only this has seen both.
1126    clip_bounds: Rect,
1127    /// How many clips of a shape a scissor cannot express are in force.
1128    ///
1129    /// Content draws where the stencil holds this, which is true only where
1130    /// every one of those clips admitted the pixel.
1131    depth: u32,
1132    /// Those clips, in the order they were built. See [`StencilClip`].
1133    clips: Vec<StencilClip>,
1134    stack: Vec<SavedState>,
1135    /// What the batch being recorded samples, in slot order.
1136    sources: Vec<TextureSource>,
1137    /// Layers already finished, in the order they were restored.
1138    ///
1139    /// A layer is restored before anything can composite it, so this order is
1140    /// already an order the passes can be executed in.
1141    finished: Vec<Pass>,
1142    extent: Extent2D,
1143    /// The target being recorded into: the frame, or a bounded layer's.
1144    target: Target,
1145    background: Option<Color>,
1146    /// Set once anything asks for antialiasing.
1147    ///
1148    /// Multisampling is a property of the pass, so it cannot vary per shape.
1149    /// Turning it on for the whole frame when any shape wants it is the
1150    /// behavior that surprises least; the alternative silently ignores the
1151    /// request on some shapes.
1152    anti_alias: bool,
1153    /// Whether the batch now open begins by redrawing the whole target.
1154    ///
1155    /// It does when a pass was cut: what follows the cut is a full-target `Src`
1156    /// blit of the pass just finished, unclipped and unstencilled, so every pixel
1157    /// is written before anything else in the batch. A pass like that can be given
1158    /// a clear color it will never show -- and a clear is what a multisampled pass
1159    /// requires here, the alternative being a resolved-to-multisample load that
1160    /// this technique has no reverse of.
1161    ///
1162    /// Tracked rather than inferred from `background` being absent, because a
1163    /// caller that never set a background is compositing onto whatever the surface
1164    /// already holds, and clearing *that* pass would erase it.
1165    seeded_by_redraw: bool,
1166    /// Whether to leave hidden pixels in the draws that write them.
1167    ///
1168    /// Culling them is pixel-identical by construction, and the way to check that claim
1169    /// is to render the same scene both ways and compare. Nothing but a test should want
1170    /// this, which is why it is reachable only through a hidden method.
1171    keep_hidden_draws: bool,
1172    samples: u32,
1173    /// Gradients tabulated because their stops did not fit in a material.
1174    ///
1175    /// Across the whole recording rather than per pass, so the same gradient
1176    /// drawn into a layer and again over it is baked once.
1177    ramps: Vec<Ramp>,
1178    /// Backdrops captured once and filtered by every layer naming the same id.
1179    ///
1180    /// A `Canvas` records one frame and `finish` consumes it, so this lives
1181    /// exactly as long as the ids are meaningful and there is nothing to
1182    /// clear. Upstream's `Canvas` is reused across frames and empties its
1183    /// `backdrop_data_` at the end of each one.
1184    backdrops: std::collections::HashMap<i64, BackdropShare>,
1185}
1186
1187/// A backdrop ready to be laid under a layer's own content.
1188///
1189/// Three things rather than a pass index, because a seed is a draw and a draw
1190/// needs a mapping: which pass holds the filtered image, which target that pass
1191/// is an image *of* -- they differ when a bounded layer seeds from its parent
1192/// -- and the matrix the filter asked for, which is the one filter that moves
1193/// the image rather than recomputing it where it stands.
1194#[derive(Clone, Copy)]
1195struct Backdrop {
1196    pass: usize,
1197    of: Target,
1198    /// `None` for every filter but a matrix, which is what it means for the
1199    /// image to be read where it was written.
1200    moved_by: Option<Affine2>,
1201}
1202
1203/// One captured backdrop, and what has already been made of it.
1204///
1205/// The capture is a pass index, which is all a backdrop needs to be here: a
1206/// pass is the unit a later pass samples, so sharing one is sharing the index
1207/// rather than managing a texture. Upstream carries a `std::shared_ptr<Texture>`
1208/// in the same slot, and a second one for the filtered result, because its
1209/// filters produce snapshots rather than passes.
1210struct BackdropShare {
1211    /// The target the capture is an image of, which need not be the one a
1212    /// later layer naming the id is drawn into.
1213    ///
1214    /// An id keys a captured image and nothing else, so a layer opened inside
1215    /// some other layer still filters what the id captured. That is upstream's
1216    /// reading and it is exercised there:
1217    /// `CanRenderMultipleBackdropBlurWithSingleBackdropIdDifferentLayers` wraps
1218    /// every panel but the first in a save layer of its own and expects all six
1219    /// to show the same ground. Seeding needs no case for it -- a filtered pass
1220    /// is drawn into a rectangle *of* its source, which is already how a
1221    /// bounded layer is seeded from a full-target capture.
1222    captured_from: Target,
1223    /// The pass holding the backdrop as it was when the id was first used.
1224    captured: usize,
1225    /// Filters already run over `captured`, and where each landed.
1226    ///
1227    /// A filter is a function of its input, so the same filter over the same
1228    /// capture is the same image and there is no reason to compute it twice.
1229    /// This is upstream's `all_filters_equal` and `shared_filter_snapshot`,
1230    /// with the restriction lifted: upstream shares one snapshot only when
1231    /// *every* filter on the id is equal, which a list of rows that blur by
1232    /// different amounts fails outright. Keyed per filter, two amounts share
1233    /// what they have in common -- the capture -- and each still gets its own.
1234    ///
1235    /// A list rather than a map because a shared backdrop has a handful of
1236    /// distinct filters at most, and `ImageFilter` holds a program's uniforms.
1237    filtered: Vec<(ImageFilter, usize)>,
1238}
1239
1240impl Canvas {
1241    /// Start recording for a target of the given size.
1242    pub fn new(extent: Extent2D) -> Self {
1243        let mut renderer = Renderer::new();
1244        renderer.begin_frame(extent, TOLERANCE);
1245        Self {
1246            renderer,
1247            batch: Batch::new(),
1248            transform: Transform2D::IDENTITY,
1249            clip: None,
1250            // The whole target to start with, which is what an unclipped
1251            // canvas may reach.
1252            clip_bounds: Rect::new(0.0, 0.0, extent.width as f32, extent.height as f32),
1253            depth: 0,
1254            clips: Vec::new(),
1255            stack: Vec::new(),
1256            sources: Vec::new(),
1257            finished: Vec::new(),
1258            extent,
1259            target: Target::frame(extent),
1260            background: None,
1261            anti_alias: false,
1262            seeded_by_redraw: false,
1263            keep_hidden_draws: false,
1264            samples: 4,
1265            ramps: Vec::new(),
1266            backdrops: std::collections::HashMap::new(),
1267            advanced_blends_in_shader: false,
1268        }
1269    }
1270
1271    /// Blend the advanced modes -- `multiply` through `luminosity` -- in the
1272    /// shader, against a copy of what is under each such draw, rather than in
1273    /// the device's blend unit.
1274    ///
1275    /// For a device without `VK_EXT_blend_operation_advanced` or its GLES
1276    /// counterpart, which is most of those that are not a desktop's: no
1277    /// combination of blend factors expresses these modes, and a recording
1278    /// that uses one is refused there (`Error::Unsupported`). With this on,
1279    /// each draw or layer composite blending by one cuts the pass first, as a
1280    /// backdrop does, and the draw reads the cut back as its destination: the
1281    /// shader computes the mode and the draw replaces what it covers. One
1282    /// full-target redraw per such draw is the cost, which is why it is off
1283    /// unless asked for: a device that has the extension does better without
1284    /// it. Whoever makes the canvas knows the device; a recording does not.
1285    ///
1286    /// The picture is the same either way, to the precision of the target:
1287    /// the copy holds what the target holds.
1288    pub fn with_advanced_blends_in_shader(mut self, on: bool) -> Self {
1289        self.advanced_blends_in_shader = on;
1290        self
1291    }
1292
1293    /// Before a draw or a composite blending by `blend`: where this canvas
1294    /// blends the advanced modes in the shader, cut the pass for one so its
1295    /// draws read what is under them, and for any other mode stop the batch
1296    /// handing out a copy that will no longer be what is under anything.
1297    ///
1298    /// First thing in every call that draws, before any texture slot is
1299    /// taken: a cut hands the slots taken so far to the pass it finishes. A
1300    /// copy no draw has read yet is still the destination, so a call that
1301    /// reaches here twice cuts once.
1302    fn prepare_destination(&mut self, blend: BlendMode) {
1303        if !self.advanced_blends_in_shader {
1304            return;
1305        }
1306        if !blend.is_advanced() {
1307            self.batch.forget_destination();
1308            return;
1309        }
1310        if self.batch.destination_fresh() {
1311            return;
1312        }
1313        let cut = self.cut_pass();
1314        let slot = self.slot_for(TextureSource::Layer(cut));
1315        self.batch.read_destination_from(slot);
1316    }
1317
1318    /// Sample count to use when anything is antialiased.
1319    pub fn with_samples(mut self, samples: u32) -> Self {
1320        self.samples = samples.max(1);
1321        self
1322    }
1323
1324    pub fn extent(&self) -> Extent2D {
1325        self.extent
1326    }
1327
1328    /// Fill the whole target before drawing anything else.
1329    ///
1330    /// Required, not merely usual, if the frame itself draws an antialiased
1331    /// shape that is not analytic. Such a shape renders through a multisample
1332    /// buffer, and there is no way to seed that buffer with what the target
1333    /// already held -- so a multisampled pass has to clear, and a canvas with
1334    /// no background gives its root pass nothing to clear to. Drawing one is
1335    /// refused rather than quietly discarding whatever was on the surface.
1336    ///
1337    /// The frame itself, and not the picture: a sample count describes one
1338    /// pass. The same shape drawn inside a layer needs the layer's pass
1339    /// multisampled and leaves the frame alone, since what the frame does with
1340    /// a finished layer is draw one image quad. So a shadow, which is a layer
1341    /// underneath, needs no background at all.
1342    ///
1343    /// [`Paint::with_anti_alias`] is the other end of the choice.
1344    pub fn clear(&mut self, color: Color) -> &mut Self {
1345        self.background = Some(color);
1346        self
1347    }
1348
1349    /// Current transform, mapping user coordinates to device pixels.
1350    pub fn transform(&self) -> Transform2D {
1351        self.transform
1352    }
1353
1354    /// The region drawing is currently confined to, in device pixels.
1355    ///
1356    /// `None` is the whole target.
1357    pub fn clip(&self) -> Option<Scissor> {
1358        self.clip
1359    }
1360
1361    /// The region drawing may still reach, in device pixels.
1362    ///
1363    /// Conservative: it is a rectangle around the clip rather than the clip
1364    /// itself, so a path clip reports its bounding box and a rotated
1365    /// rectangle reports the axis-aligned box around it. That is what makes it
1366    /// useful for the thing it is for -- deciding not to draw something --
1367    /// since a caller may skip anything outside it and must not assume
1368    /// everything inside it is visible.
1369    pub fn destination_clip_bounds(&self) -> Rect {
1370        self.clip_bounds
1371    }
1372
1373    /// The same region in the coordinates the caller is currently drawing in.
1374    ///
1375    /// The device bounds carried back through the transform, which under a
1376    /// rotation gives the box around the rotated box and so grows a little
1377    /// each time. Conservative in the same direction as everything else here:
1378    /// too large is a missed optimization, too small is a missing shape.
1379    ///
1380    /// A transform that cannot be inverted has collapsed the plane, and
1381    /// nothing drawn through it reaches anything; the empty rectangle says so.
1382    pub fn local_clip_bounds(&self) -> Rect {
1383        let Some(inverse) = self.transform.inverse() else {
1384            return Rect::new(0.0, 0.0, 0.0, 0.0);
1385        };
1386        // Two different ways this can have no answer, and they take opposite
1387        // ones. A transform that has collapsed leaves nothing reachable, which
1388        // the check above answers with an empty rectangle. A transform whose
1389        // inverse carries the clip across the vanishing line leaves *more*
1390        // reachable than a box can say -- and since this rectangle is a promise
1391        // about what lies outside it, the safe failure there is everything.
1392        let (min, max) = transformed_bounds(
1393            inverse,
1394            Vec2::new(self.clip_bounds.left, self.clip_bounds.top),
1395            Vec2::new(self.clip_bounds.right, self.clip_bounds.bottom),
1396        )
1397        .unwrap_or_else(unbounded);
1398        Rect::new(min.x, min.y, max.x, max.y)
1399    }
1400
1401    /// Narrow the tracked bounds to a rectangle already in device space.
1402    fn narrow_bounds(&mut self, min: Vec2, max: Vec2) {
1403        let current = self.clip_bounds;
1404        self.clip_bounds = Rect::new(
1405            current.left.max(min.x),
1406            current.top.max(min.y),
1407            current.right.min(max.x),
1408            current.bottom.min(max.y),
1409        );
1410        // An intersection that crossed over is empty rather than inside out,
1411        // which every consumer of a rectangle here would otherwise have to
1412        // check for itself.
1413        if self.clip_bounds.right < self.clip_bounds.left
1414            || self.clip_bounds.bottom < self.clip_bounds.top
1415        {
1416            self.clip_bounds = Rect::new(
1417                self.clip_bounds.left,
1418                self.clip_bounds.top,
1419                self.clip_bounds.left,
1420                self.clip_bounds.top,
1421            );
1422        }
1423    }
1424
1425    /// Narrow the clip to a rectangle in user space.
1426    ///
1427    /// Intersects with the clip already in force rather than replacing it,
1428    /// which is what makes the clip stack compose: a subtree can only ever
1429    /// narrow what its parent allowed. The rectangle goes through the current
1430    /// transform, so it moves with the coordinate system the caller set up.
1431    ///
1432    /// # Rotation
1433    ///
1434    /// Returns [`Error::Unsupported`] when the current transform rotates or
1435    /// skews by anything other than a quarter turn, because the result is then
1436    /// a rotated quadrilateral and this clip is a rectangle. Refusing is the
1437    /// point: the tempting alternative is to use the rotated shape's bounding
1438    /// box, which admits pixels the caller asked to remove, and produces a
1439    /// picture that is wrong in a way that looks like a rendering bug rather
1440    /// than like a clip that was never applied. Arbitrary clip shapes need a
1441    /// stencil pass, which is a separate piece of machinery.
1442    pub fn clip_rect(&mut self, rect: Rect) -> Result<&mut Self> {
1443        // Under a transform that keeps rectangles rectangular, this is exactly
1444        // a scissor, which costs nothing and is exact. Under anything else the
1445        // result is a rotated quadrilateral, and taking its bounding box would
1446        // admit pixels the caller asked to remove -- so it goes through the
1447        // stencil like any other shape. That the fast path survives is the
1448        // point: a scissor stays the right answer for an axis-aligned clip even
1449        // now that the general one exists.
1450        if !preserves_axis_alignment(self.transform) {
1451            return self.clip_path(&rect.to_path());
1452        }
1453        let Some((min, max)) = transformed_bounds(
1454            self.transform,
1455            Vec2::new(rect.left, rect.top),
1456            Vec2::new(rect.right, rect.bottom),
1457        ) else {
1458            // Unreachable through the check above, which has already refused
1459            // anything but an affine -- and written as a fallback rather than
1460            // an assertion because the two are coupled only by argument, and
1461            // the stencil path is the right answer either way.
1462            return self.clip_path(&rect.to_path());
1463        };
1464        let narrowed = Scissor::from_device_bounds(
1465            (min - self.target.origin).into(),
1466            (max - self.target.origin).into(),
1467            self.target.extent,
1468        );
1469        self.clip = Some(match self.clip {
1470            Some(existing) => existing.intersect(narrowed),
1471            None => narrowed,
1472        });
1473        self.narrow_bounds(min, max);
1474        Ok(self)
1475    }
1476
1477    /// Narrow the clip to everything *outside* a rectangle in user space.
1478    ///
1479    /// `dart:ui` spells this `clipRect` with `ClipOp.difference`, and it is the
1480    /// only clip that operation applies to there -- `clipPath` and `clipRRect`
1481    /// intersect and take no operation.
1482    ///
1483    /// Never a scissor, whatever the transform: the complement of a rectangle
1484    /// is not one, and a scissor is. So this goes through the stencil like an
1485    /// arbitrary shape, and the shape it narrows by is the target with the
1486    /// rectangle taken out of it -- two contours filled by the even-odd rule,
1487    /// which is what makes the second a hole in the first rather than a second
1488    /// region drawn over it. `draw_drrect` builds a ring the same way.
1489    ///
1490    /// Both contours are built in device coordinates and filled through the
1491    /// identity, rather than in user space through the transform. The reason is
1492    /// the target: it is a device rectangle, and expressing it in user space
1493    /// would mean inverting a transform that may not be invertible. The
1494    /// rectangle's own corners go through the transform here instead, so a
1495    /// rotation gives the quadrilateral it should rather than a box around one.
1496    pub fn clip_out_rect(&mut self, rect: Rect) -> Result<&mut Self> {
1497        if self.clip.is_some_and(Scissor::is_empty) {
1498            return Ok(self);
1499        }
1500        let mut builder = PathBuilder::new().with_fill_rule(FillRule::EvenOdd);
1501        // The whole target, which is what "outside the rectangle" is measured
1502        // against.
1503        let target = Rect::new(
1504            self.target.origin.x,
1505            self.target.origin.y,
1506            self.target.origin.x + self.target.extent.width as f32,
1507            self.target.origin.y + self.target.extent.height as f32,
1508        );
1509        builder
1510            .move_to(Vec2::new(target.left, target.top))
1511            .line_to(Vec2::new(target.right, target.top))
1512            .line_to(Vec2::new(target.right, target.bottom))
1513            .line_to(Vec2::new(target.left, target.bottom))
1514            .close();
1515        // The rectangle's corners under the transform, in the order that keeps
1516        // the contour simple. A degenerate one encloses no area and takes
1517        // nothing out, which is the right answer for a clip that removes an
1518        // empty rectangle.
1519        let corners = [
1520            Vec2::new(rect.left, rect.top),
1521            Vec2::new(rect.right, rect.top),
1522            Vec2::new(rect.right, rect.bottom),
1523            Vec2::new(rect.left, rect.bottom),
1524        ]
1525        .map(|corner| self.transform.project_point2(corner));
1526        // A corner that is not a number describes no rectangle, so there is
1527        // nothing to take out and the clip is left as it was. Under a transform
1528        // carrying perspective this is also what catches a corner past the
1529        // vanishing line, where the divide reports an infinity rather than a
1530        // wrong finite answer -- and where the four corners would no longer
1531        // describe the region even if they were finite.
1532        if !corners.iter().all(|corner| corner.is_finite()) {
1533            return Ok(self);
1534        }
1535        builder.move_to(corners[0]);
1536        for corner in &corners[1..] {
1537            builder.line_to(*corner);
1538        }
1539        builder.close();
1540
1541        let paint = RenderPaint {
1542            material: Material::solid([1.0, 1.0, 1.0, 1.0]),
1543            filter: ColorFilter::None,
1544            blend: BlendMode::Src,
1545            clip: self.clip,
1546            stencil: ClipState::narrow(self.depth),
1547        };
1548        let path = builder.build();
1549        self.renderer
1550            .fill_into(&mut self.batch, &path, Affine2::IDENTITY, &paint)?;
1551        self.depth += 1;
1552        self.clips.push(StencilClip {
1553            path,
1554            transform: Transform2D::IDENTITY,
1555            scissor: paint.clip,
1556        });
1557        // The tracked bounds are left alone, and that is not an oversight.
1558        // Removing a rectangle from the middle of a region leaves its bounding
1559        // box exactly where it was, and removing one from the edge leaves a box
1560        // that is too large -- which is the safe direction, since these bounds
1561        // decide how much a caller draws and how large a layer is allocated.
1562        Ok(self)
1563    }
1564
1565    /// Narrow the clip to an arbitrary path in user space.
1566    ///
1567    /// Intersects with the clip already in force, like [`Self::clip_rect`], and
1568    /// like it the path travels through the current transform. The shape is
1569    /// recorded into the batch as a draw that writes only the stencil, so it
1570    /// costs one draw where a rectangular clip costs none.
1571    ///
1572    /// The path is filled by the same tessellator that fills a drawn shape, so
1573    /// it obeys the same fill rule and produces the same edges. That matters
1574    /// for more than consistency: the tessellation is a set of non-overlapping
1575    /// triangles, which is what lets the stencil step forward by one rather
1576    /// than needing the parity trick an overlapping fan would.
1577    pub fn clip_path(&mut self, path: &Path) -> Result<&mut Self> {
1578        if self.clip.is_some_and(Scissor::is_empty) {
1579            // Already clipped to nothing; narrowing further changes nothing and
1580            // the draw would be dropped anyway.
1581            return Ok(self);
1582        }
1583        let paint = RenderPaint {
1584            // Masked off entirely by a clip draw, but a material is still
1585            // needed to build one. White says plainly that nothing here is a
1586            // color decision.
1587            material: Material::solid([1.0, 1.0, 1.0, 1.0]),
1588            filter: ColorFilter::None,
1589            blend: BlendMode::Src,
1590            clip: self.clip,
1591            stencil: ClipState::narrow(self.depth),
1592        };
1593        self.renderer
1594            .fill_into(&mut self.batch, path, self.transform, &paint)?;
1595        self.depth += 1;
1596        self.clips.push(StencilClip {
1597            path: path.clone(),
1598            transform: self.transform,
1599            scissor: paint.clip,
1600        });
1601        // A path clip narrows what may be drawn without touching the scissor,
1602        // so the tracked rectangle is the only place it is accounted for. Its
1603        // bounding box rather than the path: this rectangle is a promise about
1604        // what is *outside* it, and a box around a shape keeps that promise.
1605        let bounds = path.bounds();
1606        // A clip whose bounds cannot be computed narrows nothing here. The
1607        // stencil still confines it exactly; what is lost is only the tracked
1608        // rectangle used to skip work, and leaving it wide is the direction
1609        // that costs time rather than pixels.
1610        if let Some((min, max)) = transformed_bounds(self.transform, bounds.min, bounds.max) {
1611            self.narrow_bounds(min, max);
1612        }
1613        Ok(self)
1614    }
1615
1616    /// Save the transform and clip so a later `restore` can return to them.
1617    pub fn save(&mut self) -> &mut Self {
1618        self.stack.push(SavedState {
1619            transform: self.transform,
1620            clip: self.clip,
1621            clip_bounds: self.clip_bounds,
1622            depth: self.depth,
1623            clips: self.clips.len(),
1624            layer: None,
1625        });
1626        self
1627    }
1628
1629    /// Begin drawing into a layer of its own, composited back on `restore`.
1630    ///
1631    /// Everything recorded until the matching restore goes into a separate
1632    /// target and arrives as one image, which is what makes an alpha here apply
1633    /// to the group rather than to each shape in it.
1634    ///
1635    /// The layer starts unclipped and at the identity for clipping purposes,
1636    /// while keeping the current transform. It does not need to inherit the
1637    /// clip because the draw that composites it is subject to it: content the
1638    /// clip excludes is discarded once rather than prevented from being drawn,
1639    /// which costs some work in the layer and keeps a stencil clip from having
1640    /// to be rebuilt in a second target.
1641    pub fn save_layer(&mut self, layer: Layer) -> &mut Self {
1642        // A layer that captures a backdrop is handed to the bounded path with
1643        // no bounds, which narrows it to the clip in force. That path scales
1644        // the layer itself, so this one hands it over unscaled.
1645        //
1646        // A shared key goes that way too. What the key shares is the capture
1647        // and the filtered image over it, both of which stay the parent's size
1648        // because they have to serve every group naming it; the layer's own
1649        // target is bound by the clip like any other.
1650        if layer.backdrop_blur > 0.0 && layer.matrix.is_none() {
1651            let (min, max) = unbounded();
1652            // Cannot fail: only a backdrop *filter* can refuse, and this
1653            // passes none -- the blur rides on the layer.
1654            let _ = self.save_layer_device_bounds_running(layer, min, max, None, None);
1655            return self;
1656        }
1657        // The other entry to `open_layer` converts the sigmas where it computes
1658        // its reach; this one has no bounds to reach past and so converts them
1659        // here. Both are the same conversion at the same moment -- the layer is
1660        // opened under the transform the caller drew in, which is the one its
1661        // sigma is stated against.
1662        let layer = layer.scaled_by(max_scale_of(self.transform), axis_scales_of(self.transform));
1663        let widened = self.matrix_preimage(&layer);
1664        let pending = self.open_layer(layer, None, None, None).unwrap_or(None);
1665        if let Some(target) = widened {
1666            self.aim_at(target);
1667        }
1668        self.seed_backdrop(pending);
1669        self
1670    }
1671
1672    /// The region a layer must record over when a matrix will move its result.
1673    ///
1674    /// A layer's target is the parent's, and a draw outside it is scissored
1675    /// away -- which is right for every layer except one whose matrix brings
1676    /// content in from outside. `dart:ui`'s matrix image filter is exactly
1677    /// that, and upstream's `MatrixImageFilterDoesntCullWhenTranslatedFromOffscreen`
1678    /// draws a circle three hundred points to the left of the frame and
1679    /// translates it back.
1680    ///
1681    /// What has to be recorded over is the *pre-image*: the region that, once
1682    /// the matrix has moved it, lands where the parent can see it. Union with
1683    /// the parent, because a matrix that moves some content in leaves the rest
1684    /// where it was.
1685    ///
1686    /// **Opening wide costs no memory, and that is what makes this safe.** The
1687    /// pass's extent comes from the narrowed target in `finish_layer`, which is
1688    /// the content's own bounds -- so a minifying matrix, whose inverse is a
1689    /// magnifying one, widens the region a draw may land in without allocating
1690    /// for a region no draw reached. What is allocated stays bounded by what
1691    /// the caller drew.
1692    fn matrix_preimage(&self, layer: &Layer) -> Option<Target> {
1693        let matrix = layer.matrix?;
1694        let parent = self.target;
1695        let (min, max) = (
1696            parent.origin,
1697            parent.origin + Vec2::new(parent.extent.width as f32, parent.extent.height as f32),
1698        );
1699        let (back_min, back_max) = transformed_bounds(matrix.inverse()?, min, max)?;
1700        let left = min.x.min(back_min.x).floor();
1701        let top = min.y.min(back_min.y).floor();
1702        let right = max.x.max(back_max.x).ceil();
1703        let bottom = max.y.max(back_max.y).ceil();
1704        // A matrix that folds the plane or carries the region across the
1705        // vanishing line has no region to report, and one that widens past what
1706        // an extent can hold is not a picture anybody asked for.
1707        //
1708        // The second half of that sentence was not implemented, and `as u32`
1709        // **saturates**: a finite width of `3.4e38` passed the finiteness test
1710        // and came out of the cast as `u32::MAX`. A layer whose extent is four
1711        // billion texels then clamps a morphology radius to four billion and
1712        // emits one pass per thirty-two texels of it -- a hundred and
1713        // thirty-four million passes, which is a recording measured in
1714        // gigabytes. Found by `hostile_api`, whose case is in that test's
1715        // regressions file; it reached the gate as the OOM killer rather than
1716        // as a failure.
1717        let (width, height) = (right - left, bottom - top);
1718        let holdable = |side: f32| side.is_finite() && side > 0.0 && side <= MAX_TARGET_SIDE;
1719        if !(holdable(width) && holdable(height)) {
1720            return None;
1721        }
1722        Some(Target {
1723            origin: Vec2::new(left, top),
1724            extent: Extent2D::new(width as u32, height as u32),
1725        })
1726    }
1727
1728    /// Push the layer frame, and cut the backdrop out if one was asked for.
1729    ///
1730    /// Returns what the layer's target must be seeded with once its size is
1731    /// settled, which is why this is separate from the seeding: a bounded layer
1732    /// does not know its own target until after the frame exists, and the seed
1733    /// has to land in the target the content will draw into.
1734    fn open_layer(
1735        &mut self,
1736        layer: Layer,
1737        filter: Option<ImageFilter>,
1738        backdrop: Option<&ImageFilter>,
1739        region: Option<Target>,
1740    ) -> Result<Option<Backdrop>> {
1741        let parent = self.target;
1742        // Where the backdrop's filter writes, which is the target the layer is
1743        // about to take rather than the parent it is captured from. `None` is
1744        // the caller that has not worked one out yet, and gets the parent.
1745        let region = region.unwrap_or(parent);
1746        // The layer's own sigma is the `Copy`-friendly spelling of the same
1747        // thing, so it becomes a filter here and there is one path below.
1748        //
1749        // And this is where it is converted into device pixels, because this is
1750        // the first place with two components to convert it into. `Layer::scaled_by`
1751        // leaves it alone for that reason: the caller stated one number, meaning a
1752        // blur round in their space, and under a transform whose axes scale
1753        // differently that is an oval. A filter handed over by the caller is
1754        // already converted -- `save_layer_filtered` and the backdrop entry points
1755        // run it through `ImageFilter::scaled_by` -- so only this arm converts.
1756        let axes = axis_scales_of(self.transform);
1757        let asked = match backdrop {
1758            Some(filter) => filter.clone(),
1759            None if layer.backdrop_blur > 0.0 => ImageFilter::Blur {
1760                sigma_x: layer.backdrop_blur * axes.x,
1761                sigma_y: layer.backdrop_blur * axes.y,
1762            },
1763            None => ImageFilter::None,
1764        };
1765        let filtered = if asked.is_identity() {
1766            None
1767        } else {
1768            // The frame is pushed whether or not this succeeds: a layer that
1769            // fails to filter its backdrop still has to be a layer, or the
1770            // `restore` the caller has already written closes something else.
1771            match self.backdrop_pass(layer.backdrop_id, parent, region, &asked) {
1772                Ok(pending) => Some(pending),
1773                Err(e) => {
1774                    self.push_layer_frame(layer, filter);
1775                    return Err(e);
1776                }
1777            }
1778        };
1779        self.push_layer_frame(layer, filter);
1780        Ok(filtered)
1781    }
1782
1783    /// The pass a backdrop-filtered layer starts from, and what it is an image
1784    /// of.
1785    ///
1786    /// Without an id this is the whole of what a backdrop filter was: cut the
1787    /// target's content out into a pass, and filter that. With one, both halves
1788    /// are shared with whatever named the id before -- the capture always, so
1789    /// that the second layer filters what was behind the first rather than the
1790    /// first's own result, and the filtered pass as well when the filter
1791    /// matches one already run over that capture.
1792    ///
1793    /// The second element is the target the pass covers, which is `parent` for
1794    /// a fresh capture and whatever the id captured for a shared one. Seeding
1795    /// needs it to place the image, and the two can differ; see
1796    /// [`BackdropShare::captured_from`].
1797    ///
1798    /// The cut happens before the filter can refuse, which is the order the
1799    /// no-id path always had. A refusal therefore leaves the capture recorded,
1800    /// which is right: the backdrop was captured, and the next layer naming the
1801    /// id should filter that same image whether or not this one could.
1802    fn backdrop_pass(
1803        &mut self,
1804        id: Option<i64>,
1805        parent: Target,
1806        region: Target,
1807        filter: &ImageFilter,
1808    ) -> Result<Backdrop> {
1809        // A matrix is peeled off here rather than run as a pass. Every other
1810        // filter reads its input where the fragment is and writes there, so it
1811        // is a pass over a target the size of what it was handed; a matrix
1812        // moves the image instead, and a pass for it would need a target sized
1813        // for where the content went. It does not need one: what a backdrop is
1814        // seeded into is the layer's own target, already allocated and the same
1815        // size whatever the matrix says, and the seed is a draw with a mapping
1816        // -- so the matrix goes into that mapping and no pass is spent.
1817        //
1818        // Only at the top. Inside a composition the matrix is between two
1819        // filters that do run as passes, so its result is what the outer one
1820        // reads and there is no seed to fold it into; that stays refused, in
1821        // `filter_passes`.
1822        let (filter, moved_by) = match filter {
1823            ImageFilter::Matrix { transform } => {
1824                let Some(affine) = transform.to_affine() else {
1825                    return Err(Error::Unsupported(
1826                        "a projective matrix is not available as a backdrop filter; \
1827                         it maps the image through a division this seed does not do",
1828                    ));
1829                };
1830                if affine.matrix2.determinant() == 0.0 {
1831                    return Err(Error::Unsupported(
1832                        "a singular matrix is not available as a backdrop filter; \
1833                         it collapses the image and nothing says what it read",
1834                    ));
1835                }
1836                (&ImageFilter::None, Some(affine))
1837            }
1838            other => (other, None),
1839        };
1840        let Some(id) = id else {
1841            // The capture is the pass being cut, so it is the parent's size
1842            // whatever happens next. What the filter *writes* need not be: its
1843            // passes only have to cover the region the layer will hold, which
1844            // is where the seed reads from. But each filter pass maps a
1845            // full-target quad onto the whole of what it reads, a texel to a
1846            // pixel only when the two are one size, so the region's rectangle
1847            // of the capture is cropped out first: read whole, a bounded
1848            // backdrop held the entire capture shrunk into the region rather
1849            // than the part of it behind the layer. The region already reaches
1850            // as far as the filter does, so the crop cuts nothing it reads.
1851            let cut = self.cut_pass();
1852            let cropped = if region == parent {
1853                cut
1854            } else {
1855                self.crop_pass(cut, parent, region)
1856            };
1857            let pass =
1858                self.filter_passes(cropped, region, filter, BlurBasis::of(self.transform))?;
1859            return Ok(Backdrop {
1860                pass,
1861                // Unless the filter had nothing to do -- a matrix backdrop
1862                // moves the capture rather than recomputing it, and hands the
1863                // cut straight back, which is the parent's region and not this
1864                // one.
1865                of: if pass == cut { parent } else { region },
1866                moved_by,
1867            });
1868        };
1869
1870        // Read out by value first: what follows needs `&mut self`, and the
1871        // three things wanted from the entry are all `Copy`.
1872        let existing = self.backdrops.get(&id).map(|share| {
1873            let already = share
1874                .filtered
1875                .iter()
1876                .find(|(known, _)| known == filter)
1877                .map(|(_, pass)| *pass);
1878            (share.captured_from, share.captured, already)
1879        });
1880
1881        let (over, captured) = match existing {
1882            // A filter is a function of its input, so the same filter over the
1883            // same capture is the same image and there is nothing to compute.
1884            Some((from, _, Some(pass))) => {
1885                return Ok(Backdrop {
1886                    pass,
1887                    of: from,
1888                    moved_by,
1889                })
1890            }
1891            Some((from, captured, None)) => (from, captured),
1892            None => {
1893                let cut = self.cut_pass();
1894                self.backdrops.insert(
1895                    id,
1896                    BackdropShare {
1897                        captured_from: parent,
1898                        captured: cut,
1899                        filtered: Vec::new(),
1900                    },
1901                );
1902                (parent, cut)
1903            }
1904        };
1905
1906        let pass = self.filter_passes(captured, over, filter, BlurBasis::of(self.transform))?;
1907        if let Some(share) = self.backdrops.get_mut(&id) {
1908            share.filtered.push((filter.clone(), pass));
1909        }
1910        Ok(Backdrop {
1911            pass,
1912            of: over,
1913            moved_by,
1914        })
1915    }
1916
1917    /// End the current target's pass here, and answer which pass now holds it.
1918    ///
1919    /// The architecture's rule is that a pass cannot sample the attachment it
1920    /// is writing, which is exactly what a backdrop filter asks for. So the
1921    /// pass stops: everything drawn into this target so far becomes a pass of
1922    /// its own, and what follows begins by drawing that pass back in.
1923    ///
1924    /// The redraw is the cost, one full-target copy per backdrop filter, and it
1925    /// is not avoidable without the machinery the rule exists for the absence
1926    /// of. It is a `Src` blit covering the whole target, so it reproduces what
1927    /// was cut exactly rather than compositing with it.
1928    fn cut_pass(&mut self) -> usize {
1929        let target = self.target;
1930        let mut batch = std::mem::take(&mut self.batch);
1931        let sources = std::mem::take(&mut self.sources);
1932        // The clear belongs to the half that starts from nothing. A layer's
1933        // target clears to transparent and the frame's to its background; after
1934        // the cut neither clears again, since the redraw below covers every
1935        // pixel with `Src`.
1936        let clear = if self.in_layer() {
1937            Some([0.0; 4])
1938        } else {
1939            self.background
1940                .take()
1941                .map(|c| c.to_array())
1942                .or_else(|| self.seeded_by_redraw.then_some([0.0; 4]))
1943        };
1944        // Stop each draw writing pixels a later opaque draw replaces. Pixel-identical
1945        // and order-preserving -- see `Batch::cull_occluded`, which has the argument --
1946        // and done here rather than in the backends because it is a property of the
1947        // finished pass rather than of either API.
1948        if !self.keep_hidden_draws {
1949            batch.cull_occluded(target.extent);
1950        }
1951        self.finished.push(Pass {
1952            batch,
1953            descriptor: PassDescriptor {
1954                clear,
1955                samples: self.pass_samples(),
1956                viewport: None,
1957            },
1958            sources,
1959            extent: target.extent,
1960        });
1961        // The batch that continues is empty, so it inherits nothing: what
1962        // follows the cut is a full-target `Src` blit, which no sample count
1963        // changes, plus whatever is drawn next. A draw that wants
1964        // multisampling will say so again.
1965        self.anti_alias = false;
1966        let index = self.finished.len() - 1;
1967        self.draw_whole_pass(index, target, target, BlendMode::Src, None);
1968        self.seeded_by_redraw = true;
1969        self.rebuild_stencil_clips();
1970        index
1971    }
1972
1973    /// Make the stencil clips again, in the batch that follows a cut.
1974    ///
1975    /// A stencil clip is a draw and a pass owns its stencil attachment, so
1976    /// cutting the pass throws the clip state away: the redraw restores the
1977    /// color and nothing restores the stencil, leaving every content draw after
1978    /// the cut testing for a depth no pixel holds. Which is to say it draws
1979    /// nothing, silently and everywhere.
1980    ///
1981    /// The narrowings are made again in the order they were made the first
1982    /// time, at the depths they were made at -- which they still are, since
1983    /// `clips` holds exactly those in force and each was made at its own index.
1984    /// A failure to build one is dropped rather than propagated: the shape
1985    /// tessellated once already to get here, and there is no result to fail
1986    /// into halfway through a cut.
1987    fn rebuild_stencil_clips(&mut self) {
1988        for depth in 0..self.clips.len() {
1989            let clip = self.clips[depth].clone();
1990            let paint = RenderPaint {
1991                material: Material::solid([1.0, 1.0, 1.0, 1.0]),
1992                filter: ColorFilter::None,
1993                blend: BlendMode::Src,
1994                clip: clip.scissor,
1995                stencil: ClipState::narrow(depth as u32),
1996            };
1997            let _ = self
1998                .renderer
1999                .fill_into(&mut self.batch, &clip.path, clip.transform, &paint);
2000        }
2001    }
2002
2003    /// Whether a layer is open, which decides what a cut pass clears to.
2004    fn in_layer(&self) -> bool {
2005        self.stack.iter().any(|state| state.layer.is_some())
2006    }
2007
2008    /// Draw a finished pass, sized for `source`, across the whole of `into`.
2009    ///
2010    /// `into` is a rectangle of `source`: the same target when a pass is being
2011    /// redrawn after a cut, and a sub-rectangle of it when a bounded layer is
2012    /// seeded with a backdrop. The mapping is the inverse of the one a layer
2013    /// composite uses, and reduces to the full-texture mapping when the two are
2014    /// the same size, which is what makes the unbounded case share this code.
2015    fn draw_whole_pass(
2016        &mut self,
2017        pass: usize,
2018        source: Target,
2019        into: Target,
2020        blend: BlendMode,
2021        moved_by: Option<Affine2>,
2022    ) {
2023        let slot = self.slot_for(TextureSource::Layer(pass));
2024        let offset = into.origin - source.origin;
2025        let (iw, ih) = (into.extent.width as f32, into.extent.height as f32);
2026        let (sw, sh) = (source.extent.width as f32, source.extent.height as f32);
2027        // Stated in the direction the shader reads it -- clip space to the
2028        // texture -- because the sizes are known and there is no placement to
2029        // invert. The anchor rides inside it like every other paint's.
2030        let anchor = Vec2::new(-1.0 - 2.0 * offset.x / iw, 1.0 + 2.0 * offset.y / ih);
2031        let scale = Mat2::from_diagonal(Vec2::new(0.5 * iw / sw, -0.5 * ih / sh));
2032        let clip_to_texture = Affine2::from_mat2(scale) * Affine2::from_translation(-anchor);
2033        // A matrix moves the image, so the fragment at a device point reads
2034        // where that point came *from*: the mapping gains the inverse, stated
2035        // in device pixels, between the texture coordinates and the device
2036        // position they name. `texels` is that position from a normalized
2037        // coordinate and `normalized` is its inverse, so with no matrix the
2038        // three cancel and this is the mapping above unchanged.
2039        let clip_to_texture = match moved_by {
2040            None => clip_to_texture,
2041            Some(matrix) => {
2042                let texels = Affine2::from_translation(source.origin)
2043                    * Affine2::from_scale(Vec2::new(sw, sh));
2044                let normalized = texels.inverse();
2045                normalized * matrix.inverse() * texels * clip_to_texture
2046            }
2047        };
2048        let material = Material::Image {
2049            to_local: to_local_columns(Transform2D::from(clip_to_texture)),
2050            slot,
2051            alpha: 1.0,
2052            // Clamped when the image stays where it was, which is every case
2053            // but one: the mapping then covers exactly the texture and there is
2054            // nothing outside it to decide about. A matrix leaves parts of the
2055            // target naming no texel, and those have to come out transparent so
2056            // what is underneath shows -- smearing the edge across them is what
2057            // a clamp would do and is not what a filter that moved an image
2058            // says about where the image is not.
2059            tile: [if moved_by.is_some() {
2060                TileMode::Decal
2061            } else {
2062                TileMode::Clamp
2063            }; 2],
2064            // A layer is composited at its own size, so a texel lands on a
2065            // pixel and the filter has nothing to blend. Linear anyway, which
2066            // is what a target scaled by a resize would want.
2067            sampling: Sampling::Linear,
2068            source: [0.0, 0.0, 1.0, 1.0],
2069            tint: [1.0, 1.0, 1.0, 1.0],
2070        };
2071        let paint = RenderPaint {
2072            material,
2073            filter: ColorFilter::None,
2074            blend,
2075            // Neither clipped nor stencilled: this is the target's own content
2076            // being restored or seeded, not something the caller drew, and a
2077            // clip in force belongs to what comes after it.
2078            clip: None,
2079            stencil: ClipState::UNCLIPPED,
2080        };
2081        let whole = into.path();
2082        let _ = self
2083            .renderer
2084            .fill_into(&mut self.batch, &whole, Affine2::IDENTITY, &paint);
2085    }
2086
2087    /// Put the filtered backdrop under the layer's own content.
2088    ///
2089    /// `Src`, because it is the layer's starting image rather than something
2090    /// composited onto it, and the layer's target was cleared to transparent.
2091    fn seed_backdrop(&mut self, pending: Option<Backdrop>) {
2092        let Some(Backdrop {
2093            pass,
2094            of: parent,
2095            moved_by,
2096        }) = pending
2097        else {
2098            return;
2099        };
2100        let into = self.target;
2101        self.draw_whole_pass(pass, parent, into, BlendMode::Src, moved_by);
2102    }
2103
2104    fn push_layer_frame(&mut self, layer: Layer, filter: Option<ImageFilter>) {
2105        self.stack.push(SavedState {
2106            transform: self.transform,
2107            clip: self.clip,
2108            clip_bounds: self.clip_bounds,
2109            depth: self.depth,
2110            clips: self.clips.len(),
2111            layer: Some(LayerFrame {
2112                batch: std::mem::take(&mut self.batch),
2113                sources: std::mem::take(&mut self.sources),
2114                clips: std::mem::take(&mut self.clips),
2115                paint: layer,
2116                filter,
2117                parent: self.target,
2118                anti_alias: std::mem::take(&mut self.anti_alias),
2119                seeded_by_redraw: std::mem::take(&mut self.seeded_by_redraw),
2120                blur_basis: BlurBasis::of(self.transform),
2121            }),
2122        });
2123        self.clip = None;
2124        self.depth = 0;
2125    }
2126
2127    /// Open a layer that only needs to cover `bounds`.
2128    ///
2129    /// `bounds` is in the current user space, and is the caller's promise that
2130    /// nothing drawn in the layer matters outside it. The layer gets a target
2131    /// the size of that region rather than the size of the frame, which is the
2132    /// whole reason to state it: a layer over a tenth of the frame then costs a
2133    /// tenth of the memory and a tenth of the fill, and a frame that opens
2134    /// several stops being dominated by full-frame allocations it does not use.
2135    ///
2136    /// The promise is enforced by construction rather than trusted. Content
2137    /// outside the region is clipped away by the target's own edges, so a
2138    /// caller who understates the bounds sees the drawing cut off — visible and
2139    /// attributable, rather than reading stale memory.
2140    ///
2141    /// The region is taken to device pixels and rounded outward to whole ones,
2142    /// so a fractional bound never costs coverage at the edge, and is narrowed
2143    /// to what the enclosing target can show, since a layer larger than that
2144    /// renders pixels nothing can sample. A region that comes out empty falls
2145    /// back to a full-size layer, that being a case where a smaller target
2146    /// would be a guess and guessing wrong loses drawing.
2147    ///
2148    /// A layer that filters its backdrop is the exception to all of this: for
2149    /// it the bounds are not an optimization but the region filtered, so
2150    /// omitting them filters the whole target rather than merely allocating
2151    /// more of one. See [`Layer::backdrop_blur`].
2152    ///
2153    /// Under a rotation the region becomes a quadrilateral, and the target is
2154    /// the box around it. That covers more than the caller promised, which is
2155    /// the safe direction: a target is an allocation rather than a clip the
2156    /// caller can observe, so over-covering costs a little memory where
2157    /// under-covering would lose drawing. This is the opposite of what
2158    /// [`Self::clip_rect`] does with the same box, and for the same reason —
2159    /// there the box would admit pixels the caller asked to remove.
2160    pub fn save_layer_bounds(&mut self, layer: Layer, bounds: Rect) -> &mut Self {
2161        let (min, max) = transformed_bounds(
2162            self.transform,
2163            Vec2::new(bounds.left, bounds.top),
2164            Vec2::new(bounds.right, bounds.bottom),
2165        )
2166        .unwrap_or_else(unbounded);
2167        self.save_layer_device_bounds(layer, min, max)
2168    }
2169
2170    /// A layer filtered as a whole by any image filter.
2171    ///
2172    /// [`Layer`]'s own fields carry the four kinds that fit in a `Copy` struct
2173    /// -- a blur, a morphology, a matrix and a color filter -- and apply them
2174    /// in one fixed order. This takes an [`ImageFilter`], which adds the two
2175    /// they cannot say: a caller's fragment program, and a composition in
2176    /// whichever order the caller wrote it.
2177    ///
2178    /// The same operation `dart:ui` spells as an `imageFilter` on the paint
2179    /// handed to `saveLayer`, and the group counterpart of what
2180    /// `Paint::with_image_filter` already does for one draw.
2181    ///
2182    /// Refuses a matrix, which is a redirection rather than an absence: a
2183    /// group's finished image is moved by `Layer::with_matrix`, which states
2184    /// the same thing and is what `peel` turns this filter into everywhere
2185    /// else. Refused here rather than at `restore`, because a `restore` has no
2186    /// result to fail into and by then the caller has drawn into the layer.
2187    ///
2188    /// A *backdrop's* matrix is not refused; see `backdrop_pass`. The two are
2189    /// different questions -- a group's own image is composited by machinery
2190    /// that already takes a matrix, and a backdrop's is seeded by a draw that
2191    /// now does.
2192    pub fn save_layer_filtered(
2193        &mut self,
2194        layer: Layer,
2195        bounds: Option<Rect>,
2196        filter: &ImageFilter,
2197    ) -> Result<&mut Self> {
2198        if matches!(filter, ImageFilter::Matrix { .. }) {
2199            return Err(Error::Unsupported(
2200                "a matrix filters a group through `Layer::with_matrix`, which \
2201                 states where the finished image goes",
2202            ));
2203        }
2204        // Refused here for the reason the depth is a constant at all: everything
2205        // that reads a composition walks it recursively, and a composition deep
2206        // enough took the process down rather than returning an error. See
2207        // `ImageFilter::MAX_NESTING`.
2208        if filter.nests_deeper_than(ImageFilter::MAX_NESTING) {
2209            return Err(Error::Unsupported(
2210                "this image filter composes more filters than can be walked",
2211            ));
2212        }
2213        let (min, max) = match bounds {
2214            Some(bounds) => transformed_bounds(
2215                self.transform,
2216                Vec2::new(bounds.left, bounds.top),
2217                Vec2::new(bounds.right, bounds.bottom),
2218            )
2219            .unwrap_or_else(unbounded),
2220            None => unbounded(),
2221        };
2222        self.save_layer_device_bounds_running(layer, min, max, Some(filter.clone()), None)
2223    }
2224
2225    /// A layer over a backdrop filtered by any image filter.
2226    ///
2227    /// [`Layer::backdrop_blur`] is the same operation with the one filter a
2228    /// `Copy` layer can hold, and is the spelling to reach for when a blur is
2229    /// what is wanted. This takes the rest: a color filter, a morphology, a
2230    /// caller's fragment program, or a composition of them -- which is what
2231    /// `SceneBuilder.pushBackdropFilter` accepts and what upstream's
2232    /// `SaveLayer` takes a `DlImageFilter` for.
2233    ///
2234    /// The bounds are the filtered region rather than an optimization, for the
2235    /// reason [`Layer::backdrop_blur`] gives: a frosted panel is a bounded
2236    /// layer, and the same layer unbounded filters the whole frame. Both are
2237    /// meaningful and they are different pictures.
2238    ///
2239    /// Refuses a matrix, which is the one kind that moves the image rather than
2240    /// recomputing it in place. See `filter_passes`.
2241    pub fn save_layer_backdrop(
2242        &mut self,
2243        layer: Layer,
2244        bounds: Option<Rect>,
2245        backdrop: &ImageFilter,
2246    ) -> Result<&mut Self> {
2247        // The same refusal `save_layer_filtered` makes, and for the same reason:
2248        // a backdrop's filter is read by the same recursive walks.
2249        if backdrop.nests_deeper_than(ImageFilter::MAX_NESTING) {
2250            return Err(Error::Unsupported(
2251                "this image filter composes more filters than can be walked",
2252            ));
2253        }
2254        let (min, max) = match bounds {
2255            Some(bounds) => transformed_bounds(
2256                self.transform,
2257                Vec2::new(bounds.left, bounds.top),
2258                Vec2::new(bounds.right, bounds.bottom),
2259            )
2260            .unwrap_or_else(unbounded),
2261            None => unbounded(),
2262        };
2263        self.save_layer_device_bounds_running(layer, min, max, None, Some(backdrop))
2264    }
2265
2266    /// A bounded layer whose region is already in device pixels.
2267    ///
2268    /// The same thing [`Self::save_layer_bounds`] does, minus the transform.
2269    /// Every filter's reach is a length in device pixels, so a caller that has
2270    /// already worked out where a filtered result will land -- which composing
2271    /// two filters requires, since the inner one's growth has to fit inside the
2272    /// outer one's target -- has device coordinates in hand and would only be
2273    /// mapping them backward to have them mapped forward again. Under a scale
2274    /// the round trip is not the identity: a reach of eight device pixels
2275    /// divided by the scale and multiplied by it again is eight only if nothing
2276    /// rounds, and the bounds are floored and ceiled at the end.
2277    fn save_layer_device_bounds(&mut self, layer: Layer, min: Vec2, max: Vec2) -> &mut Self {
2278        // Cannot fail: only a backdrop filter can refuse, and this passes none.
2279        let _ = self.save_layer_device_bounds_running(layer, min, max, None, None);
2280        self
2281    }
2282
2283    /// The same, with a caller's program to run over the finished layer.
2284    ///
2285    /// Separate rather than a defaulted argument because every caller but the
2286    /// three filtered draws passes `None`, and a parameter that is almost
2287    /// always one value reads as though it were sometimes the other.
2288    fn save_layer_device_bounds_running(
2289        &mut self,
2290        layer: Layer,
2291        min: Vec2,
2292        max: Vec2,
2293        filter: Option<ImageFilter>,
2294        backdrop: Option<&ImageFilter>,
2295    ) -> Result<&mut Self> {
2296        // A caller's sigma is in the space they were drawing in, which is what
2297        // `dart:ui` means by it and what upstream honors -- its
2298        // `GaussianBlurFilterContents` scales by `effect_transform.Basis()`,
2299        // and the backdrop path hands it `transform.Basis()`. Everything below
2300        // this line works in device pixels: the reach is applied to bounds
2301        // already transformed, and the passes that do the blurring run on a
2302        // target. So the conversion happens once, here, where the transform
2303        // that decides it is still the one the caller drew under.
2304        let basis = BlurBasis::of(self.transform);
2305        let scale = max_scale_of(self.transform);
2306        let axes = axis_scales_of(self.transform);
2307        let layer = layer.scaled_by(scale, axes);
2308        // And the filters beside it, which this line did not touch for as long as
2309        // it has existed. The comment above said the conversion happens once here
2310        // and it happened to the layer only, so `save_layer_filtered` with a blur
2311        // took a device sigma while the same filter through
2312        // `Paint::with_image_filter` -- which becomes a layer -- took a local one.
2313        let filter = filter.map(|filter| filter.scaled_by(scale, axes));
2314        let backdrop = backdrop
2315            .cloned()
2316            .map(|filter| filter.scaled_by(scale, axes));
2317        let backdrop = backdrop.as_ref();
2318        let reach = layer.reach(basis);
2319        // A layer opened under a clip cannot draw outside it, and neither can
2320        // the draw that composites it, so an unbounded one does not need a
2321        // target the size of its parent. A frosted panel is the case that
2322        // pays: the clip is the panel and the parent is the frame, and the
2323        // capture, the blur's passes and the intermediate were all frame-sized
2324        // for a panel a fortieth of the area.
2325        //
2326        // Only where a backdrop is being captured, and only for a layer that
2327        // shares no key and has no matrix. Each of those wants a region this
2328        // does not know how to compute: a shared capture has to cover every
2329        // group naming the id -- which is upstream's coverage union and is not
2330        // this -- a matrix records its pre-image, which is where the content
2331        // will come *from* rather than where the clip is, and a destructive
2332        // group naming the id -- which is upstream's coverage union and is not
2333        // this -- and a matrix records its pre-image, which is where the
2334        // content will come *from* rather than where the clip is.
2335        //
2336        // A destructive mode is not excluded, and the difference from
2337        // `narrowed` is the whole of why. That one shrinks to the layer's
2338        // *content*, which such a mode reaches past -- it writes where the
2339        // source drew nothing. This shrinks to the clip, which is the region
2340        // the composite can touch at all, so there is nothing outside it left
2341        // to affect.
2342        let captures_backdrop = backdrop.is_some() || layer.backdrop_blur > 0.0;
2343        let (min, max) = if captures_backdrop && layer.matrix.is_none() {
2344            let clip = self.clip_bounds;
2345            (
2346                Vec2::new(min.x.max(clip.left), min.y.max(clip.top)),
2347                Vec2::new(max.x.min(clip.right), max.y.min(clip.bottom)),
2348            )
2349        } else {
2350            (min, max)
2351        };
2352        // A filter given to the layer as a whole reaches past what it is handed
2353        // too, and by how much only the filter knows. Asked here rather than
2354        // left to the narrowing below, because the narrowing only runs for a
2355        // layer that was *not* given bounds: a caller who states bounds gets
2356        // the target those bounds describe, and a filter's spread has to be
2357        // added to it or the spread is cut off at the bound.
2358        //
2359        // Missing this made the two spellings of a layer blur disagree. A sigma
2360        // on the layer went through `reach` above and spread ten pixels past a
2361        // stated bound; the same blur handed over as the layer's filter stopped
2362        // dead at it. They are the same picture and the same comment two
2363        // functions up says so.
2364        let filter_reach = filter.as_ref().map(|filter| {
2365            let unit = Vec2::ZERO;
2366            let (min, max) = filter.covering(unit, unit, &|sigma| basis.reach(sigma));
2367            (-min).max(max)
2368        });
2369        // A blur reaches past what it was given. The caller states where the
2370        // content is, which is the question they can answer; how far a blur
2371        // carries it is this renderer's arithmetic, and a target sized to the
2372        // content alone would cut the halo off square at the bound -- the
2373        // failure looking exactly like a shadow with a straight edge.
2374        //
2375        // The kernel's own radius, `ceil((sigma - 0.5) * sqrt(3))`, which is
2376        // where the shader stops taking taps -- so the target covers every
2377        // texel the blur will actually read and no more. Nearer one and three
2378        // quarter deviations than three: the truncation is upstream's
2379        // `kKernelRadiusPerSigma`, and `blur_reach` is the one place it is
2380        // stated.
2381        let (min, max) = (min - reach, max + reach);
2382        // After the layer's own blur and morphology, because that is the order
2383        // `finish_layer` applies them in: the filter sees what those produced.
2384        let (min, max) = match filter_reach {
2385            Some(spread) => (min - spread, max + spread),
2386            None => (min, max),
2387        };
2388        let parent = self.target;
2389        let left = min.x.floor().max(parent.origin.x);
2390        let top = min.y.floor().max(parent.origin.y);
2391        let right = max
2392            .x
2393            .ceil()
2394            .min(parent.origin.x + parent.extent.width as f32);
2395        let bottom = max
2396            .y
2397            .ceil()
2398            .min(parent.origin.y + parent.extent.height as f32);
2399        // Worked out before the layer is opened, because opening it is what
2400        // builds the backdrop's passes and those want to know where they are
2401        // writing. The layer is still opened without *seeding*: the seed has to
2402        // land in the target the content will draw into, so it waits until that
2403        // target is the one aimed at.
2404        let narrowed = (right > left && bottom > top).then(|| Target {
2405            origin: Vec2::new(left, top),
2406            extent: Extent2D::new((right - left) as u32, (bottom - top) as u32),
2407        });
2408        let pending = self.open_layer(layer, filter, backdrop, narrowed)?;
2409        let Some(target) = narrowed else {
2410            // Nothing survived the clamp, so the layer keeps the full-size
2411            // target it was opened with and the backdrop is seeded across that.
2412            self.seed_backdrop(pending);
2413            return Ok(self);
2414        };
2415        self.aim_at(target);
2416        self.seed_backdrop(pending);
2417        Ok(self)
2418    }
2419
2420    /// How many layers are open, for a caller checking its own balance.
2421    pub fn layer_depth(&self) -> usize {
2422        self.stack.iter().filter(|s| s.layer.is_some()).count()
2423    }
2424
2425    /// The slot a source occupies in the pass being recorded, adding it if new.
2426    ///
2427    /// Slots are per pass rather than global, because each pass carries its own
2428    /// table. Deduplicating means a recording that draws the same image twenty
2429    /// times binds one texture rather than twenty.
2430    /// The slot holding this gradient's colors, when they cannot be carried.
2431    ///
2432    /// `None` for the ordinary case, which keeps the stops in push constants
2433    /// and costs no texture, no upload and no binding. Only a gradient with
2434    /// more stops than a material can hold pays for a ramp, and it pays once
2435    /// per distinct gradient rather than once per draw.
2436    fn ramp_for(&mut self, stops: &[GradientStop]) -> Option<u32> {
2437        (stops.len() > MAX_STOPS).then(|| self.ramp_slot(stops))
2438    }
2439
2440    /// Tabulate a gradient's colors and return the slot holding them.
2441    ///
2442    /// Called only where the stops outnumber what a material can carry. The
2443    /// ramp is deduplicated across the recording by its contents, because the
2444    /// same gradient drawn twice is one texture, and a frame that paints a
2445    /// hundred list rows with one theme gradient should upload it once.
2446    fn ramp_slot(&mut self, stops: &[GradientStop]) -> u32 {
2447        let ramp = Ramp::bake(stops);
2448        let index = match self.ramps.iter().position(|r| *r == ramp) {
2449            Some(index) => index,
2450            None => {
2451                self.ramps.push(ramp);
2452                self.ramps.len() - 1
2453            }
2454        };
2455        self.slot_for(TextureSource::Ramp(index))
2456    }
2457
2458    fn slot_for(&mut self, source: TextureSource) -> u32 {
2459        if let Some(index) = self.sources.iter().position(|s| *s == source) {
2460            return index as u32;
2461        }
2462        self.sources.push(source);
2463        (self.sources.len() - 1) as u32
2464    }
2465
2466    /// Return to the most recently saved transform and clip.
2467    ///
2468    /// Restoring without a matching save leaves both alone rather than
2469    /// panicking: an unbalanced pair is a caller bug, but taking down a frame
2470    /// loop for it is worse than continuing with what is already correct.
2471    pub fn restore(&mut self) -> &mut Self {
2472        let Some(previous) = self.stack.pop() else {
2473            return self;
2474        };
2475        self.transform = previous.transform;
2476        self.clip = previous.clip;
2477        self.clip_bounds = previous.clip_bounds;
2478
2479        if let Some(frame) = previous.layer {
2480            // The clip and stencil are restored before the composite is
2481            // recorded, so the layer arrives subject to what was in force when
2482            // it was opened rather than to whatever it did inside itself.
2483            self.depth = previous.depth;
2484            self.clips = frame.clips.clone();
2485            self.finish_layer(frame);
2486            return self;
2487        }
2488
2489        // Everything this save added to the list goes with it. The widening
2490        // draws below undo the same clips on the device; this is the record of
2491        // them a later pass cut would rebuild from.
2492        self.clips.truncate(previous.clips);
2493
2494        // A scissor is state the recorder holds, so restoring it is an
2495        // assignment. A stencil clip lives in a buffer on the device, so
2496        // restoring it is a draw: one covering the whole target per level being
2497        // left, each stepping back the pixels that reached that level.
2498        //
2499        // Deliberately unscissored. The step back lands exactly where the
2500        // matching narrowing landed, because that is where the stencil holds
2501        // the value being tested for -- so it needs no help from a scissor, and
2502        // asking it to agree with one that has already been restored to
2503        // something else would be a way to get it wrong.
2504        if self.depth > previous.depth {
2505            // Stated in device pixels, so it goes through the identity rather
2506            // than whatever transform happens to be in force.
2507            let whole = self.target.path();
2508            while self.depth > previous.depth {
2509                let paint = RenderPaint {
2510                    material: Material::solid([1.0, 1.0, 1.0, 1.0]),
2511                    filter: ColorFilter::None,
2512                    blend: BlendMode::Src,
2513                    clip: None,
2514                    stencil: ClipState::widen(self.depth),
2515                };
2516                let _ = self
2517                    .renderer
2518                    .fill_into(&mut self.batch, &whole, Affine2::IDENTITY, &paint);
2519                self.depth -= 1;
2520            }
2521        }
2522        self
2523    }
2524
2525    /// How many saves are outstanding, for a caller checking its own balance.
2526    pub fn save_depth(&self) -> usize {
2527        self.stack.len()
2528    }
2529
2530    pub fn translate(&mut self, x: f32, y: f32) -> &mut Self {
2531        self.concat(Affine2::from_translation(Vec2::new(x, y)))
2532    }
2533
2534    pub fn scale(&mut self, x: f32, y: f32) -> &mut Self {
2535        self.concat(Affine2::from_scale(Vec2::new(x, y)))
2536    }
2537
2538    /// Rotate by an angle in radians.
2539    pub fn rotate(&mut self, radians: f32) -> &mut Self {
2540        self.concat(Affine2::from_angle(radians))
2541    }
2542
2543    /// Apply an arbitrary transform on top of the current one.
2544    ///
2545    /// Takes anything that is a transform of the plane, which is an `Affine2`
2546    /// for almost every caller and a [`Transform2D`] for one that wants
2547    /// perspective. Widened rather than replaced: nobody should have to build a
2548    /// three-by-three to move something ten pixels to the right.
2549    pub fn concat(&mut self, transform: impl Into<Transform2D>) -> &mut Self {
2550        self.transform = self.transform * transform.into();
2551        self
2552    }
2553
2554    /// Apply a `dart:ui` four-by-four, which is column-major and sixteen long.
2555    ///
2556    /// The entry point for perspective, and the one `dart:ui` states: its
2557    /// `Canvas.transform` takes a matrix of this shape. Named apart from
2558    /// [`Self::transform`], which reports the current one and cannot share a
2559    /// name with a method that changes it.
2560    ///
2561    /// The reduction to a three-by-three is exact rather than a narrowing.
2562    /// Everything drawn here lies on the plane where `z` is zero, and a
2563    /// four-by-four applied to such a point never reads its `z` column; the `z`
2564    /// row yields a depth with nothing to do here. What is left -- rows and
2565    /// columns zero, one and three -- is the whole of what the matrix means on
2566    /// the plane. A caller whose matrix depends on `z` is getting the part of
2567    /// it that acts on what they are drawing, which is all of it.
2568    pub fn concat_4x4(&mut self, matrix: &[f32; 16]) -> &mut Self {
2569        self.concat(Transform2D::from_column_major_4x4(matrix))
2570    }
2571
2572    pub fn draw_path(&mut self, path: &Path, paint: &Paint) -> Result<&mut Self> {
2573        self.prepare_destination(paint.blend);
2574        if !paint.is_visible() || path.is_empty() {
2575            return Ok(self);
2576        }
2577        // Before the mask blur, so the two compose in the order they are
2578        // defined in: an image filter acts on what was drawn, and what was
2579        // drawn is whatever the mask blur produced.
2580        if !paint.image_filter.is_identity() {
2581            return self.draw_filtered(path, paint);
2582        }
2583        // A rounded rectangle that still knows it is one can have its mask blur
2584        // evaluated rather than run as passes. This is where a shadow arrives:
2585        // `draw_shadow` takes a path, as `dart:ui`'s `drawShadow` does, so
2586        // without the shape traveling with the outline every shadow would take
2587        // the general route however round it is.
2588        if let Some((bounds, radius)) = path.as_rounded_rect() {
2589            let rect = Rect::new(bounds.min.x, bounds.min.y, bounds.max.x, bounds.max.y);
2590            if let Some((material, pad, drawn)) = self.analytic_rrect_blur_draw(rect, radius, paint)
2591            {
2592                return self.draw_analytic(rect.outset(pad), material, &drawn);
2593            }
2594        }
2595        // A color filter is normally arithmetic in this renderer's own fragment
2596        // shader, which a runtime effect replaces outright -- there is nowhere
2597        // in a caller's program to put the matrix, and the program is what runs.
2598        // Left alone, the filter was accepted and silently did nothing, which
2599        // is the shape of failure this codebase least wants: no error, no
2600        // effect, and a caller with no way to tell.
2601        //
2602        // So the filter is applied to the image the program drew instead, which
2603        // is what it means anyway. It costs a layer, which is what every other
2604        // filter that acts on a finished image already costs.
2605        if matches!(paint.shader, Shader::RuntimeEffect { .. }) && !paint.color_filter.is_identity()
2606        {
2607            return self.draw_effect_filtered(path, paint);
2608        }
2609        if paint.mask_blur > 0.0 {
2610            if let Some(drawn) = self.shadow_mesh_blur(path, paint) {
2611                return drawn.map(|()| self);
2612            }
2613            return self.draw_masked(Masked::Path(path), paint);
2614        }
2615        if paint.anti_alias {
2616            self.anti_alias = true;
2617        }
2618
2619        // A clip narrowed to nothing means this shape cannot reach any pixel.
2620        // Tessellating it to find that out is wasted work, and it is a normal
2621        // state rather than an error: a subtree scrolled out of view is clipped
2622        // away every frame it stays there.
2623        if self.clip.is_some_and(Scissor::is_empty) {
2624            return Ok(self);
2625        }
2626
2627        // Upstream tries its vertex-interpolated gradient first, and so does
2628        // this: `LinearGradientContents::Render` calls `CanApplyFastGradient`
2629        // before reaching the uniform walk. Here rather than in `draw_rect`
2630        // because everything above has to run first -- a mask blur or a
2631        // runtime-effect filter takes its own route, and the first attempt at
2632        // this path intercepted earlier and drew a masked shape sharp and
2633        // unmasked. §19 of `docs/non-parity.md` records that.
2634        //
2635        // The shape has to be a rectangle recorded as one, which `draw_rect`
2636        // and a zero-radius `draw_rrect` do and an arbitrary path with four
2637        // corners does not: the predicate needs the rectangle's edges, and a
2638        // path that happens to trace them has not said they are edges.
2639        if matches!(paint.style, Style::Fill) {
2640            if let Some((rect, 0.0)) = path.as_rounded_rect() {
2641                let rect = Rect::new(rect.min.x, rect.min.y, rect.max.x, rect.max.y);
2642                // Only where the gradient is in the rectangle's own space:
2643                // the sections run along the rectangle's edges.
2644                let sections = (paint.shader_transform == Transform2D::IDENTITY)
2645                    .then(|| fast_gradient_sections(rect, &paint.effective_shader()))
2646                    .flatten();
2647                if let Some(sections) = sections {
2648                    return self.draw_gradient_sections(&sections, paint);
2649                }
2650            }
2651        }
2652
2653        // Resolved before the clip is read, since it may add a slot to this
2654        // pass's table.
2655        let material = self.material_for(paint);
2656        // A stroke too thin to cover a pixel is widened to one and dimmed to
2657        // pay for it. See `thin_stroke`; this is the tessellated route, where
2658        // the quantization it exists for is at its worst -- coverage comes
2659        // from a multisample buffer, so a sub-pixel line has four coverages
2660        // available to it and one of them is none.
2661        let (style, coverage) = match &paint.style {
2662            Style::Stroke(stroke) => {
2663                let (width, coverage) =
2664                    thin_stroke(self.transform, stroke.width, Zero::IsAHairline);
2665                (Style::Stroke(stroke.with_width(width)), coverage)
2666            }
2667            other => (*other, 1.0),
2668        };
2669        let render_paint = RenderPaint {
2670            material: material.with_opacity(coverage),
2671            filter: paint.color_filter,
2672            blend: paint.blend,
2673            clip: self.clip,
2674            stencil: ClipState::content(self.depth),
2675        };
2676        match &style {
2677            Style::Fill => {
2678                self.renderer
2679                    .fill_into(&mut self.batch, path, self.transform, &render_paint)?
2680            }
2681            Style::Stroke(stroke) => self.renderer.stroke_into(
2682                &mut self.batch,
2683                path,
2684                stroke,
2685                paint.dash.as_ref(),
2686                self.transform,
2687                &render_paint,
2688            )?,
2689        }
2690        Ok(self)
2691    }
2692
2693    /// Draw a gradient as one quad per pair of stops, letting the rasterizer
2694    /// interpolate between them.
2695    ///
2696    /// The material shades opaque white and the vertex colors carry the result
2697    /// under `Modulate`, which is the identity against white -- the arrangement
2698    /// `draw_vertices` already uses for a caller's mesh. What `VertexGradient`
2699    /// adds over `Solid` is that it dithers, which is the whole of why it is a
2700    /// material of its own: a long run of nearly equal values bands on an
2701    /// eight-bit target whichever stage produced it.
2702    ///
2703    /// One push per section rather than one for all of them, so each quad's six
2704    /// indices address its own four vertices -- which is also what lets
2705    /// `BatchDraw::covered` recognize a section, and what makes the batch's own
2706    /// merging decide whether they coalesce.
2707    fn draw_gradient_sections(
2708        &mut self,
2709        sections: &[GradientSection],
2710        paint: &Paint,
2711    ) -> Result<&mut Self> {
2712        let to_clip = self.target.projection() * self.transform;
2713        for section in sections {
2714            let vertices: Vec<Vertex> = section
2715                .corners
2716                .iter()
2717                .zip(&section.colors)
2718                .map(|(position, color)| {
2719                    let clip = to_clip.project_homogeneous(*position);
2720                    Vertex::projected([clip.x, clip.y, clip.z], [0.0, 0.0]).with_color(*color)
2721                })
2722                .collect();
2723            self.batch.push_mesh_tinted(
2724                &vertices,
2725                // Two triangles sharing the diagonal from corner zero to corner
2726                // two, which is the winding `fan_fill` emits for a quad and what
2727                // `BatchDraw::covered` matches against.
2728                &[0, 1, 2, 0, 2, 3],
2729                Material::VertexGradient,
2730                paint.color_filter,
2731                paint.blend,
2732                self.clip,
2733                ClipState::content(self.depth),
2734                paint.tint_blend,
2735                // The section colors carry the paint's opacity already.
2736                1.0,
2737                // The color comes from the vertices, not from a coordinate, so
2738                // there is nothing for the material to read a position for.
2739                false,
2740            )?;
2741        }
2742        Ok(self)
2743    }
2744
2745    /// Resolve a paint's shader against the current transform.
2746    ///
2747    /// Gradient endpoints go through the same mapping the geometry does, so a
2748    /// gradient rotates and scales with its shape rather than staying fixed to
2749    /// the screen. Doing it here rather than in the fragment stage means the
2750    /// shader receives clip-space endpoints and needs no transform of its own.
2751    ///
2752    /// The paint's [`Paint::shader_transform`] comes first, from the shader's
2753    /// space into the canvas's, so it is folded into the same one mapping and
2754    /// costs the fragment stage nothing.
2755    fn material_for(&mut self, paint: &Paint) -> Material {
2756        let to_clip = self.target.projection() * self.transform * paint.shader_transform;
2757        self.material_from(&paint.effective_shader(), to_clip)
2758    }
2759
2760    /// The same, for a draw whose fragments locate themselves some other way.
2761    ///
2762    /// A mesh that states a coordinate per vertex has already put each one in
2763    /// the caller's own space, so the mapping the fragment stage applies must
2764    /// not carry the geometry's transform as well -- it would be applied twice,
2765    /// once by the vertices and once by the mapping. Passing the identity here
2766    /// leaves exactly the paint's own part: the translation that measures from
2767    /// a gradient's start, the rotation that orients a sweep, and nothing else.
2768    ///
2769    /// The shader then runs the same arithmetic on `(uv, 1)` that it runs on a
2770    /// clip position, which is why there is one path in it rather than two.
2771    ///
2772    /// The shader's own transform stays: the coordinates are in the space
2773    /// the paint is used in, and it carries the shader's space into that.
2774    fn material_at_texture_coords(&mut self, paint: &Paint) -> Material {
2775        self.material_from(&paint.effective_shader(), paint.shader_transform)
2776    }
2777
2778    fn material_from(&mut self, shader: &Shader, to_clip: Transform2D) -> Material {
2779        let stops_of = |stops: &[crate::paint::GradientStop]| -> Vec<Stop> {
2780            stops
2781                .iter()
2782                .map(|s| Stop::new(s.color.to_array(), s.offset))
2783                .collect()
2784        };
2785
2786        match shader {
2787            Shader::Solid(color) => Material::solid(color.to_array()),
2788            // Passed through untouched. Every other material here is resolved
2789            // -- geometry carried into clip space, a radius folded into a
2790            // matrix -- because this renderer's own shader expects it that
2791            // way. A caller's program expects whatever the caller wrote, and
2792            // there is nothing here that could resolve it correctly.
2793            Shader::RuntimeEffect {
2794                program,
2795                uniforms,
2796                images,
2797            } => Material::Runtime {
2798                program: *program,
2799                uniforms: uniforms.clone(),
2800                // Through this pass's own table, like every other texture: a
2801                // layer occupies a slot too, so a caller's index and the
2802                // pass's are not the same number once one is opened.
2803                textures: {
2804                    let mut bound = [None; emblema_hal::MAX_EFFECT_TEXTURES];
2805                    // Past the ceiling the extra names are dropped rather than
2806                    // refused: a program cannot declare a binding the layout
2807                    // does not have, so a caller naming more textures than that
2808                    // has named some the program could not read either.
2809                    for (slot, into) in images.iter().zip(bound.iter_mut()) {
2810                        *into = Some(self.slot_for(TextureSource::Image(*slot)));
2811                    }
2812                    bound
2813                },
2814            },
2815            Shader::Image {
2816                slot,
2817                rect,
2818                alpha,
2819                tile,
2820                source,
2821                tint,
2822                sampling,
2823            } => {
2824                // Texture coordinates run from zero to one across the
2825                // destination rectangle, so the mapping is: undo the transform
2826                // that took user space to clip space, then scale by the
2827                // rectangle's own size. Composing the two here means the shader
2828                // receives one matrix and does no inversion of its own.
2829                //
2830                // Built forwards and inverted once: the unit square of texture
2831                // coordinates is scaled by the rectangle's size, placed at its
2832                // corner, and carried to clip space by the transform in force.
2833                // A degenerate transform has no inverse to take, and the
2834                // identity stands in for it -- unobservable, because the
2835                // geometry went through the same matrix and has no area.
2836                let placement = to_clip
2837                    * Affine2::from_translation(Vec2::new(rect.left, rect.top))
2838                    * Affine2::from_scale(Vec2::new(
2839                        rect.right - rect.left,
2840                        rect.bottom - rect.top,
2841                    ));
2842                Material::Image {
2843                    to_local: invert_to_local(placement),
2844                    sampling: *sampling,
2845                    // The caller's index goes through this pass's own table,
2846                    // because a layer occupies a slot too and the two number
2847                    // independently. A recording that never uses a layer maps
2848                    // them one to one, which is why this is invisible until it
2849                    // is not.
2850                    slot: self.slot_for(TextureSource::Image(*slot)),
2851                    alpha: *alpha,
2852                    source: [source.left, source.top, source.right, source.bottom],
2853                    tint: tint.to_array(),
2854                    tile: *tile,
2855                }
2856            }
2857            Shader::LinearGradient {
2858                start,
2859                end,
2860                stops,
2861                tile,
2862            } => {
2863                let axis = *end - *start;
2864                if !axis.is_finite() || !start.is_finite() {
2865                    return Material::Solid([0.0; 4]);
2866                }
2867                let ramp_slot = self.ramp_for(stops);
2868                Material::LinearGradient {
2869                    axis: [axis.x, axis.y],
2870                    // Maps a clip-space position back into the space the axis is
2871                    // stated in, which is the caller's, measured from the
2872                    // gradient's start. Without it the target's aspect ratio
2873                    // leaks into the gradient's direction.
2874                    to_local: invert_to_local(to_clip * Affine2::from_translation(*start)),
2875                    stops: stops_of(stops),
2876                    tile: *tile,
2877                    ramp: ramp_slot,
2878                }
2879            }
2880            Shader::RadialGradient {
2881                center,
2882                radius,
2883                stops,
2884                tile,
2885            } => {
2886                // Folding the center and the radius into the mapping means the
2887                // shader measures against unit distance from the origin and
2888                // never sees either.
2889                let placement = to_clip
2890                    * Affine2::from_translation(*center)
2891                    * Affine2::from_scale(Vec2::splat(*radius));
2892                if !placement.is_finite() {
2893                    return Material::Solid([0.0; 4]);
2894                }
2895                // A radius of nothing folds to a singular mapping, and the
2896                // inversion below answers a singular matrix with the identity.
2897                // That is the right answer for an inversion and the wrong one
2898                // here: it invents a radius of one clip unit, so a gradient the
2899                // caller asked to have no extent comes out spanning half the
2900                // target and changing with the target's size.
2901                //
2902                // What it should be is the limit of the real thing. As the
2903                // radius shrinks, every point but the center runs off the end
2904                // of the ramp -- so under clamp it settles on the last stop,
2905                // and under decal it leaves, because past the end is where
2906                // decal draws nothing. Repeat and mirror have no limit at all,
2907                // the parameter oscillating faster and faster, and they take
2908                // the same answer as clamp because a stable color is worth
2909                // more than an arbitrary one that shimmers.
2910                //
2911                // The limit rather than a refusal, on the same reasoning that
2912                // makes a mask blur of zero the sharp shape: a caller animating
2913                // a radius down to nothing should arrive somewhere, not have
2914                // the gradient disappear at the last frame.
2915                if !radius.is_finite() || *radius <= 0.0 {
2916                    if matches!(tile, TileMode::Decal) {
2917                        return Material::Solid([0.0; 4]);
2918                    }
2919                    let last = stops
2920                        .iter()
2921                        .max_by(|a, b| a.offset.total_cmp(&b.offset))
2922                        .map(|s| s.color.to_array())
2923                        .unwrap_or([0.0; 4]);
2924                    return Material::solid(last);
2925                }
2926                let ramp_slot = self.ramp_for(stops);
2927                Material::RadialGradient {
2928                    to_local: invert_to_local(placement),
2929                    stops: stops_of(stops),
2930                    tile: *tile,
2931                    ramp: ramp_slot,
2932                }
2933            }
2934            Shader::ConicalGradient {
2935                start_center,
2936                start_radius,
2937                end_center,
2938                end_radius,
2939                stops,
2940                tile,
2941            } => {
2942                let axis = *end_center - *start_center;
2943                // The shader is told where the second center is with one float
2944                // instead of two, which is only possible if it already knows
2945                // the direction. Rotating the gradient's space so the axis
2946                // runs along +X is how it comes to know it, and the rotation
2947                // costs nothing: it folds into a matrix that has to be built
2948                // and inverted regardless.
2949                //
2950                // A zero axis leaves the angle undefined and the rotation
2951                // arbitrary, which is correct rather than merely harmless --
2952                // two concentric circles have no direction to preserve, and
2953                // every rotation is the right one.
2954                let angle = if axis == Vec2::ZERO {
2955                    0.0
2956                } else {
2957                    axis.y.atan2(axis.x)
2958                };
2959                let oriented =
2960                    to_clip * Affine2::from_translation(*start_center) * Affine2::from_angle(angle);
2961                if !oriented.is_finite() || !start_radius.is_finite() || !end_radius.is_finite() {
2962                    return Material::Solid([0.0; 4]);
2963                }
2964                let ramp_slot = self.ramp_for(stops);
2965                Material::ConicalGradient {
2966                    to_local: invert_to_local(oriented),
2967                    // In the gradient's own space, which this rotation and the
2968                    // canvas transform's inverse together make into user space
2969                    // -- so both radii are the ones the caller stated, and
2970                    // neither is folded into the matrix the way a radial
2971                    // gradient's single radius is. A scale can normalize one
2972                    // radius; it cannot normalize two.
2973                    start_radius: *start_radius,
2974                    radius_delta: *end_radius - *start_radius,
2975                    separation: axis.length(),
2976                    stops: stops_of(stops),
2977                    tile: *tile,
2978                    ramp: ramp_slot,
2979                }
2980            }
2981            Shader::SweepGradient {
2982                center,
2983                start_angle,
2984                end_angle,
2985                stops,
2986                tile,
2987            } => {
2988                let placement = to_clip * Affine2::from_translation(*center);
2989                if !placement.is_finite() || !start_angle.is_finite() || !end_angle.is_finite() {
2990                    return Material::Solid([0.0; 4]);
2991                }
2992                let ramp_slot = self.ramp_for(stops);
2993                Material::SweepGradient {
2994                    to_local: invert_to_local(placement),
2995                    start_angle: *start_angle,
2996                    end_angle: *end_angle,
2997                    stops: stops_of(stops),
2998                    tile: *tile,
2999                    ramp: ramp_slot,
3000                }
3001            }
3002        }
3003    }
3004
3005    /// Draw a shape through a blurred layer, which is what a mask blur is.
3006    ///
3007    /// Blurring coverage and then filling equals filling and then blurring
3008    /// exactly when the fill is constant, since a blur is linear. That identity
3009    /// is the whole implementation: a bounded layer, blurred, with the shape
3010    /// drawn into it. It also means the machinery is one already tested rather
3011    /// than a second blur written beside the first.
3012    ///
3013    /// The bounds are the shape's, widened by how far the blur reaches. A
3014    /// caller doing this by hand has to know that reach, which is exactly the
3015    /// part that is easy to get wrong and shows as a shadow with a straight
3016    /// edge where it was cut off.
3017    /// Draw into a layer, filter it, and composite it back.
3018    ///
3019    /// The same machinery a mask blur uses, without the restriction: a mask
3020    /// blur is only the same picture as this when the fill does not vary, and
3021    /// so takes a solid color, while filtering a result is defined whatever
3022    /// produced it. What is paid for that is a target of its own.
3023    /// The layer that applies one filter, where that filter is a leaf.
3024    ///
3025    /// `None` for the two that are not: `is_identity` keeps `None` out, and
3026    /// `peel` recurses through a composition's outer half until it reaches
3027    /// something that is not one -- so neither can arrive here. They were
3028    /// reachable when peeling took that half to be a leaf, and composing two
3029    /// compositions was then refused as unimplemented, having been assembled
3030    /// out of nothing but implemented filters.
3031    fn filter_layer(&self, filter: &ImageFilter) -> Option<(Layer, Option<ImageFilter>)> {
3032        if let ImageFilter::Runtime { program, uniforms } = filter {
3033            // The layer itself is plain: what makes it a filter is the pass run
3034            // over it at restore, which needs the program and cannot get it
3035            // from a `Copy` layer.
3036            return Some((
3037                Layer::opacity(1.0),
3038                Some(ImageFilter::Runtime {
3039                    program: *program,
3040                    uniforms: uniforms.clone(),
3041                }),
3042            ));
3043        }
3044        Some((
3045            match *filter {
3046                ImageFilter::Blur { sigma_x, sigma_y } => {
3047                    Layer::opacity(1.0).with_blur_xy(sigma_x, sigma_y)
3048                }
3049                ImageFilter::Matrix { transform } => Layer::opacity(1.0).with_matrix(transform),
3050                ImageFilter::Dilate { radius_x, radius_y } => {
3051                    Layer::opacity(1.0).with_morphology(Morphology::dilate(radius_x, radius_y))
3052                }
3053                ImageFilter::Erode { radius_x, radius_y } => {
3054                    Layer::opacity(1.0).with_morphology(Morphology::erode(radius_x, radius_y))
3055                }
3056                ImageFilter::Color(filter) => Layer::opacity(1.0).with_color_filter(filter),
3057                ImageFilter::Runtime { .. } => unreachable!("handled above"),
3058                ImageFilter::None | ImageFilter::Compose { .. } => return None,
3059            },
3060            None,
3061        ))
3062    }
3063
3064    /// A glyph run drawn into a layer, and the layer filtered.
3065    ///
3066    /// The third of these, after the shape and the mesh, and the same shape as
3067    /// both. The bounds come from the run's own boxes, since a run has neither
3068    /// a path nor vertices to take them from.
3069    fn draw_glyphs_filtered(
3070        &mut self,
3071        glyphs: &[PositionedGlyph],
3072        atlas: &Atlas,
3073        atlas_slot: u32,
3074        paint: &Paint,
3075    ) -> Result<&mut Self> {
3076        if paint
3077            .image_filter
3078            .nests_deeper_than(ImageFilter::MAX_NESTING)
3079        {
3080            return Err(Error::Unsupported(
3081                "this image filter composes more filters than can be walked",
3082            ));
3083        }
3084        let (outermost, rest) = paint.image_filter.peel();
3085        let Some((layer, runtime)) = self.filter_layer(&outermost) else {
3086            return Err(Error::Unsupported("this image filter is not implemented"));
3087        };
3088        let (mut min, mut max) = (Vec2::splat(f32::INFINITY), Vec2::splat(f32::NEG_INFINITY));
3089        for glyph in glyphs {
3090            let corner = Vec2::from(glyph.position);
3091            min = min.min(corner);
3092            max = max.max(corner + Vec2::from(glyph.size));
3093        }
3094        if !min.is_finite() || !max.is_finite() {
3095            return Err(Error::Unsupported(
3096                "a glyph in this run is not at a finite position",
3097            ));
3098        }
3099        let (min, max) = transformed_bounds(self.transform, min, max).unwrap_or_else(unbounded);
3100        let basis = BlurBasis::of(self.transform);
3101        let (min, max) = rest.covering(min, max, &|sigma| basis.reach(sigma));
3102        let _ = self.save_layer_device_bounds_running(
3103            layer.with_blend(paint.blend),
3104            min,
3105            max,
3106            runtime,
3107            None,
3108        );
3109        let inner = paint
3110            .clone()
3111            .with_image_filter(rest)
3112            .with_blend(BlendMode::SrcOver);
3113        let failure = self.draw_glyphs(glyphs, atlas, atlas_slot, &inner).err();
3114        self.restore();
3115        match failure {
3116            Some(e) => Err(e),
3117            None => Ok(self),
3118        }
3119    }
3120
3121    /// A mesh drawn into a layer, and the layer filtered.
3122    ///
3123    /// The path version's twin, and separate rather than shared because the two
3124    /// differ in the only two places that matter -- where the bounds come from,
3125    /// and which draw call the remainder of the chain is handed back to. The
3126    /// peeling, the region arithmetic and the blend placement are the same and
3127    /// are described there.
3128    fn draw_vertices_filtered(&mut self, mesh: &Vertices, paint: &Paint) -> Result<&mut Self> {
3129        if paint
3130            .image_filter
3131            .nests_deeper_than(ImageFilter::MAX_NESTING)
3132        {
3133            return Err(Error::Unsupported(
3134                "this image filter composes more filters than can be walked",
3135            ));
3136        }
3137        let (outermost, rest) = paint.image_filter.peel();
3138        let Some((layer, runtime)) = self.filter_layer(&outermost) else {
3139            return Err(Error::Unsupported("this image filter is not implemented"));
3140        };
3141        // From the vertices themselves. A mesh has no path to take bounds from,
3142        // and the positions are in the same coordinates a path's points would
3143        // be, so the transform below is the one that applies to either.
3144        let positions = mesh.positions();
3145        let (mut min, mut max) = (Vec2::splat(f32::INFINITY), Vec2::splat(f32::NEG_INFINITY));
3146        for point in positions {
3147            min = min.min(*point);
3148            max = max.max(*point);
3149        }
3150        if !min.is_finite() || !max.is_finite() {
3151            return Err(Error::Unsupported("a mesh position is not a finite number"));
3152        }
3153        let (min, max) = transformed_bounds(self.transform, min, max).unwrap_or_else(unbounded);
3154        let basis = BlurBasis::of(self.transform);
3155        let (min, max) = rest.covering(min, max, &|sigma| basis.reach(sigma));
3156        let _ = self.save_layer_device_bounds_running(
3157            layer.with_blend(paint.blend),
3158            min,
3159            max,
3160            runtime,
3161            None,
3162        );
3163        let inner = paint
3164            .clone()
3165            .with_image_filter(rest)
3166            .with_blend(BlendMode::SrcOver);
3167        let failure = self.draw_vertices(mesh, &inner).err();
3168        self.restore();
3169        match failure {
3170            Some(e) => Err(e),
3171            None => Ok(self),
3172        }
3173    }
3174
3175    /// A caller's program drawn into a layer, and the layer recolored.
3176    ///
3177    /// The bounds are the path's own, widened by a stroke where there is one.
3178    /// Nothing here reaches past that: a color filter moves colors rather than
3179    /// pixels, so the region it can affect is the region that was drawn.
3180    fn draw_effect_filtered(&mut self, path: &Path, paint: &Paint) -> Result<&mut Self> {
3181        let bounds = self.filter_bounds(path, paint);
3182        let (min, max) = transformed_bounds(
3183            self.transform,
3184            Vec2::new(bounds.left, bounds.top),
3185            Vec2::new(bounds.right, bounds.bottom),
3186        )
3187        .unwrap_or_else(unbounded);
3188        self.save_layer_device_bounds(
3189            Layer::opacity(1.0)
3190                .with_color_filter(paint.color_filter)
3191                // The blend belongs to the composite, not to the draw inside.
3192                // That is what `saveLayer` means by taking a paint, and it is
3193                // the only placement that gives the right answer for a blend
3194                // reading its destination: inside the layer the destination is
3195                // transparent black, so a mode like `Multiply` applied there
3196                // would come out empty and then be composited over the frame it
3197                // was supposed to darken.
3198                .with_blend(paint.blend),
3199            min,
3200            max,
3201        );
3202        // Without the filter, or this would open a layer inside itself forever,
3203        // and over an empty layer rather than through the caller's blend, which
3204        // the composite above now carries.
3205        let inner = paint
3206            .clone()
3207            .with_color_filter(ColorFilter::None)
3208            .with_blend(BlendMode::SrcOver);
3209        let failure = self.draw_path(path, &inner).err();
3210        self.restore();
3211        match failure {
3212            Some(e) => Err(e),
3213            None => Ok(self),
3214        }
3215    }
3216
3217    fn draw_filtered(&mut self, path: &Path, paint: &Paint) -> Result<&mut Self> {
3218        // One filter is peeled off here and the rest is handed back to
3219        // `draw_path`, which lands in this method again if anything is left.
3220        // A chain of filters is a stack of layers, and this builds the stack
3221        // one frame at a time rather than all at once -- which keeps the
3222        // single-filter case exactly what it was, with the remainder `None`.
3223        if paint
3224            .image_filter
3225            .nests_deeper_than(ImageFilter::MAX_NESTING)
3226        {
3227            return Err(Error::Unsupported(
3228                "this image filter composes more filters than can be walked",
3229            ));
3230        }
3231        let (outermost, rest) = paint.image_filter.peel();
3232        let Some((layer, runtime)) = self.filter_layer(&outermost) else {
3233            return Err(Error::Unsupported("this image filter is not implemented"));
3234        };
3235        let bounds = self.filter_bounds(path, paint);
3236        // In device pixels, because that is where a filter's reach is measured.
3237        // The outer layer has to cover everything the rest of the chain needs,
3238        // both what goes into it and what comes out -- a layer's target is
3239        // clipped to its parent's, so a target sized for the result alone would
3240        // crop the content before the inner filter ever ran.
3241        let (min, max) = transformed_bounds(
3242            self.transform,
3243            Vec2::new(bounds.left, bounds.top),
3244            Vec2::new(bounds.right, bounds.bottom),
3245        )
3246        .unwrap_or_else(unbounded);
3247        let basis = BlurBasis::of(self.transform);
3248        let (min, max) = rest.covering(min, max, &|sigma| basis.reach(sigma));
3249        // The caller's blend rides the outermost composite. Left on the draw
3250        // inside, it was applied against the layer's own transparent black --
3251        // so a mode that reads its destination found nothing there, and the
3252        // result was composited over the frame it was meant to combine with.
3253        // `Plus` over a cyan ground gave the source unchanged instead of the
3254        // sum, for every image filter, since filters were added.
3255        //
3256        // Only the outermost, which is why the inner paint is neutral: peeling
3257        // a chain opens a layer per link, and a blend carried down would be
3258        // applied once per link rather than once.
3259        let _ = self.save_layer_device_bounds_running(
3260            layer.with_blend(paint.blend),
3261            min,
3262            max,
3263            runtime,
3264            None,
3265        );
3266        // The mask blur, if there is one, is left on: it applies to the drawing
3267        // this filter is filtering.
3268        let inner = paint
3269            .clone()
3270            .with_image_filter(rest)
3271            .with_blend(BlendMode::SrcOver);
3272        let failure = self.draw_path(path, &inner).err();
3273        self.restore();
3274        match failure {
3275            Some(e) => Err(e),
3276            None => Ok(self),
3277        }
3278    }
3279
3280    /// A path's bounds, widened by however far a stroke reaches past it.
3281    ///
3282    /// How far a blur reaches is deliberately not added: opening a bounded
3283    /// layer with a blur already widens the region by that, and the layer is
3284    /// the right place for it, since it knows its own sigma.
3285    ///
3286    /// The stroke's own reach was untested for a while, because that blur
3287    /// widening covers any stroke whose half-width is under the blur's own
3288    /// reach, and every test had one. It takes a wide stroke and a small blur to tell the two
3289    /// apart, and there is one now.
3290    fn filter_bounds(&self, path: &Path, paint: &Paint) -> Rect {
3291        let bounds = path.bounds();
3292        let reach = match &paint.style {
3293            // The width the stroke is drawn at, which for a sub-pixel one is
3294            // wider than the width it asked for. A bound taken from the asked
3295            // width would cut the widening off at the edge of the layer.
3296            Style::Stroke(stroke) if stroke.width.is_finite() => {
3297                thin_stroke(self.transform, stroke.width, Zero::IsAHairline).0 / 2.0
3298            }
3299            _ => 0.0,
3300        };
3301        Rect::new(
3302            bounds.min.x - reach,
3303            bounds.min.y - reach,
3304            bounds.max.x + reach,
3305            bounds.max.y + reach,
3306        )
3307    }
3308
3309    /// What a mask blur is blurring.
3310    ///
3311    /// A mask blur draws its content two or three times -- once into a blurred
3312    /// layer, sometimes again at full sharpness to combine with it -- and every
3313    /// style needs the same content each time. Naming the content rather than
3314    /// passing a path is what lets a glyph run take the same four styles a
3315    /// shape does, which matters because a text shadow is a mask blur over a
3316    /// run and is how the common case of shadowed text is drawn.
3317    fn draw_mask_content(&mut self, content: Masked<'_>, paint: &Paint) -> Result<&mut Self> {
3318        match content {
3319            Masked::Path(path) => self.draw_path(path, paint),
3320            Masked::Mesh(mesh) => self.draw_vertices(mesh, paint),
3321            Masked::Glyphs {
3322                glyphs,
3323                atlas,
3324                slot,
3325            } => self.draw_glyphs(glyphs, atlas, slot, paint),
3326        }
3327    }
3328
3329    /// The bounds of what a mask blur is blurring, in the canvas's own units.
3330    fn mask_bounds(&self, content: Masked<'_>, paint: &Paint) -> Rect {
3331        match content {
3332            Masked::Path(path) => self.filter_bounds(path, paint),
3333            Masked::Mesh(mesh) => {
3334                let (mut min, mut max) =
3335                    (Vec2::splat(f32::INFINITY), Vec2::splat(f32::NEG_INFINITY));
3336                for position in mesh.positions() {
3337                    min = min.min(*position);
3338                    max = max.max(*position);
3339                }
3340                Rect::new(min.x, min.y, max.x, max.y)
3341            }
3342            Masked::Glyphs { glyphs, .. } => {
3343                let (mut min, mut max) =
3344                    (Vec2::splat(f32::INFINITY), Vec2::splat(f32::NEG_INFINITY));
3345                for glyph in glyphs {
3346                    let corner = Vec2::from(glyph.position);
3347                    min = min.min(corner);
3348                    max = max.max(corner + Vec2::from(glyph.size));
3349                }
3350                Rect::new(min.x, min.y, max.x, max.y)
3351            }
3352        }
3353    }
3354
3355    /// A mask blur over a fill that varies, built the way `dart:ui` states it.
3356    ///
3357    /// The path below draws the paint through a blurred layer, which is the
3358    /// same picture only where the fill does not vary. This is the other order
3359    /// and the one a mask filter actually means: blur the shape's coverage,
3360    /// then fill through it. It needs no machinery that was not already here --
3361    /// the fill goes down across everything the blur reaches, the coverage is
3362    /// blurred in a layer of its own, and `DstIn` composites the second onto
3363    /// the first as a mask.
3364    ///
3365    /// Only a path. A glyph run reaches this call too, and a run tints one
3366    /// color by its own nature rather than by anything to do with blurring, so
3367    /// a gradient over one is refused here exactly as it is refused when
3368    /// nothing is blurred at all.
3369    fn draw_masked_through_coverage(
3370        &mut self,
3371        content: Masked<'_>,
3372        paint: &Paint,
3373    ) -> Result<&mut Self> {
3374        let bounds = self.mask_bounds(content, paint);
3375        // Wide enough for whichever blur this content's route will draw.
3376        let held = bounds.outset(self.mask_blur_reach(content, paint));
3377        // White, because what is wanted from the shape here is its coverage
3378        // rather than its color: the fill supplies the color and this supplies
3379        // where it lands.
3380        let coverage = Paint::fill(Color::WHITE).with_anti_alias(paint.anti_alias);
3381        // This one floods the held region with the caller's paint, so it has to
3382        // be a *fill* whatever the caller asked for. Left as the caller's own
3383        // style it drew the outline of the held rectangle when the caller was
3384        // stroking, and the mask below then cut that away to nothing -- the
3385        // rectangle's border is nowhere near the shape. A stroked shape with a
3386        // fill that varies came out empty, on both backends.
3387        //
3388        // Only the flood needs it. Handing the coverage the caller's style as
3389        // well changes no pixel of any plate here, so something other than this
3390        // line is already giving the mask the band rather than the region, and
3391        // a line that changes nothing does not go in with a comment saying it
3392        // does.
3393        let fill = paint
3394            .clone()
3395            .with_mask_blur(0.0)
3396            .with_blend(BlendMode::SrcOver)
3397            .with_style(Style::Fill);
3398
3399        self.save_layer_bounds(Layer::opacity(1.0).with_blend(paint.blend), held);
3400        // Across everything the blur reaches, not across the shape: a blurred
3401        // mask is wider than what it was made from, and a fill stopping at the
3402        // shape's own edge would cut the halo off square.
3403        let failure = self.draw_rect(held, &fill).err().or_else(|| {
3404            if paint.mask_blur_style == MaskBlurStyle::Normal {
3405                // The blurred coverage is the whole mask, so the layer that
3406                // carries it can be the layer that blurs it.
3407                let mask = Layer::opacity(1.0)
3408                    .with_blur(paint.mask_blur)
3409                    .with_blend(BlendMode::DstIn);
3410                self.save_layer_bounds(mask, held);
3411                let inner = self.draw_mask_content(content, &coverage).err();
3412                self.restore();
3413                return inner;
3414            }
3415            // The other three combine the blurred coverage with the sharp one,
3416            // and the combination is not itself blurred -- so this layer
3417            // carries no blur, and the blur happens inside it on the operand
3418            // that wants it.
3419            self.save_layer_bounds(Layer::opacity(1.0).with_blend(BlendMode::DstIn), held);
3420            let inner = self.draw_mask_styles(
3421                content,
3422                &coverage,
3423                paint.mask_blur,
3424                paint.mask_blur_style,
3425                bounds,
3426            );
3427            self.restore();
3428            inner
3429        });
3430        self.restore();
3431        match failure {
3432            Some(e) => Err(e),
3433            None => Ok(self),
3434        }
3435    }
3436
3437    fn draw_masked(&mut self, content: Masked<'_>, paint: &Paint) -> Result<&mut Self> {
3438        if !matches!(paint.shader, Shader::Solid(_)) {
3439            if !matches!(content, Masked::Glyphs { .. }) {
3440                return self.draw_masked_through_coverage(content, paint);
3441            }
3442            // A glyph run, and it is the only thing left here. A run tints one
3443            // color by its own nature rather than by anything to do with
3444            // blurring, so a varying fill over one is refused exactly as it is
3445            // refused when nothing is blurred at all.
3446            //
3447            // See `Paint::mask_blur`: drawing the paint through a blurred layer
3448            // is the other order, and for anything that varies the two are
3449            // different pictures. Drawing one while the caller asked for the
3450            // other is the substitution this renderer refuses
3451            // elsewhere.
3452            return Err(Error::Unsupported(
3453                "a mask blur over a glyph run takes a solid color; \
3454                 draw into a blurred layer for anything else",
3455            ));
3456        }
3457        let bounds = self.mask_bounds(content, paint);
3458        // Without the mask, or this would open a layer inside itself forever --
3459        // and with the caller's blend taken off, because it belongs to the
3460        // composite that puts the finished mask on the frame rather than to a
3461        // draw inside a layer that starts empty. Left on, a mode reading its
3462        // destination found transparent black there, and `Plus` over a cyan
3463        // ground gave the source unchanged instead of the sum.
3464        //
3465        // The style's own blends below are a different thing and stay: they
3466        // combine the shape with its blur *within* the layer, which is exactly
3467        // where a destination-reading mode is supposed to look.
3468        let inner = paint
3469            .clone()
3470            .with_mask_blur(0.0)
3471            .with_blend(BlendMode::SrcOver);
3472
3473        // The blurred coverage alone is the whole picture for the default
3474        // style, so it needs one layer and no second draw.
3475        if paint.mask_blur_style == MaskBlurStyle::Normal {
3476            self.save_layer_bounds(
3477                Layer::opacity(1.0)
3478                    .with_blur(paint.mask_blur)
3479                    .with_blend(paint.blend),
3480                bounds,
3481            );
3482            // The result is discarded to end the borrow before restoring, and
3483            // taken up again after: the layer has to be closed whether the
3484            // draw inside it succeeded or not, or every later draw lands in a
3485            // layer nobody composites.
3486            let failure = self.draw_mask_content(content, &inner).err();
3487            self.restore();
3488            return match failure {
3489                Some(e) => Err(e),
3490                None => Ok(self),
3491            };
3492        }
3493
3494        // Every other style combines the blurred coverage with the shape's
3495        // own. That combination is the same whether what is being combined is
3496        // color or coverage, so it lives in `draw_mask_styles` and both routes
3497        // through here call it.
3498        // Wide enough for whichever blur this content's route will draw.
3499        let held = bounds.outset(self.mask_blur_reach(content, paint));
3500        self.save_layer_bounds(Layer::opacity(1.0).with_blend(paint.blend), held);
3501        let failure = self.draw_mask_styles(
3502            content,
3503            &inner,
3504            paint.mask_blur,
3505            paint.mask_blur_style,
3506            bounds,
3507        );
3508        self.restore();
3509        match failure {
3510            Some(e) => Err(e),
3511            None => Ok(self),
3512        }
3513    }
3514
3515    /// How far past its bounds a mask blur on this content will draw.
3516    ///
3517    /// The two routes reach different distances and the layer holding them has
3518    /// to fit whichever is used: a sampled blur stops at `blur_reach`, about
3519    /// 1.73 deviations, and an evaluated one carries to `pad_for_sigma`, about
3520    /// 2.5. Sized for the first, an evaluated blur is cut off square; sized for
3521    /// the second regardless, every *sampled* blur pays for a transient about
3522    /// twice the area to hold a halo it will never draw.
3523    ///
3524    /// So it asks which route the content will take, rather than taking the
3525    /// larger of the two and calling it safe.
3526    fn mask_blur_reach(&mut self, content: Masked<'_>, paint: &Paint) -> f32 {
3527        let sampled = blur_reach(paint.mask_blur);
3528        let probe = paint.clone().with_mask_blur_style(MaskBlurStyle::Normal);
3529        match self.analytic_style_blur(content, &probe, paint.mask_blur) {
3530            Some((_, _, pad)) => sampled.max(pad),
3531            None => sampled,
3532        }
3533    }
3534
3535    /// The evaluated blur for a style's blurred ingredient, where one applies.
3536    ///
3537    /// The styles other than `Normal` combine a blurred shape with its sharp
3538    /// self, and the blurred half is the same thing `Normal` draws — so where
3539    /// `Normal` would be evaluated rather than sampled, this half can be too.
3540    /// `inner` is the paint with the blur already taken off, which is what the
3541    /// styles draw with, so the deviation is handed back in.
3542    ///
3543    /// Returns the rectangle the draw covers as well as the material, because
3544    /// the caller has to widen its layer to hold it: an evaluated blur reaches
3545    /// `pad_for_sigma`, which is further than the `blur_reach` a sampled one is
3546    /// truncated at, and a layer sized for the sampled reach cuts it.
3547    fn analytic_style_blur(
3548        &mut self,
3549        content: Masked<'_>,
3550        inner: &Paint,
3551        sigma: f32,
3552    ) -> Option<(Rect, Material, f32)> {
3553        let Masked::Path(path) = content else {
3554            return None;
3555        };
3556        let (bounds, radius) = path.as_rounded_rect()?;
3557        let rect = Rect::new(bounds.min.x, bounds.min.y, bounds.max.x, bounds.max.y);
3558        // Asked for as `Normal`, whatever style the caller wants: the blurred
3559        // half *is* the normal blur, and the style is the rule for combining it
3560        // with the sharp shape rather than a property of the blur. Left as the
3561        // caller's, the eligibility check refuses it -- which is right when the
3562        // question is "may this whole draw be one expression" and wrong here.
3563        let asked = inner
3564            .clone()
3565            .with_mask_blur(sigma)
3566            .with_mask_blur_style(MaskBlurStyle::Normal);
3567        let (material, pad) = self.analytic_rrect_blur(rect, radius, &asked)?;
3568        Some((rect, material, pad))
3569    }
3570
3571    /// Combine a shape's blurred coverage with its sharp own, per style.
3572    ///
3573    /// Draws into whatever layer the caller has already opened, and that layer
3574    /// is not optional: drawn straight onto the target, a blend that reads the
3575    /// destination would reach what was already there rather than only what
3576    /// this is building.
3577    ///
3578    /// What is being combined is the caller's business. Given the paint the
3579    /// shape is filled with, this composes colors and is the whole picture;
3580    /// given white, it composes coverage, and the caller masks a varying fill
3581    /// through the result. The rules are identical either way, which is why
3582    /// there is one of these rather than two.
3583    ///
3584    /// Which of the two operands is drawn first is not a matter of taste. A
3585    /// blend only runs where its source produces a fragment, and the shape
3586    /// produces none outside itself -- so a rule that has to *remove*
3587    /// something outside the shape cannot be written with the shape as the
3588    /// source. The blurred layer composites as a quad over the whole region, so
3589    /// it is the operand that can act everywhere, and the two rules needing
3590    /// that are the two where the shape goes down first.
3591    fn draw_mask_styles(
3592        &mut self,
3593        content: Masked<'_>,
3594        inner: &Paint,
3595        sigma: f32,
3596        style: MaskBlurStyle,
3597        bounds: Rect,
3598    ) -> Option<Error> {
3599        // Not itself blurred, so nothing widens it on its behalf.
3600        let blurred = Layer::opacity(1.0).with_blur(sigma);
3601        match style {
3602            // Blur first, then the shape over it. `SrcOver` leaves the blur
3603            // where the shape is not, and `DstOut` takes the shape out of it
3604            // -- both of which want the destination untouched outside the
3605            // shape, which is what a source that draws nothing there gives.
3606            MaskBlurStyle::Solid | MaskBlurStyle::Outer => {
3607                let blend = match style {
3608                    MaskBlurStyle::Solid => BlendMode::SrcOver,
3609                    _ => BlendMode::DstOut,
3610                };
3611                // The blurred half, evaluated where it can be. These two
3612                // styles draw it first with the layer's own blend, so nothing
3613                // has to be relaxed to allow it -- unlike `Inner`, whose blur
3614                // is composited with `DstIn` and needs coverage this cannot
3615                // give from a quad.
3616                let first = match self.analytic_style_blur(content, inner, sigma) {
3617                    Some((rect, material, pad)) => {
3618                        self.draw_analytic(rect.outset(pad), material, inner).err()
3619                    }
3620                    None => {
3621                        self.save_layer_bounds(blurred, bounds);
3622                        let failed = self.draw_mask_content(content, inner).err();
3623                        self.restore();
3624                        failed
3625                    }
3626                };
3627                first.or_else(|| {
3628                    self.draw_mask_content(content, &inner.clone().with_blend(blend))
3629                        .err()
3630                })
3631            }
3632            // The shape first, and the blur composited onto it with `DstIn`.
3633            // The other order is the obvious one and is wrong: outside the
3634            // shape there is no fragment for `DstIn` to run on, so the blur
3635            // survives exactly where this style is supposed to discard it.
3636            // Compositing a layer covers the whole region, so putting the
3637            // blur on that side is what makes the rule act everywhere.
3638            MaskBlurStyle::Inner => {
3639                let first = self.draw_mask_content(content, inner).err();
3640                if first.is_some() {
3641                    return first;
3642                }
3643                // `DstIn` is the one blend the analytic route refuses
3644                // everywhere else, because it changes the destination where the
3645                // source drew nothing and a quad is smaller than the region a
3646                // layer composite covers. That argument does not reach here,
3647                // and the reason is specific rather than a relaxation: the only
3648                // thing in this layer is the sharp shape drawn a line above,
3649                // the shape is a fill and so lies within `rect`, and the quad
3650                // is `rect` grown by the blur's reach. Everything the blend
3651                // could have to zero is under the quad; outside it the layer is
3652                // still transparent, where zeroing and leaving alone are the
3653                // same. So the eligibility is asked about the blur -- with
3654                // `SrcOver`, since that is what the question means -- and the
3655                // blend is put on at the draw.
3656                match self.analytic_style_blur(content, inner, sigma) {
3657                    Some((rect, material, pad)) => {
3658                        let composite = inner.clone().with_blend(BlendMode::DstIn);
3659                        self.draw_analytic(rect.outset(pad), material, &composite)
3660                            .err()
3661                    }
3662                    None => {
3663                        self.save_layer_bounds(blurred.with_blend(BlendMode::DstIn), bounds);
3664                        let second = self.draw_mask_content(content, inner).err();
3665                        self.restore();
3666                        second
3667                    }
3668                }
3669            }
3670            MaskBlurStyle::Normal => unreachable!("handled by the caller"),
3671        }
3672    }
3673
3674    /// Fill or stroke a rectangle.
3675    ///
3676    /// **A fill is tessellated.** It used to take the same distance field a rounded
3677    /// rectangle does, with no corner to round, on the reasoning that a shape
3678    /// computing its own coverage spares the pass multisampling. That was measured
3679    /// backwards on 2026-09-30: the field is the dearer route by about thirty per
3680    /// cent. On the `stacked interface` frame, tessellated at four samples against
3681    /// analytic at one -- 16.077 ms against 24.508 on a Pi 5, 66.100 against 93.981
3682    /// on a VisionFive 2, 1.786 against 2.758 on x86-64. Three architectures, one
3683    /// direction. `docs/on-a-board.md` has the conditions, the control and the
3684    /// arithmetic.
3685    ///
3686    /// The arithmetic the old comment had wrong: multisampling shades once per pixel
3687    /// and pays in attachment bandwidth and a resolve -- 1.23x on V3D, 2.62x on
3688    /// PowerVR, not 4x -- while the field costs an evaluation per fragment across a
3689    /// quad, and for a rectangle that field evaluates to a constant.
3690    ///
3691    /// It is also what upstream does. `FillRectGeometry::GetPositionBuffer`, read at
3692    /// `flutter/flutter` master on 2026-10-01, emits a four-vertex triangle strip
3693    /// under `Mode::kNormal`; there is no fragment-evaluated rectangle fill there at
3694    /// all. So the flip closes a divergence rather than opening one, and the edge a
3695    /// rectangle gets here is now the edge upstream gives it.
3696    ///
3697    /// **A stroke stays on the field.** What was measured is a fill, the stroke route
3698    /// is careful about a corner the field would otherwise round -- see
3699    /// `analytic_rrect` -- and nothing here has measured what that costs.
3700    pub fn draw_rect(&mut self, rect: Rect, paint: &Paint) -> Result<&mut Self> {
3701        self.prepare_destination(paint.blend);
3702        if rect.is_empty() {
3703            return Ok(self);
3704        }
3705        if matches!(paint.style, Style::Stroke(_)) {
3706            if let Some((material, to_local)) = self.analytic_rrect(rect, 0.0, paint) {
3707                return self.draw_analytic_local(rect, material, paint, to_local);
3708            }
3709        }
3710        let path = rect.to_path();
3711        self.draw_path(&path, paint)
3712    }
3713
3714    /// Fill or stroke a rectangle with rounded corners.
3715    ///
3716    /// The shape an interface is mostly made of, and the reason it is here
3717    /// rather than left to the caller: building it from arcs by hand is a dozen
3718    /// lines that have to get the corner tangents right, and getting them
3719    /// slightly wrong shows as a corner that is subtly not round.
3720    ///
3721    /// **A fill is tessellated once the pass is multisampled**, and takes the
3722    /// field until then. What the field buys is a pass left at one sample, and
3723    /// since `draw_rect` started tessellating its fills on 2026-10-01 most frames
3724    /// give that up early: one antialiased rectangle multisamples the pass. From
3725    /// there on the field is evaluated across a whole quad for an edge four
3726    /// samples would have given anyway, and at equal sample counts it was already
3727    /// measured as the dearer route -- see `docs/architecture.md`.
3728    ///
3729    /// Measured 2026-11-12 on a Pi 5, interleaved, four runs a side: the cards
3730    /// of `full frame, mixed content`, drawn over a multisampled ground, cost
3731    /// 0.64 ms from the field and 0.29 tessellated, and the frame 14.46 against
3732    /// 14.10. `docs/on-a-board.md` has the frames. Upstream tessellates the fill
3733    /// too: `Canvas::DrawRoundRect` sends it to `RoundRectGeometry`, a
3734    /// tessellated strip, unless `--impeller-use-sdfs` is passed, which it is
3735    /// not by default.
3736    ///
3737    /// Before anything has multisampled the pass, the field stays. Tessellating
3738    /// there would turn multisampling on for the whole pass, which is what the
3739    /// field exists to avoid, and would make a frame drawn with no background
3740    /// into a multisampled pass with nothing to clear to, which the backends
3741    /// refuse.
3742    ///
3743    /// **A stroke stays on the field**, as `draw_rect`'s does, and for the
3744    /// reason given there. Both routes need what `analytic_rrect` admits -- a
3745    /// solid paint that asked for antialiasing -- and anything else goes to
3746    /// `draw_path`.
3747    pub fn draw_rrect(&mut self, rect: Rect, radius: f32, paint: &Paint) -> Result<&mut Self> {
3748        self.prepare_destination(paint.blend);
3749        if rect.is_empty() {
3750            return Ok(self);
3751        }
3752        // Before the sharp field, because that one refuses a mask blur and this
3753        // is what answers it: the blur is folded into the expression rather
3754        // than run as passes around the draw.
3755        if let Some((material, pad, drawn)) = self.analytic_rrect_blur_draw(rect, radius, paint) {
3756            return self.draw_analytic(rect.outset(pad), material, &drawn);
3757        }
3758        if matches!(paint.style, Style::Stroke(_)) || self.pass_samples() == 1 {
3759            if let Some((material, to_local)) = self.analytic_rrect(rect, radius, paint) {
3760                return self.draw_analytic_local(rect, material, paint, to_local);
3761            }
3762        }
3763        let path = rect.to_rounded_path(radius);
3764        self.draw_path(&path, paint)
3765    }
3766
3767    /// A rounded rectangle whose corners need not match.
3768    ///
3769    /// The eight numbers `dart:ui`'s `RRect` carries, in the order upstream's
3770    /// `RoundingRadii` carries them: top-left, top-right, bottom-left,
3771    /// bottom-right, each an x radius and a y radius. Radii that overrun the
3772    /// side they share are fitted by `dart:ui`'s rule -- see
3773    /// [`Rect::to_rounded_path_with_radii`].
3774    ///
3775    /// Tessellated, always. The fragment-evaluated route [`Self::draw_rrect`]
3776    /// can take -- for a stroke, or a fill in a pass not yet multisampled -- is
3777    /// a signed distance to a shape with one circular radius, and eight numbers
3778    /// is a different function rather than that one with more arguments. So a
3779    /// corner that differs from its neighbors is tessellated where a uniform
3780    /// one might not be. A multisampled fill is tessellated either way, so
3781    /// there the two calls cost the same.
3782    pub fn draw_rrect_with_radii(
3783        &mut self,
3784        rect: Rect,
3785        radii: RoundingRadii,
3786        paint: &Paint,
3787    ) -> Result<&mut Self> {
3788        self.prepare_destination(paint.blend);
3789        if rect.is_empty() {
3790            return Ok(self);
3791        }
3792        // A caller who spells a uniform shape this way still gets the route
3793        // `draw_rrect` picks, which matters because the general call is the one
3794        // a `dart:ui` port reaches for and most of what it is handed is uniform.
3795        if let Some(radius) = uniform_circular_radius(radii) {
3796            return self.draw_rrect(rect, radius, paint);
3797        }
3798        let path = rect.to_rounded_path_with_radii(radii);
3799        self.draw_path(&path, paint)
3800    }
3801
3802    /// Draw Flutter's rounded superellipse -- the iOS-style squircle.
3803    ///
3804    /// `dart:ui`'s `drawRSuperellipse`. The corners are not arcs of one curve:
3805    /// each is a superellipse arc, a circular arc across the diagonal, and a
3806    /// second superellipse arc, with the superellipse's degree read from a
3807    /// fitted table on the ratio of side to radius. See
3808    /// [`emblema_geometry::superellipse`] for what that means and for what
3809    /// checks the transcription of the table.
3810    ///
3811    /// Tessellated rather than evaluated in the fragment stage. A rounded
3812    /// rectangle of a single radius takes the analytic route because there is
3813    /// a closed form to evaluate; this shape has none, which is the same
3814    /// reason it took so long to arrive.
3815    pub fn draw_rsuperellipse(
3816        &mut self,
3817        rect: Rect,
3818        radii: RoundingRadii,
3819        paint: &Paint,
3820    ) -> Result<&mut Self> {
3821        self.prepare_destination(paint.blend);
3822        if rect.is_empty() {
3823            return Ok(self);
3824        }
3825        self.draw_path(&rsuperellipse_path(rect, radii), paint)
3826    }
3827
3828    /// Clip to Flutter's rounded superellipse.
3829    ///
3830    /// `dart:ui`'s `clipRSuperellipse`, and the same shape
3831    /// [`Canvas::draw_rsuperellipse`] draws.
3832    pub fn clip_rsuperellipse(&mut self, rect: Rect, radii: RoundingRadii) -> Result<&mut Self> {
3833        self.clip_path(&rsuperellipse_path(rect, radii))
3834    }
3835
3836    /// How far past the shape a blurred rounded rectangle has to draw.
3837    ///
3838    /// Wider than `blur_reach`, and deliberately: that is where a *sampled*
3839    /// Gaussian's kernel is truncated, and this expression has no kernel to
3840    /// truncate. It is evaluated everywhere and falls off smoothly, so what
3841    /// bounds it is where the falloff stops being visible rather than where the
3842    /// taps stop. Upstream's `PadForSigma`, whose comment records that three
3843    /// deviations was tried and left a cutoff on large blurs.
3844    fn pad_for_sigma(sigma: f32) -> f32 {
3845        sigma * (sigma / 47.6 + 2.5).min(3.5)
3846    }
3847
3848    /// The gate above, with the one substitution upstream makes, and the paint
3849    /// to draw the result with.
3850    ///
3851    /// Three shapes reach the evaluated blur -- a rounded-rectangle path,
3852    /// `draw_rrect` and `draw_circle` -- and all three share this. The fourth
3853    /// caller of [`Self::analytic_rrect_blur`] deliberately does not: it is
3854    /// building the blurred *ingredient* of a style that combines it with the
3855    /// sharp shape inside a layer, and a substitution good for a whole draw is
3856    /// not good for one operand of a combination.
3857    fn analytic_rrect_blur_draw(
3858        &mut self,
3859        rect: Rect,
3860        radius: f32,
3861        paint: &Paint,
3862    ) -> Option<(Material, f32, Paint)> {
3863        let drawn = Self::erasing_blur_paint(paint);
3864        let (material, pad) = self.analytic_rrect_blur(rect, radius, &drawn)?;
3865        Some((material, pad, drawn))
3866    }
3867
3868    /// `Clear` on a blurred shape, expressed as a mode that respects coverage.
3869    ///
3870    /// The gate below refuses a mode that writes where its source is
3871    /// transparent, and it is right to: the field is evaluated across a quad
3872    /// larger than the shape, so such a mode erases what is behind it in the
3873    /// gap. `Clear` is the one mode that can be admitted anyway, because on a
3874    /// coverage it is not what its factors say. Clearing by an amount `c` is
3875    /// `dst * (1 - c)`, which is `DstOut` against a white source -- and white
3876    /// is exact rather than approximate, since `Clear` discards the source
3877    /// color by definition and cannot care which one it had.
3878    ///
3879    /// This is upstream's own special case, in upstream's own one place.
3880    /// `SolidRRectLikeBlurContents::Render` checks for `BlendMode::kClear`,
3881    /// forces the color to white, and sets a flag that turns the pipeline's
3882    /// blend into a reverse subtraction -- destination factor `One`, source
3883    /// factor `DestinationColor`, so `dst - src * dst`. The arithmetic is the
3884    /// same; upstream reaches it by subtraction because its fragment writes
3885    /// coverage directly, and this reaches it by naming the mode that already
3886    /// means it.
3887    ///
3888    /// Only `Clear`. Upstream does not generalize this and neither does this:
3889    /// the other six modes that ignore coverage have no such reading and stay
3890    /// on the route that gets them wrong, which is `docs/non-parity.md`
3891    /// section 15.
3892    fn erasing_blur_paint(paint: &Paint) -> Paint {
3893        if paint.blend != BlendMode::Clear {
3894            return paint.clone();
3895        }
3896        paint
3897            .clone()
3898            .with_shader(Shader::Solid(Color::WHITE))
3899            .with_blend(BlendMode::DstOut)
3900            // Dropped rather than carried, because it provably cannot matter:
3901            // a color filter transforms the source color and `Clear` discards
3902            // it. Carried into the substitution it would stop being a no-op
3903            // and start changing how much is erased.
3904            .with_color_filter(ColorFilter::None)
3905    }
3906
3907    /// Draw a blurred rounded rectangle without a blur pass, if this one can be.
3908    ///
3909    /// The route upstream takes for the same shape, and the reason it is worth
3910    /// taking is that the general one costs three passes per shape where this
3911    /// costs one draw in the pass already open.
3912    ///
3913    /// `analytic_stroke` cannot answer this one, and the difference is the
3914    /// point: it refuses a mask blur outright, because a sharp distance field
3915    /// on an oversized quad cannot be put inside a layer and blurred. That is
3916    /// exactly the refusal this route lifts, by folding the blur into the field
3917    /// rather than wrapping the draw in one. Its other refusals do carry over
3918    /// and are restated here.
3919    /// Returns the material and how far past the rectangle it must be drawn,
3920    /// both in the shape's own space.
3921    fn analytic_rrect_blur(
3922        &mut self,
3923        rect: Rect,
3924        radius: f32,
3925        paint: &Paint,
3926    ) -> Option<(Material, f32)> {
3927        if !paint.is_visible() || self.clip.is_some_and(Scissor::is_empty) {
3928            return None;
3929        }
3930        // This emits a fragment across the whole padded quad, which is much
3931        // larger than the shape, so a mode that touches the destination where
3932        // the source is transparent would erase what is behind it in the gap.
3933        if !paint.blend.respects_coverage() {
3934            return None;
3935        }
3936        // An image filter wants a layer around the draw, and a quad larger than
3937        // its shape is the wrong thing to put in one.
3938        if !paint.image_filter.is_identity() {
3939            return None;
3940        }
3941        // A fill only. A blurred *stroke* is the blur of a band rather than of
3942        // the shape: a different picture, and not one this expression states.
3943        // A dash is refused with it, since there is no stroke to dash.
3944        if !matches!(paint.style, Style::Fill) {
3945            return None;
3946        }
3947        // The blurred coverage itself. The other three styles are that
3948        // combined with the sharp shape, which the general route assembles out
3949        // of two draws and this cannot say in one.
3950        if paint.mask_blur_style != MaskBlurStyle::Normal {
3951            return None;
3952        }
3953        let shader = paint.effective_shader();
3954        let Shader::Solid(color) = &*shader else {
3955            return None;
3956        };
3957        if radius.is_nan() || radius < 0.0 {
3958            return None;
3959        }
3960        // `is_finite` first, so a sigma that is not a number is refused rather
3961        // than compared: every comparison against NaN is false, so a bare
3962        // `<= 0.0` would let it through.
3963        if !paint.mask_blur.is_finite() || paint.mask_blur <= 0.0 {
3964            return None;
3965        }
3966        // The deviation is in device pixels -- see `non-parity.md` on a shadow's
3967        // elevation -- and everything below is in the shape's own space, so it
3968        // has to be carried across. Getting this wrong is invisible at the
3969        // identity and doubles the blur's tail on a canvas scaled by two.
3970        let affine = self.transform.to_affine()?;
3971        let sx = affine.matrix2.x_axis.length();
3972        let sy = affine.matrix2.y_axis.length();
3973        if !sx.is_finite() || !sy.is_finite() || sx <= 0.0 || sy <= 0.0 {
3974            return None;
3975        }
3976        // One deviation cannot describe a blur that is wider along one axis
3977        // than the other, and this expression carries exactly one. A transform
3978        // that scales the axes differently goes to the general route, which
3979        // blurs in device space and does not care.
3980        if (sx - sy).abs() > 1e-3 * sx.max(sy) {
3981            return None;
3982        }
3983        // Stated in the shape's own space already, so there is nothing to
3984        // convert. It used to be `paint.mask_blur / sx`, which is what a
3985        // device-space sigma needed and what made a blur refuse to grow with
3986        // the transform.
3987        let sigma = paint.mask_blur;
3988
3989        let radius = radius.min(rect.width() / 2.0).min(rect.height() / 2.0);
3990        let material = self.rrect_blur_material(rect, radius, sigma, *color)?;
3991        Some((material, Self::pad_for_sigma(sigma)))
3992    }
3993
3994    /// A blurred convex fill drawn as a shadow mesh, if this one can be.
3995    ///
3996    /// Upstream's route for every mask-blurred fill it has no analytic shape
3997    /// for -- an oval that is not a circle, a rounded rectangle with unequal
3998    /// corners, any other convex path -- and the one `drawShadow` takes for
3999    /// them: `Canvas::AttemptDrawBlurredPathSource`, a mesh from
4000    /// `ShadowPathGeometry` drawn through `ShadowVerticesContents`. A concave
4001    /// path, or one of more than one contour, has no mesh and is blurred the
4002    /// general way, as upstream blurs it.
4003    ///
4004    /// The same eligibility as the analytic rounded rectangle's, for the same
4005    /// reasons, and one difference: a mesh is built per axis, so a transform
4006    /// that scales the axes differently is no reason to refuse.
4007    ///
4008    /// `None` when this route does not apply; otherwise the draw's result.
4009    fn shadow_mesh_blur(&mut self, path: &Path, paint: &Paint) -> Option<Result<()>> {
4010        if !paint.is_visible() || self.clip.is_some_and(Scissor::is_empty) {
4011            return None;
4012        }
4013        // The mesh reaches past the shape, so a mode that writes where its
4014        // source is transparent would erase what is behind the falloff.
4015        if !paint.blend.respects_coverage() {
4016            return None;
4017        }
4018        if !paint.image_filter.is_identity()
4019            || !matches!(paint.style, Style::Fill)
4020            || paint.mask_blur_style != MaskBlurStyle::Normal
4021        {
4022            return None;
4023        }
4024        if !paint.mask_blur.is_finite() || paint.mask_blur <= 0.0 {
4025            return None;
4026        }
4027        let shader = paint.effective_shader();
4028        let Shader::Solid(color) = &*shader else {
4029            return None;
4030        };
4031        let affine = self.transform.to_affine()?;
4032        let scale = Vec2::new(
4033            affine.matrix2.x_axis.length(),
4034            affine.matrix2.y_axis.length(),
4035        );
4036        let reach = emblema_geometry::shadow_reach(paint.mask_blur, scale.x.max(scale.y));
4037        let mesh = emblema_geometry::ambient_shadow_mesh(path, scale, reach)?;
4038        if mesh.is_empty() {
4039            return Some(Ok(()));
4040        }
4041        let to_clip = self.target.projection() * self.transform;
4042        let vertices: Vec<Vertex> = mesh
4043            .positions
4044            .iter()
4045            .zip(&mesh.gaussians)
4046            .map(|(p, g)| {
4047                let clip = to_clip.project_homogeneous(*p);
4048                Vertex::projected([clip.x, clip.y, clip.z], [*g, 0.0])
4049            })
4050            .collect();
4051        Some(self.batch.push_mesh(
4052            &vertices,
4053            &mesh.indices,
4054            Material::ShadowMesh {
4055                color: color.to_array(),
4056            },
4057            paint.color_filter,
4058            paint.blend,
4059            self.clip,
4060            ClipState::content(self.depth),
4061        ))
4062    }
4063
4064    /// The material for a blurred rounded rectangle drawn without a blur pass.
4065    ///
4066    /// Raph Levien's approximation, transcribed from upstream's
4067    /// `SolidRRectLikeBlurContents::PopulateFragContext`, which evaluates the
4068    /// same method. Every line is arithmetic the shader would otherwise repeat
4069    /// per fragment, and none of it is this renderer's invention -- the
4070    /// constants are upstream's, and where one looks arbitrary it is because
4071    /// it was fitted rather than derived.
4072    ///
4073    /// `rect` and `radius` are in the shape's own space, `sigma` in device
4074    /// pixels, as everywhere else here.
4075    fn rrect_blur_material(
4076        &self,
4077        rect: Rect,
4078        radius: f32,
4079        sigma: f32,
4080        color: Color,
4081    ) -> Option<Material> {
4082        // Below one, the approximation is sharper than the pixel grid can show
4083        // and the error function saturates; upstream floors it in the same
4084        // place. The root of two is the conversion between the deviation this
4085        // renderer states and the one the expression below is written in.
4086        let sigma = (sigma * std::f32::consts::SQRT_2).max(1.0);
4087        let mut size = Vec2::new(rect.width(), rect.height());
4088        if !size.x.is_finite() || !size.y.is_finite() || !sigma.is_finite() {
4089            return None;
4090        }
4091        if size.x <= 0.0 || size.y <= 0.0 {
4092            return None;
4093        }
4094        let min_edge = size.x.min(size.y);
4095        let r_max = 0.5 * min_edge;
4096
4097        // Two corner radii rather than the caller's one: a blurred corner is
4098        // rounder than the shape's, and how much rounder depends on the
4099        // deviation. Their ratio becomes the exponent, so a sharp corner under
4100        // a wide blur is measured with a larger exponent than a round one.
4101        let r0 = radius.hypot(sigma * 1.15).min(r_max);
4102        let r1 = radius.hypot(sigma * 2.0).min(r_max);
4103        let exponent = 2.0 * r1 / r0;
4104        let s_inv = 1.0 / sigma;
4105
4106        // Pull the long end in. A rectangle much longer than it is wide blurs
4107        // to something the axis-wise expression makes too eccentric, and this
4108        // shortens the long axis by an amount that vanishes as either side
4109        // grows past the deviation -- which is why it is a pair of Gaussians
4110        // of the sides rather than a ratio.
4111        let falloff = |v: f32| (-(v * s_inv * 0.5).powi(2)).exp();
4112        let delta = 1.25 * sigma * (falloff(size.x) - falloff(size.y));
4113        // Whichever axis is longer is the one shortened, which is a deliberate
4114        // departure from upstream and the only one in this expression.
4115        // Upstream writes `rSize += NegPos(delta)`, which is
4116        // `{min(delta, 0), max(delta, 0)}` -- so it shortens x when x is the
4117        // long axis and *lengthens* y when y is, leaving the same rectangle
4118        // blurred to two different widths depending on which way it is turned.
4119        // Its own comment says "pull in long end", which is what this does in
4120        // both orientations. See `non-parity.md`.
4121        size.x += delta.min(0.0);
4122        size.y += (-delta).min(0.0);
4123
4124        let adjust = size * 0.5 - Vec2::splat(r1);
4125        // Normalizes the fade, so the middle of a shape large against its blur
4126        // reaches full coverage rather than something near it.
4127        let scale = 0.5 * erf7(s_inv * 0.5 * (size.x.max(size.y) - 0.5 * radius));
4128
4129        let center = Vec2::new(
4130            (rect.left + rect.right) / 2.0,
4131            (rect.top + rect.bottom) / 2.0,
4132        );
4133        let to_clip = self.target.projection() * self.transform;
4134        let material = Material::RoundedRectBlur {
4135            color: color.to_array(),
4136            to_local: invert_to_local(to_clip * Affine2::from_translation(center)),
4137            adjust: [adjust.x, adjust.y],
4138            r1,
4139            exponent,
4140            s_inv,
4141            min_edge,
4142            scale,
4143        };
4144        // A field that is not a number puts NaN through every fragment, and a
4145        // NaN coverage is a shape that vanishes or a frame that does. Upstream
4146        // checks the same eight and declines the same way.
4147        [adjust.x, adjust.y, r1, exponent, s_inv, min_edge, scale]
4148            .iter()
4149            .all(|v| v.is_finite())
4150            .then_some(material)
4151    }
4152
4153    /// A paint for the fragment-evaluated rounded rectangle, where one applies.
4154    ///
4155    /// A solid-colored fill or stroke that asked for antialiasing. The material
4156    /// carries a stroke width and an outer radius, and the bench times the stroked
4157    /// case as `stroked field`.
4158    ///
4159    /// Refused: a gradient or an image, which would need its own mapping and this
4160    /// one at once -- the case the push-constant budget was sized against; an
4161    /// aliased fill, which asks for the hard edges the tessellated path gives; and
4162    /// a square-cornered stroked rectangle, for the reason stated where the body
4163    /// declines it.
4164    /// The material, and the clip-to-local mapping it would otherwise carry.
4165    ///
4166    /// Returned beside the material rather than inside it so that two of this
4167    /// shape in different places compare equal and the batch merges them; the
4168    /// mapping rides on the vertices instead. See `Renderer::fill_into_local`.
4169    fn analytic_rrect(
4170        &self,
4171        rect: Rect,
4172        radius: f32,
4173        paint: &Paint,
4174    ) -> Option<(Material, [f32; 12])> {
4175        // Invisible and fully-clipped shapes are rejected before the path is
4176        // built, and this route has to reject them too. It bypasses
4177        // `draw_path`, which is where those checks live -- so an alpha of zero
4178        // went from recording nothing to recording a quad the fragment stage
4179        // discards a pixel at a time.
4180        if !paint.is_visible() || self.clip.is_some_and(Scissor::is_empty) {
4181            return None;
4182        }
4183        // A stroked rectangle with square corners is the one shape this route
4184        // draws differently, and it took a plate sending a rectangle through
4185        // `draw_rect` to notice. A distance field's stroke is the band a fixed
4186        // distance either side of the outline, and at a vertex that band's
4187        // outer edge is an arc -- so the corners come out *rounded*, where
4188        // `dart:ui`'s default join is a miter and the tessellated route gives
4189        // the sharp corner it asks for. Measured on a nine-wide stroke, one
4190        // route draws the corner pixel and the other does not: a difference of
4191        // two hundred and fifty-three out of two hundred and fifty-five.
4192        //
4193        // With a radius the outline has no vertex, so there is no join to get
4194        // wrong and the arc is what the shape is. Only the square-cornered case
4195        // is refused, and only where the caller asked for something other than
4196        // the round join the field would give them anyway.
4197        // A bevel cuts the corner off, which is neither the arc a round join
4198        // gives nor the point a miter does, and no offset of this shape is that
4199        // -- so it is the one join still sent to the tessellator. The other two
4200        // are the outer offset with and without a radius, which is what
4201        // `outer_radius` carries below.
4202        let mitered = match &paint.style {
4203            Style::Stroke(style) if style.width > 0.0 => {
4204                if style.join == LineJoin::Bevel {
4205                    return None;
4206                }
4207                style.join == LineJoin::Miter
4208            }
4209            _ => false,
4210        };
4211        // Widened and dimmed on the same terms the tessellated route is, so
4212        // that which route a shape takes stays invisible. See `thin_stroke`.
4213        let (stroke, coverage) =
4214            thin_stroke(self.transform, analytic_stroke(paint)?, Zero::IsNotAStroke);
4215        let shader = paint.effective_shader();
4216        let Shader::Solid(color) = &*shader else {
4217            return None;
4218        };
4219        // A radius of zero is a plain rectangle, which this field describes as
4220        // well as any other: with no corner to round, the expression is the
4221        // distance to the nearer edge. NaN is not a radius and falls back.
4222        if radius.is_nan() || radius < 0.0 {
4223            return None;
4224        }
4225        let to_clip = self.target.projection() * self.transform;
4226        let center = Vec2::new(
4227            (rect.left + rect.right) / 2.0,
4228            (rect.top + rect.bottom) / 2.0,
4229        );
4230        let clip_to_local = invert_to_local(to_clip * Affine2::from_translation(center));
4231        Some((
4232            Material::RoundedRect {
4233                color: dimmed(*color, coverage),
4234                half_size: [rect.width() / 2.0, rect.height() / 2.0],
4235                // Identity, because the mapping travels on the vertices instead
4236                // -- `clip_to_local` below, applied by `fill_into_local`. It maps a
4237                // clip-space position back into the shape's own space, measured
4238                // from its center, so the distance is measured where the radius
4239                // means what the caller said; measuring in clip space would round
4240                // the corners by different amounts on each axis of a target that is
4241                // not square. Keeping it out of the material is what lets two of
4242                // this shape in different places merge into one draw.
4243                to_local: to_local_columns(Transform2D::IDENTITY),
4244                radius: radius.min(rect.width() / 2.0).min(rect.height() / 2.0),
4245                // A mitered square corner offsets to a square corner, which is a
4246                // radius of nothing. Everything else grows by half the stroke:
4247                // a rounded corner because that is what offsetting an arc does, and
4248                // a round join because the arc is what it asks for.
4249                outer_radius: if mitered && radius <= 0.0 {
4250                    0.0
4251                } else {
4252                    radius.min(rect.width() / 2.0).min(rect.height() / 2.0) + stroke / 2.0
4253                },
4254                stroke,
4255            },
4256            clip_to_local,
4257        ))
4258    }
4259
4260    /// Draw the quad a fragment-evaluated shape is painted onto.
4261    ///
4262    /// Outset by a pixel, because the coverage ramp runs half a pixel either
4263    /// side of the edge: a quad ending exactly at the shape would clip the
4264    /// outer half of its own antialiasing and leave a hard edge on a shape
4265    /// drawn to be soft. Outsetting costs a ring of fragments that compute a
4266    /// coverage of zero.
4267    fn draw_analytic(
4268        &mut self,
4269        rect: Rect,
4270        material: Material,
4271        paint: &Paint,
4272    ) -> Result<&mut Self> {
4273        // A pixel for the coverage ramp, plus half the stroke where one is
4274        // traced: an outline straddles the edge, so it reaches outward by half
4275        // its width beyond the shape it belongs to.
4276        let reach = 1.0
4277            + thin_stroke(
4278                self.transform,
4279                analytic_stroke(paint).unwrap_or(0.0),
4280                Zero::IsNotAStroke,
4281            )
4282            .0 / 2.0;
4283        let outset = Rect::new(
4284            rect.left - reach,
4285            rect.top - reach,
4286            rect.right + reach,
4287            rect.bottom + reach,
4288        );
4289        let render_paint = RenderPaint {
4290            material,
4291            filter: paint.color_filter,
4292            blend: paint.blend,
4293            clip: self.clip,
4294            stencil: ClipState::content(self.depth),
4295        };
4296        self.renderer.fill_into(
4297            &mut self.batch,
4298            &outset.to_path(),
4299            self.transform,
4300            &render_paint,
4301        )?;
4302        Ok(self)
4303    }
4304
4305    /// [`Self::draw_analytic`], with the shape's own space carried on the
4306    /// vertices instead of in the material.
4307    ///
4308    /// Separate rather than an `Option` on the one above, because the two say
4309    /// different things: a material that maps clip space itself is one shape's
4310    /// worth of draw, and one that reads `uv` merges with every other placement
4311    /// of the same shape. Only the rounded rectangle takes this route so far --
4312    /// the ellipse and the blurred rectangle still carry their mapping.
4313    fn draw_analytic_local(
4314        &mut self,
4315        rect: Rect,
4316        material: Material,
4317        paint: &Paint,
4318        clip_to_local: [f32; 12],
4319    ) -> Result<&mut Self> {
4320        let reach = 1.0
4321            + thin_stroke(
4322                self.transform,
4323                analytic_stroke(paint).unwrap_or(0.0),
4324                Zero::IsNotAStroke,
4325            )
4326            .0 / 2.0;
4327        let outset = Rect::new(
4328            rect.left - reach,
4329            rect.top - reach,
4330            rect.right + reach,
4331            rect.bottom + reach,
4332        );
4333        let render_paint = RenderPaint {
4334            material,
4335            filter: paint.color_filter,
4336            blend: paint.blend,
4337            clip: self.clip,
4338            stencil: ClipState::content(self.depth),
4339        };
4340        self.renderer.fill_into_local(
4341            &mut self.batch,
4342            &outset.to_path(),
4343            self.transform,
4344            &render_paint,
4345            clip_to_local,
4346        )?;
4347        Ok(self)
4348    }
4349
4350    /// The shadow an object at `elevation` casts, under one light.
4351    ///
4352    /// The rule rather than the picture, which is why this is a call and not a
4353    /// blurred draw a caller assembles: the whole point of an elevation is
4354    /// that everything at the same height casts a consistent shadow, and
4355    /// consistency is what a rule spread across call sites loses first.
4356    ///
4357    /// The model is a single light above and behind the viewer, which is what
4358    /// Impeller uses and what makes a raised object's shadow fall downward on
4359    /// screen. Three things follow from the elevation and nothing else: the
4360    /// shadow is offset downward by it, blurred in proportion to it, and drawn
4361    /// at a quarter of the stated color's alpha before that alpha is adjusted
4362    /// for the color's own luminance.
4363    ///
4364    /// `elevation` is in device pixels, whatever the transform: the shadow
4365    /// falls that far straight down the screen, as upstream's does. Upstream
4366    /// is handed it in logical pixels and multiplies by a device pixel ratio
4367    /// first (`occluder_z = dpr * elevation`), which is a framework concept
4368    /// rather than a rendering one; a caller who has one should apply it here.
4369    ///
4370    /// `transparent_occluder` is accepted and unused, which is what upstream
4371    /// does with it -- `DlDispatcherBase::drawShadow` takes the flag and its
4372    /// drawing code never reads it. It stays on the signature because
4373    /// `dart:ui` has it, and a caller porting a call should not have to find
4374    /// out that one argument went missing.
4375    pub fn draw_shadow(
4376        &mut self,
4377        path: &Path,
4378        color: Color,
4379        elevation: f32,
4380        _transparent_occluder: bool,
4381    ) -> Result<&mut Self> {
4382        if !elevation.is_finite() || elevation <= 0.0 || color.is_invisible() {
4383            // Nothing at ground level: an object resting on the surface casts
4384            // no shadow, which is the same answer as an invisible one.
4385            return Ok(self);
4386        }
4387
4388        let shade = tonal_shadow_color(color);
4389        let affine = self.transform.to_affine();
4390        // The y axis's stretch, not the larger of the two: upstream divides by
4391        // `GetCurrentTransform().GetScale().y`, the length of the transformed
4392        // y basis vector. Without a basis to read -- perspective -- the single
4393        // factor stands in.
4394        let scale_y = affine
4395            .map(|a| a.matrix2.y_axis.length())
4396            .filter(|s| s.is_finite() && *s > 0.0)
4397            .unwrap_or_else(|| {
4398                let s = max_scale_of(self.transform);
4399                if s.is_finite() && s > 0.0 {
4400                    s
4401                } else {
4402                    1.0
4403                }
4404            });
4405        // Elevation gives a kernel radius, which the blur takes as a
4406        // deviation only after converting. Skipping the conversion is the
4407        // larger half of what made a shadow here twice as soft as upstream's.
4408        //
4409        // Divided by the y scale first and converted after, in upstream's
4410        // order: `Radius{kLightRadius * occluder_z / scale.y}` and then
4411        // `Radius::operator Sigma`. A mask blur's sigma is stated in the space
4412        // the drawing is in and grows with the transform, so a shadow whose
4413        // softness comes from an *elevation* rather than from a length would
4414        // grow with it too -- and upstream's does not. The division cancels
4415        // the multiplication the filter applies, leaving a shadow's softness
4416        // fixed in device pixels however large the caster is drawn;
4417        // `a_shadows_softness_is_fixed_in_device_pixels` is the test. This
4418        // used to convert first and divide after, which divides the
4419        // conversion's half pixel by the scale too: a shadow a quarter of a
4420        // pixel sharper than upstream's at a scale of two.
4421        let sigma = sigma_for_radius(LIGHT_RADIUS * elevation / scale_y);
4422        // Straight down the screen by `elevation` device pixels: upstream's
4423        // `PreConcat(MakeTranslation(0, occluder_z))`, which puts the
4424        // translation before the current transform. There is no pre-concat
4425        // here, so the device offset goes back through the transform's linear
4426        // part, inverted, and is applied as an ordinary translation in local
4427        // units. A plain `translate(0, elevation)` moved it `scale` times as
4428        // far, and under a rotation along the rotated axis.
4429        let device_down = Vec2::new(0.0, elevation);
4430        let down = affine
4431            .map(|a| a.matrix2)
4432            .filter(|m| m.determinant().abs() > f32::EPSILON)
4433            .map(|m| m.inverse() * device_down)
4434            .filter(|v| v.is_finite())
4435            .unwrap_or(Vec2::new(0.0, elevation / scale_y));
4436        let paint = Paint::fill(shade).with_mask_blur(sigma);
4437
4438        // The whole shadow, whatever the occluder is, which is what upstream
4439        // draws: `DlDispatcherBase::drawShadow` takes `transparent_occluder`
4440        // and its drawing code never reads it.
4441        //
4442        // This used to punch the caster's outline out of the shadow for an
4443        // opaque one, on the grounds that the part a caster covers is spent.
4444        // The grounds were sound and the result was not worth them. An opaque
4445        // caster drawn over its own shadow is the arrangement the flag
4446        // describes, and there the two are the same picture -- measured at
4447        // zero of sixty-five thousand bytes differing -- while the punch cost a
4448        // layer, so every shadow was five passes where four will do. A
4449        // deviation that produces identical pixels more slowly has nothing to
4450        // recommend it.
4451        self.save();
4452        self.translate(down.x, down.y);
4453        let failure = self.draw_path(path, &paint).err();
4454        self.restore();
4455        match failure {
4456            Some(e) => Err(e),
4457            None => Ok(self),
4458        }
4459    }
4460
4461    /// Fill or stroke a circle.
4462    ///
4463    /// An antialiased solid fill goes through the same distance field a rounded
4464    /// rectangle does, because it is one: a square whose corner radius is half
4465    /// its side has no straight edge left, and the field reduces exactly to the
4466    /// distance from the center less the radius. So a circle costs two
4467    /// triangles and needs no shader of its own, where four cubics flattened to
4468    /// a tolerance cost vertices in proportion to how large it is drawn.
4469    pub fn draw_circle(&mut self, center: Vec2, radius: f32, paint: &Paint) -> Result<&mut Self> {
4470        self.prepare_destination(paint.blend);
4471        // NaN named rather than caught by a negated comparison, which reads as
4472        // a typo and which clippy objects to on exactly those grounds.
4473        if radius.is_nan() || radius <= 0.0 {
4474            return Ok(self);
4475        }
4476        let bounds = Rect::new(
4477            center.x - radius,
4478            center.y - radius,
4479            center.x + radius,
4480            center.y + radius,
4481        );
4482        // A circle is a rounded rectangle whose corners are half its side, which
4483        // is how the line below already treats it and how upstream states it:
4484        // `DrawOval` on a square sends `RRectBlurShape(rect, width * 0.5)`.
4485        if let Some((material, pad, drawn)) = self.analytic_rrect_blur_draw(bounds, radius, paint) {
4486            return self.draw_analytic(bounds.outset(pad), material, &drawn);
4487        }
4488        if let Some((material, to_local)) = self.analytic_rrect(bounds, radius, paint) {
4489            return self.draw_analytic_local(bounds, material, paint, to_local);
4490        }
4491        let path = circle_path(center, radius);
4492        self.draw_path(&path, paint)
4493    }
4494
4495    /// Fill or stroke an ellipse inscribed in `bounds`.
4496    ///
4497    /// A circle where the bounds are square, and the shape a rounded rectangle
4498    /// cannot become: past half its shorter side a rounded rectangle stops
4499    /// changing, giving a stadium, where an ellipse keeps curving on both axes.
4500    ///
4501    /// An antialiased solid fill is evaluated per fragment like the other
4502    /// shapes here. Everything else is tessellated from four cubics, which
4503    /// approximate an ellipse exactly as well as they approximate a circle --
4504    /// which is to say closely, and not exactly.
4505    pub fn draw_oval(&mut self, bounds: Rect, paint: &Paint) -> Result<&mut Self> {
4506        self.prepare_destination(paint.blend);
4507        if bounds.is_empty() {
4508            return Ok(self);
4509        }
4510        if let Some(material) = self.analytic_ellipse(bounds, paint) {
4511            return self.draw_analytic(bounds, material, paint);
4512        }
4513        let path = oval_path(bounds);
4514        self.draw_path(&path, paint)
4515    }
4516
4517    /// A paint for the fragment-evaluated ellipse, where one applies.
4518    ///
4519    /// The same conditions the rounded rectangle answers to, and for the same
4520    /// reasons.
4521    fn analytic_ellipse(&self, bounds: Rect, paint: &Paint) -> Option<Material> {
4522        if !paint.is_visible() || self.clip.is_some_and(Scissor::is_empty) {
4523            return None;
4524        }
4525        let (stroke, coverage) =
4526            thin_stroke(self.transform, analytic_stroke(paint)?, Zero::IsNotAStroke);
4527        let shader = paint.effective_shader();
4528        let Shader::Solid(color) = &*shader else {
4529            return None;
4530        };
4531        let to_clip = self.target.projection() * self.transform;
4532        let center = Vec2::new(
4533            (bounds.left + bounds.right) / 2.0,
4534            (bounds.top + bounds.bottom) / 2.0,
4535        );
4536        Some(Material::Ellipse {
4537            color: dimmed(*color, coverage),
4538            half_size: [bounds.width() / 2.0, bounds.height() / 2.0],
4539            to_local: invert_to_local(to_clip * Affine2::from_translation(center)),
4540            stroke,
4541        })
4542    }
4543
4544    /// Draw a run of positioned glyphs from one atlas, as a single draw.
4545    ///
4546    /// `atlas_slot` indexes the image table supplied at draw time, and each
4547    /// glyph names where in that atlas its coverage sits. A run is one draw
4548    /// however many glyphs it holds, because the coordinates travel on the
4549    /// vertices rather than in the paint — which is the reason vertices carry
4550    /// them at all, text being the highest draw-count content there is.
4551    ///
4552    /// The paint's color is the text color; its shader is otherwise ignored,
4553    /// since the atlas supplies coverage rather than color. Gradient-filled
4554    /// text needs the run drawn into a layer and the gradient drawn through it,
4555    /// which is a thing a caller can already build out of what is here.
4556    pub fn draw_glyphs(
4557        &mut self,
4558        glyphs: &[PositionedGlyph],
4559        atlas: &Atlas,
4560        atlas_slot: u32,
4561        paint: &Paint,
4562    ) -> Result<&mut Self> {
4563        self.prepare_destination(paint.blend);
4564        if glyphs.is_empty() || !paint.is_visible() {
4565            return Ok(self);
4566        }
4567        if self.clip.is_some_and(Scissor::is_empty) {
4568            return Ok(self);
4569        }
4570        // A run does not go through `draw_path` either, so it has to notice
4571        // these itself -- and did not, which made it the third call to accept a
4572        // filter and quietly draw without one.
4573        if !paint.image_filter.is_identity() {
4574            return self.draw_glyphs_filtered(glyphs, atlas, atlas_slot, paint);
4575        }
4576        if paint.mask_blur > 0.0 {
4577            // The same four styles a shape gets, over the run instead. A run is
4578            // coverage times one solid color, which is exactly the case where
4579            // blurring the coverage and blurring the result agree -- so unlike
4580            // a mesh, there is nothing here to refuse. This is how a text
4581            // shadow is drawn.
4582            return self.draw_masked(
4583                Masked::Glyphs {
4584                    glyphs,
4585                    atlas,
4586                    slot: atlas_slot,
4587                },
4588                paint,
4589            );
4590        }
4591
4592        let color = match &*paint.effective_shader() {
4593            Shader::Solid(color) => color.to_array(),
4594            // A run tints one color, so anything else has no meaning here. The
4595            // first stop of a gradient is a guess at what was meant, and a
4596            // guess drawn is worse than a refusal read.
4597            _ => {
4598                return Err(Error::Unsupported(
4599                    "glyphs take a solid color; fill a layer through a gradient instead",
4600                ))
4601            }
4602        };
4603
4604        let to_clip = self.target.projection() * self.transform;
4605        let mut vertices = Vec::with_capacity(glyphs.len() * 4);
4606        let mut indices = Vec::with_capacity(glyphs.len() * 6);
4607        for glyph in glyphs {
4608            let Some(rect) = atlas.get(glyph.key) else {
4609                // A glyph nobody added would sample whatever texel happens to
4610                // sit at the origin, which draws a plausible smudge. Refusing
4611                // names the glyph instead.
4612                return Err(Error::Unsupported(
4613                    "a glyph in this run is not in the atlas",
4614                ));
4615            };
4616            if rect.width == 0 || rect.height == 0 {
4617                // A space occupies no texels and needs no quad, but it still
4618                // traveled through the run rather than being the caller's to
4619                // filter out.
4620                continue;
4621            }
4622
4623            let [u0, v0, u1, v1] = rect.uv(atlas.size());
4624            let [x, y] = glyph.position;
4625            let [w, h] = glyph.size;
4626            let corners = [
4627                ([x, y], [u0, v0]),
4628                ([x + w, y], [u1, v0]),
4629                ([x + w, y + h], [u1, v1]),
4630                ([x, y + h], [u0, v1]),
4631            ];
4632            let base = vertices.len() as u32;
4633            for ([px, py], uv) in corners {
4634                // Homogeneous, so the atlas coordinate beside it is
4635                // interpolated perspective-correctly rather than swimming
4636                // across the quad.
4637                let clip = to_clip.project_homogeneous(Vec2::new(px, py));
4638                vertices.push(Vertex::projected([clip.x, clip.y, clip.z], uv));
4639            }
4640            indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
4641        }
4642        if indices.is_empty() {
4643            return Ok(self);
4644        }
4645
4646        let slot = self.slot_for(TextureSource::Image(atlas_slot));
4647        self.batch.push_mesh(
4648            &vertices,
4649            &indices,
4650            Material::Glyph { color, slot },
4651            paint.color_filter,
4652            paint.blend,
4653            self.clip,
4654            ClipState::content(self.depth),
4655        )?;
4656        Ok(self)
4657    }
4658
4659    /// Draw a mesh of triangles the caller supplied.
4660    ///
4661    /// The one drawing call whose geometry does not come from tessellating a
4662    /// shape, which is why it is also the one that can produce triangles this
4663    /// renderer would never have made: overlapping, degenerate, wound either
4664    /// way. None of that is checked beyond what [`Vertices`] checks at
4665    /// construction, because a mesh is a caller saying what to draw rather
4666    /// than what to draw *around*, and second-guessing it would defeat the
4667    /// point.
4668    ///
4669    /// Not antialiased. Coverage here comes from the rasterizer's own rule
4670    /// rather than from a distance field or a tessellated feather, and the
4671    /// interior edges of a mesh are seams between triangles that must not be
4672    /// feathered at all -- a mesh whose triangles each faded at their borders
4673    /// would show a lattice of its own construction.
4674    ///
4675    /// Texture coordinates, where the mesh carries them, require an image
4676    /// paint: they say where in a texture each vertex reads, and a paint with
4677    /// no texture leaves them meaning nothing. The reverse is allowed -- an
4678    /// image paint with no coordinates maps by position, the same as on any
4679    /// other shape.
4680    pub fn draw_vertices(&mut self, mesh: &Vertices, paint: &Paint) -> Result<&mut Self> {
4681        self.prepare_destination(paint.blend);
4682        if mesh.is_empty() || !paint.is_visible() {
4683            return Ok(self);
4684        }
4685        if self.clip.is_some_and(Scissor::is_empty) {
4686            return Ok(self);
4687        }
4688        // The same routing `draw_path` does, and it has to be repeated here
4689        // because a mesh does not go through `draw_path` at all. Left out, an
4690        // image filter on a mesh -- or on an atlas, which is a mesh by the time
4691        // it arrives -- was accepted and silently dropped.
4692        if !paint.image_filter.is_identity() {
4693            return self.draw_vertices_filtered(mesh, paint);
4694        }
4695        if paint.mask_blur > 0.0 {
4696            // A mask blur blurs coverage and then fills through it, so the fill
4697            // has to have a value everywhere the blurred coverage reaches --
4698            // including outside the shape, where the halo is. A paint has one
4699            // there, whether it is a color or a gradient, because a paint is a
4700            // function of position. Per-vertex colors do not: they are defined
4701            // on the mesh's own triangles and nowhere else, and the halo has
4702            // nothing to take its color from.
4703            //
4704            // So the refusal is about where the color comes from rather than
4705            // about meshes. A mesh built from positions alone is filled by the
4706            // paint exactly as a path is, and takes the same route.
4707            if mesh.colors().is_empty() {
4708                return self.draw_masked(Masked::Mesh(mesh), paint);
4709            }
4710            // Refused rather than dropped, and rather than approximated:
4711            // extrapolating vertex colors into the halo would be inventing a
4712            // picture, which is the substitution this renderer refuses.
4713            return Err(Error::Unsupported(
4714                "a mask blur over a mesh with per-vertex colors has no color for \
4715                 its halo; draw the mesh into a blurred layer instead",
4716            ));
4717        }
4718
4719        let textured = !mesh.texture_coords().is_empty();
4720        // An image mesh has a material of its own, which samples the sheet at
4721        // the interpolated coordinate. Every other shader reads its coordinate
4722        // from the fragment's position, and the flag passed to the batch below
4723        // is what redirects it to the vertices instead -- so the material is
4724        // the ordinary one and nothing here has to know which kind it is.
4725        //
4726        // This used to refuse anything but an image, and the refusal said the
4727        // coordinates needed an image paint to read. `dart:ui` reads whatever
4728        // color source the paint carries at a mesh's coordinates, image or not.
4729        //
4730        // It then refused a caller's program alone, on the reasoning that a
4731        // program replaces this renderer's fragment shader outright and so has
4732        // nowhere for a per-vertex coordinate to arrive. That was wrong, and
4733        // wrong about this renderer rather than about upstream: a program
4734        // replaces the *fragment* stage, and the vertex stage it runs behind is
4735        // this renderer's own whatever the fragment does. That stage hands on
4736        // `uv` beside `clip`, and a program declaring the same `VertexOutput`
4737        // -- which one has to, to be a pipeline here at all -- receives both.
4738        //
4739        // So a program reads the mesh's coordinate by reading `in.uv`, and
4740        // chooses, where every built-in shader is told which to use by the flag
4741        // below. `effect_mesh_uv.wgsl` is the fixture that proves it: the
4742        // sibling of `effect.wgsl` differing in one line.
4743        let at_coords = textured && !matches!(paint.shader, Shader::Image { .. });
4744        // A mesh with colors of its own blends the paint's result into them,
4745        // and upstream fades what that blend produced by the paint's alpha:
4746        // `AtlasContents` and the vertices contents both scale their output,
4747        // not their texture. So the material is the paint at full strength
4748        // and the opacity rides on the draw, applied after the blend. Under
4749        // `Modulate` the two orders are one product; under `SrcOver` a sprite
4750        // faded first lets its color show through, which upstream's does not.
4751        //
4752        // Not a caller's program: its fragment stage is its own, and reads
4753        // neither the blend nor this. A mesh without colors blends with none,
4754        // and its paint fades as every other draw's does.
4755        let opacity = paint.effective_opacity();
4756        let fades_after = !mesh.colors().is_empty()
4757            && !matches!(paint.shader, Shader::RuntimeEffect { .. })
4758            && opacity < 1.0;
4759        let full;
4760        let (paint, opacity) = if fades_after {
4761            full = paint.clone().with_opacity(1.0);
4762            (&full, opacity)
4763        } else {
4764            (paint, 1.0)
4765        };
4766        let material = match (&paint.shader, textured) {
4767            (Shader::Image { .. }, true) => self.mesh_material(paint)?,
4768            _ if at_coords => self.material_at_texture_coords(paint),
4769            _ => self.material_for(paint),
4770        };
4771
4772        let to_clip = self.target.projection() * self.transform;
4773        let coords = mesh.texture_coords();
4774        let colors = mesh.colors();
4775        let vertices: Vec<Vertex> = mesh
4776            .positions()
4777            .iter()
4778            .enumerate()
4779            .map(|(i, position)| {
4780                let clip = to_clip.project_homogeneous(*position);
4781                let uv = coords.get(i).copied().unwrap_or(Vec2::ZERO);
4782                let vertex = Vertex::projected([clip.x, clip.y, clip.z], [uv.x, uv.y]);
4783                match colors.get(i) {
4784                    // Premultiplied here rather than in the shader, because
4785                    // what the rasterizer interpolates between two vertices is
4786                    // what gets multiplied in, and interpolating straight color
4787                    // across an edge whose alpha varies gives a color neither
4788                    // end asked for.
4789                    Some(color) => vertex.with_color(premultiplied(*color)),
4790                    None => vertex,
4791                }
4792            })
4793            .collect();
4794
4795        self.batch.push_mesh_tinted(
4796            &vertices,
4797            mesh.indices(),
4798            material,
4799            paint.color_filter,
4800            paint.blend,
4801            self.clip,
4802            ClipState::content(self.depth),
4803            paint.tint_blend,
4804            opacity,
4805            // Where the coordinates say something the material cannot work out
4806            // for itself. An image mesh is excluded because it already reads
4807            // them, through a material of its own; everything else -- a
4808            // gradient, a caller's program -- derives its coordinate from the
4809            // fragment's position unless told otherwise, and this is the
4810            // telling. The material above was built to match.
4811            at_coords,
4812        )?;
4813        Ok(self)
4814    }
4815
4816    /// Draw many pieces of one sheet, each with its own transform, in one draw.
4817    ///
4818    /// This is `draw_vertices` with the mesh built for you, and building it is
4819    /// the part worth not getting wrong: each sprite is a quad running from
4820    /// the origin to its source's size, placed by its transform, with the
4821    /// source rectangle divided by the sheet's size to become the
4822    /// coordinates its corners read. A caller assembling that themselves has
4823    /// four chances per sprite to transpose an axis.
4824    ///
4825    /// One draw for the whole batch: a hundred sprites from one sheet differ
4826    /// only in their vertices, so they have no reason to be a hundred draws.
4827    /// Anything that would split them -- a different sheet, a different paint
4828    /// -- is a second call.
4829    ///
4830    /// A loop over [`Self::draw_vertices`] would end up as one draw too, since
4831    /// a batch merges adjacent draws that differ in nothing. What this saves
4832    /// is the per-sprite arithmetic rather than the draw calls.
4833    ///
4834    /// `sheet` is the size of the uploaded texture in texels, which the paint
4835    /// does not carry: a recording is built without touching a device and has
4836    /// never seen how large the texture is.
4837    ///
4838    /// Each sprite's [`Sprite::color`] goes to its four corners and combines
4839    /// with what the sheet gives there by the paint's
4840    /// [`Paint::tint_blend`], as `dart:ui`'s colors and blend mode do: the
4841    /// sprite the source, its color the destination. [`Paint::opacity`]
4842    /// fades what that produced, as upstream's atlas fades by the paint's
4843    /// alpha, not the sprite before it meets its color.
4844    pub fn draw_atlas(
4845        &mut self,
4846        sprites: &[Sprite],
4847        sheet: Extent2D,
4848        paint: &Paint,
4849    ) -> Result<&mut Self> {
4850        self.prepare_destination(paint.blend);
4851        if sprites.is_empty() || !paint.is_visible() {
4852            return Ok(self);
4853        }
4854        if sheet.width == 0 || sheet.height == 0 {
4855            return Err(Error::Unsupported(
4856                "a sprite sheet with no texels has nothing to read",
4857            ));
4858        }
4859        if !sprites.iter().all(|s| s.source.is_finite()) {
4860            return Err(Error::Unsupported(
4861                "a sprite's source rectangle is not a finite number",
4862            ));
4863        }
4864
4865        let texels = Vec2::new(sheet.width as f32, sheet.height as f32);
4866        let mut positions = Vec::with_capacity(sprites.len() * 4);
4867        let mut coords = Vec::with_capacity(sprites.len() * 4);
4868        let mut colors = Vec::with_capacity(sprites.len() * 4);
4869        let mut indices = Vec::with_capacity(sprites.len() * 6);
4870        for sprite in sprites {
4871            let source = &sprite.source;
4872            let size = Vec2::new(source.width, source.height);
4873            let origin = Vec2::new(source.x, source.y);
4874            // Corners in the same order for both, so a coordinate and the
4875            // position it belongs to are written by one step of the loop and
4876            // cannot come apart.
4877            let corners = [
4878                Vec2::ZERO,
4879                Vec2::new(size.x, 0.0),
4880                size,
4881                Vec2::new(0.0, size.y),
4882            ];
4883            let base = positions.len() as u32;
4884            for corner in corners {
4885                positions.push(sprite.transform.transform_point2(corner));
4886                coords.push((origin + corner) / texels);
4887                // The same color at all four corners: a sprite is tinted as a
4888                // whole, and a gradient across one is a mesh rather than a
4889                // sprite.
4890                colors.push(sprite.color);
4891            }
4892            indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
4893        }
4894
4895        let mesh = Vertices::full(VertexMode::Triangles, positions, coords, colors, indices)?;
4896        self.draw_vertices(&mesh, paint)
4897    }
4898
4899    /// The material for a mesh reading a texture at its own coordinates.
4900    ///
4901    /// Separate from [`Self::material_for`] because an image drawn on a shape
4902    /// and an image drawn on a mesh are different materials rather than one
4903    /// material in two modes -- the mapping, and the source rectangle that
4904    /// selects part of a sheet, are both things the vertices have already
4905    /// said. A caller wanting one sprite from a sheet states its texels in the
4906    /// coordinates.
4907    fn mesh_material(&mut self, paint: &Paint) -> Result<Material> {
4908        // The same as a source rectangle, below: the coordinates already say
4909        // where the image lands.
4910        if paint.shader_transform != Transform2D::IDENTITY {
4911            return Err(Error::Unsupported(
4912                "a textured mesh states its own coordinates; put the shader transform in them",
4913            ));
4914        }
4915        let shader = paint.effective_shader();
4916        let Shader::Image {
4917            slot,
4918            alpha,
4919            tile,
4920            tint,
4921            source,
4922            sampling,
4923            ..
4924        } = &*shader
4925        else {
4926            return Err(Error::Unsupported("a mesh material needs an image paint"));
4927        };
4928        // A source rectangle and a per-vertex coordinate are two answers to
4929        // the same question, and applying one on top of the other would mean a
4930        // coordinate of one landed at the rectangle's far edge rather than at
4931        // the texture's. Refused rather than ignored: a caller who set it
4932        // meant something by it, and the mesh is where they say it instead.
4933        if *source != Rect::new(0.0, 0.0, 1.0, 1.0) {
4934            return Err(Error::Unsupported(
4935                "a textured mesh states its own coordinates; put the source rectangle in them",
4936            ));
4937        }
4938        let table_slot = self.slot_for(TextureSource::Image(*slot));
4939        Ok(Material::Mesh {
4940            slot: table_slot,
4941            alpha: *alpha,
4942            tint: tint.to_array(),
4943            tile: *tile,
4944            sampling: *sampling,
4945        })
4946    }
4947
4948    /// Draw a run of points, joined as the mode says.
4949    ///
4950    /// A point is a segment of no length, which is what decides how it looks:
4951    /// the stroke's cap is the whole of the shape. A round cap gives a dot the
4952    /// width across, a square cap a square of that side, and a butt cap --
4953    /// which adds nothing to either end of a segment -- gives nothing at all.
4954    /// That is not a special case being handled; it is the only reading of a
4955    /// zero-length segment that stays consistent with how every other stroke
4956    /// is drawn.
4957    ///
4958    /// Takes the stroke's width even from a paint asking to fill, since there
4959    /// is no interior to fill and a point with no width is not a shape.
4960    pub fn draw_points(
4961        &mut self,
4962        mode: PointMode,
4963        points: &[Vec2],
4964        paint: &Paint,
4965    ) -> Result<&mut Self> {
4966        self.prepare_destination(paint.blend);
4967        let stroke = match &paint.style {
4968            Style::Stroke(stroke) => *stroke,
4969            Style::Fill => StrokeStyle::default(),
4970        };
4971        // Negative only, which is upstream's guard -- `PointFieldGeometry`
4972        // refuses `radius_ < 0.0` and widens everything else. A width of zero is
4973        // a point one pixel across, the same reading a zero-width stroke gets.
4974        if !stroke.width.is_finite() || stroke.width < 0.0 {
4975            return Ok(self);
4976        }
4977
4978        match mode {
4979            // One draw for the whole field, which is what upstream's
4980            // `PointFieldGeometry` produces and what this used to fail to.
4981            //
4982            // It used to be a draw per point, and the reason is worth keeping
4983            // because it is not the obvious one. The other two modes below
4984            // issue a call per segment and still come out as one draw: a batch
4985            // merges draws that share a material, and consecutive segments do.
4986            // A point did not, because the analytic circle it went through
4987            // carries its center in `to_local` -- so two points at two places
4988            // were two materials, and no number of them could merge.
4989            //
4990            // `Material::PointField` is the same field with the center taken
4991            // off the paint and put on the vertices, as the unit circle's
4992            // corners in the texture coordinate. Every point is then the same
4993            // material and the field is one draw, with the edge each of them
4994            // had: the shader differentiates the implicit function across the
4995            // pixel rather than forming a distance, and a derivative of an
4996            // interpolated value is as good as one of a computed value.
4997            PointMode::Points => {
4998                let radius = point_radius(self.transform, stroke.width);
4999                if !matches!(stroke.cap, LineCap::Round | LineCap::Square) {
5000                    // A butt cap extends a segment by nothing, and nothing is
5001                    // what a segment of no length becomes.
5002                    return Ok(self);
5003                }
5004                let round = matches!(stroke.cap, LineCap::Round);
5005                // A mask blur or an image filter wants a layer around the
5006                // draw, which is machinery the per-point route already reaches
5007                // through `draw_circle` and this one skips entirely. Two tests
5008                // that walk every call taking a paint caught exactly that: the
5009                // field accepted a blur and drew what it draws without one.
5010                //
5011                // The condition is the same one `analytic_stroke` states for
5012                // the same reason, and it is worth keeping the shape of that
5013                // rule rather than a list: every route that needs a layer has
5014                // to decline here.
5015                if paint.mask_blur > 0.0 || !paint.image_filter.is_identity() {
5016                    return self.draw_points_individually(points, &stroke, paint);
5017                }
5018                let material = self.material_for(paint);
5019                let Material::Solid(color) = material else {
5020                    // A field takes one color, which is what a point field is.
5021                    // Anything else keeps the old route, where each point is
5022                    // its own shape and can carry its own mapping.
5023                    return self.draw_points_individually(points, &stroke, paint);
5024                };
5025
5026                // A round cap's quad is a pixel wider than the disc, for the
5027                // reason `draw_analytic` outsets its own: the coverage ramp
5028                // runs half a pixel either side of the edge, and a quad ending
5029                // exactly on the circle clips the outer half of its own
5030                // antialiasing. Measured without it, ninety-two pixels of the
5031                // frame differed from the same dots drawn one at a time, at
5032                // the four places the circle meets its quad.
5033                //
5034                // The texture coordinate is scaled to match, so that the unit
5035                // circle still falls where the disc's edge is rather than at
5036                // the corner of the widened quad. A square cap is the quad
5037                // itself and takes neither: its coordinates are zero, where
5038                // the field is saturated, so it covers what it is given.
5039                let (extent, coord) = if round {
5040                    (radius + 1.0, (radius + 1.0) / radius.max(1e-6))
5041                } else {
5042                    (radius, 0.0)
5043                };
5044                let to_clip = self.target.projection() * self.transform;
5045                let mut vertices: Vec<Vertex> = Vec::with_capacity(points.len() * 4);
5046                let mut indices: Vec<u32> = Vec::with_capacity(points.len() * 6);
5047                for point in points {
5048                    if !point.is_finite() {
5049                        continue;
5050                    }
5051                    let base = vertices.len() as u32;
5052                    for (dx, dy) in [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)] {
5053                        let at = Vec2::new(point.x + dx * extent, point.y + dy * extent);
5054                        let clip = to_clip.project_homogeneous(at);
5055                        vertices.push(Vertex::projected(
5056                            [clip.x, clip.y, clip.z],
5057                            [dx * coord, dy * coord],
5058                        ));
5059                    }
5060                    indices.extend([base, base + 1, base + 2, base, base + 2, base + 3]);
5061                }
5062                if indices.is_empty() {
5063                    return Ok(self);
5064                }
5065                self.batch.push_mesh_tinted(
5066                    &vertices,
5067                    &indices,
5068                    Material::PointField { color },
5069                    paint.color_filter,
5070                    paint.blend,
5071                    self.clip,
5072                    ClipState::content(self.depth),
5073                    paint.tint_blend,
5074                    1.0,
5075                    false,
5076                )?;
5077            }
5078            PointMode::Lines => {
5079                for pair in points.chunks_exact(2) {
5080                    self.draw_line(pair[0], pair[1], paint)?;
5081                }
5082            }
5083            PointMode::Polygon => {
5084                if points.len() >= 2 {
5085                    let mut b = PathBuilder::new();
5086                    b.move_to(points[0]);
5087                    for point in &points[1..] {
5088                        b.line_to(*point);
5089                    }
5090                    self.draw_path(&b.build(), paint)?;
5091                }
5092            }
5093        }
5094        Ok(self)
5095    }
5096
5097    /// The field drawn a point at a time, for a paint a field cannot carry.
5098    ///
5099    /// A point field is one color by construction -- the material holds one --
5100    /// so a gradient or an image paint still goes through the shape each point
5101    /// has, and costs a draw each. That is the old behavior kept for the case
5102    /// it was right for rather than a fallback nobody exercises: `dart:ui`
5103    /// allows any paint on `drawPoints`, and a caller who asks for a gradient
5104    /// across a field should get one.
5105    fn draw_points_individually(
5106        &mut self,
5107        points: &[Vec2],
5108        stroke: &StrokeStyle,
5109        paint: &Paint,
5110    ) -> Result<&mut Self> {
5111        // Widened on the same terms the field route is, so which route a point
5112        // takes stays invisible -- this one is reached for a mask blur, an image
5113        // filter or a shader, none of which changes how small a point may be.
5114        let radius = point_radius(self.transform, stroke.width);
5115        // Filled rather than stroked: what is being drawn is the cap itself,
5116        // and asking the stroker for a segment of no length is asking it for a
5117        // direction that does not exist.
5118        let dot = paint.clone().with_style(Style::Fill);
5119        for point in points {
5120            if !point.is_finite() {
5121                continue;
5122            }
5123            match stroke.cap {
5124                LineCap::Round => {
5125                    self.draw_circle(*point, radius, &dot)?;
5126                }
5127                LineCap::Square => {
5128                    self.draw_rect(
5129                        Rect::new(
5130                            point.x - radius,
5131                            point.y - radius,
5132                            point.x + radius,
5133                            point.y + radius,
5134                        ),
5135                        &dot,
5136                    )?;
5137                }
5138                LineCap::Butt => {}
5139            }
5140        }
5141        Ok(self)
5142    }
5143
5144    /// Draw a finished recording into this one.
5145    ///
5146    /// `dart:ui` calls this `drawPicture`, and it is a smaller thing here than
5147    /// there, which is worth saying plainly. An `SkPicture` is a command list,
5148    /// so replaying one under a new transform re-runs the commands and
5149    /// re-tessellates at the new scale. A [`Recording`] is already tessellated:
5150    /// its paths were flattened at a tolerance taken from the transform in force
5151    /// when they were recorded, and its vertices are in clip space. Magnified,
5152    /// it shows the polygon it was flattened to.
5153    ///
5154    /// So this composes scenes at about the scale they were recorded at. It is
5155    /// not the reuse optimization the same call is elsewhere, and a caller who
5156    /// wants that should re-record.
5157    ///
5158    /// What it costs is a layer, because that is what it is: the recording's
5159    /// passes are taken as they are and its root becomes an image this canvas
5160    /// samples. Nothing is re-recorded and no geometry is touched, which is
5161    /// what makes it cheap and also what makes it unable to re-tessellate.
5162    ///
5163    /// # Slots
5164    ///
5165    /// A recording naming a caller's image by index keeps that index. The two
5166    /// recordings are submitted with one image table, so an index means the
5167    /// same thing in both -- a caller composing recordings that disagree about
5168    /// what image three is has to renumber before recording, which is a thing
5169    /// they can see and this call cannot.
5170    ///
5171    /// Its layers and its baked gradients are renumbered, since those name
5172    /// positions in lists this recording is appending to.
5173    pub fn draw_recording(&mut self, recording: &Recording, paint: &Paint) -> Result<&mut Self> {
5174        self.prepare_destination(paint.blend);
5175        if recording.is_empty() || !paint.is_visible() {
5176            return Ok(self);
5177        }
5178        if self.clip.is_some_and(Scissor::is_empty) {
5179            return Ok(self);
5180        }
5181
5182        // Where the passes and ramps being appended will land. Taken before
5183        // anything is pushed, because every index inside the recording is
5184        // relative to lists that start here.
5185        let pass_offset = self.finished.len();
5186        let ramp_offset = self.ramps.len();
5187        self.ramps.extend(recording.ramps.iter().cloned());
5188
5189        for pass in &recording.passes {
5190            let mut pass = pass.clone();
5191            for source in &mut pass.sources {
5192                *source = match *source {
5193                    // A layer names a pass by position in the recording it came
5194                    // from, and that recording's passes are now further along.
5195                    TextureSource::Layer(index) => TextureSource::Layer(index + pass_offset),
5196                    TextureSource::Ramp(index) => TextureSource::Ramp(index + ramp_offset),
5197                    // The caller's own table, which both recordings share.
5198                    TextureSource::Image(index) => TextureSource::Image(index),
5199                };
5200            }
5201            self.finished.push(pass);
5202        }
5203
5204        // The recording's root is the image this canvas now samples, and every
5205        // other pass it brought is a layer feeding that one.
5206        let root = self.finished.len() - 1;
5207        let slot = self.slot_for(TextureSource::Layer(root));
5208
5209        // The recording rendered at its own extent, and it lands here at that
5210        // size with its top-left at the origin of the current transform. A
5211        // recording is a picture rather than a shape, so it has no bounds of
5212        // its own to place -- where it goes is what the transform says.
5213        let extent = recording.extent;
5214        let placement = Rect::new(0.0, 0.0, extent.width as f32, extent.height as f32);
5215        // The mapping from a fragment's clip position back to a texel of the
5216        // recording, which is the same pair a layer composite builds -- except
5217        // that a layer sits at a known place in its parent and a recording is
5218        // placed by the transform, so the mapping is built from that instead.
5219        //
5220        // Clip space runs from -1 to 1 and upward, so the axes are halved and Y
5221        // is negated. Inverting the transform is what carries a fragment back
5222        // into the recording's own coordinates; a transform that folds the
5223        // plane has no inverse, and the geometry collapses with it, so both
5224        // halves go together and nothing is drawn.
5225        let to_clip = self.target.projection() * self.transform;
5226        if to_clip.determinant().abs() <= f32::EPSILON {
5227            return Ok(self);
5228        }
5229        // The recording's texture spans its own extent from the origin, so
5230        // that rectangle carried through the transform is the placement, and
5231        // the mapping the shader wants is its inverse.
5232        let picture_to_clip =
5233            to_clip * Affine2::from_scale(Vec2::new(extent.width as f32, extent.height as f32));
5234        if !picture_to_clip.is_finite() {
5235            return Ok(self);
5236        }
5237        let material = Material::Image {
5238            to_local: invert_to_local(picture_to_clip),
5239            slot,
5240            alpha: 1.0,
5241            tile: [TileMode::Clamp; 2],
5242            // At its own size a texel lands on a pixel, and under a transform
5243            // the recording is resampled -- which is what a picture drawn
5244            // scaled means, and the same answer a matrix image filter gives.
5245            sampling: Sampling::Linear,
5246            source: [0.0, 0.0, 1.0, 1.0],
5247            tint: [1.0, 1.0, 1.0, 1.0],
5248        };
5249        let render_paint = RenderPaint {
5250            material,
5251            filter: paint.color_filter,
5252            blend: paint.blend,
5253            clip: self.clip,
5254            stencil: ClipState::content(self.depth),
5255        };
5256        self.renderer.fill_into(
5257            &mut self.batch,
5258            &placement.to_path(),
5259            self.transform,
5260            &render_paint,
5261        )?;
5262        Ok(self)
5263    }
5264
5265    /// Fill the ring between two rounded rectangles.
5266    ///
5267    /// One path of two contours filled by the even-odd rule, which is what
5268    /// makes the inner one a hole rather than a second ring drawn on top. A
5269    /// caller could assemble this, and the reason not to leave them to it is
5270    /// the rule: two contours wound the same way fill solid under the nonzero
5271    /// rule and hollow under even-odd, and which one a border needs is not
5272    /// something to rediscover per call site.
5273    pub fn draw_drrect(
5274        &mut self,
5275        outer: Rect,
5276        outer_radius: f32,
5277        inner: Rect,
5278        inner_radius: f32,
5279        paint: &Paint,
5280    ) -> Result<&mut Self> {
5281        self.prepare_destination(paint.blend);
5282        if outer.is_empty() {
5283            return Ok(self);
5284        }
5285        self.draw_drrect_with_radii(
5286            outer,
5287            [[outer_radius; 2]; 4],
5288            inner,
5289            [[inner_radius; 2]; 4],
5290            paint,
5291        )
5292    }
5293
5294    /// A ring between two rounded rectangles whose corners need not match.
5295    ///
5296    /// [`Self::draw_drrect`] with the eight numbers each, and the same shape:
5297    /// two contours filled even-odd, which is what makes the inner one a hole.
5298    /// Each rectangle's radii are fitted to it on its own, since a ring is two
5299    /// rounded rectangles and not one shape with a thickness.
5300    pub fn draw_drrect_with_radii(
5301        &mut self,
5302        outer: Rect,
5303        outer_radii: RoundingRadii,
5304        inner: Rect,
5305        inner_radii: RoundingRadii,
5306        paint: &Paint,
5307    ) -> Result<&mut Self> {
5308        self.prepare_destination(paint.blend);
5309        if outer.is_empty() {
5310            return Ok(self);
5311        }
5312        let mut b = PathBuilder::new().with_fill_rule(FillRule::EvenOdd);
5313        outer.add_rounded_contour_with_radii(&mut b, outer.fitted_radii(outer_radii));
5314        if !inner.is_empty() {
5315            inner.add_rounded_contour_with_radii(&mut b, inner.fitted_radii(inner_radii));
5316        }
5317        self.draw_path(&b.build(), paint)
5318    }
5319
5320    /// Fill everything the clip still admits.
5321    ///
5322    /// `dart:ui` calls this `drawPaint`. What it fills is the clip rather than
5323    /// the target, which is why it is a call and not a rectangle a caller
5324    /// writes: the rectangle they would need is the clip's bounds carried back
5325    /// through the current transform, and getting that wrong is invisible
5326    /// until a transform is in force.
5327    ///
5328    /// The bounds are conservative, so this may cover more than the clip
5329    /// admits -- and the clip then removes the excess, which is what makes a
5330    /// superset the safe direction to be wrong in.
5331    pub fn draw_paint(&mut self, paint: &Paint) -> Result<&mut Self> {
5332        self.prepare_destination(paint.blend);
5333        let bounds = self.local_clip_bounds();
5334        if bounds.is_empty() {
5335            return Ok(self);
5336        }
5337        self.draw_rect(bounds, paint)
5338    }
5339
5340    /// Fill everything the clip admits with one color.
5341    ///
5342    /// `dart:ui` calls this `drawColor`. Distinct from [`Self::clear`], which
5343    /// replaces the whole target and ignores the clip: this is a draw, so it
5344    /// blends and it obeys what is in force.
5345    pub fn draw_color(&mut self, color: Color, blend: BlendMode) -> Result<&mut Self> {
5346        self.prepare_destination(blend);
5347        self.draw_paint(&Paint::fill(color).with_blend(blend))
5348    }
5349
5350    /// Draw an image stretched by its middle, keeping its corners.
5351    ///
5352    /// `dart:ui` calls this `drawImageNine`, and it is the shape every
5353    /// resizable panel with a border is made of. `center` is the part of the
5354    /// image, in texels, that may stretch; what surrounds it is divided into
5355    /// eight pieces that stretch along one axis or neither.
5356    ///
5357    /// A caller could write the nine draws. The reason not to leave them to it
5358    /// is the rule rather than the arithmetic: which pieces stretch in which
5359    /// direction is the whole of what a nine-patch means, and nine call sites
5360    /// are nine chances to stretch a corner.
5361    ///
5362    /// The paint supplies the blend, the filters, its opacity and whether the
5363    /// edges are antialiased; its shader is replaced, since each of the nine
5364    /// pieces needs its own. The opacity fades each piece, which is the same
5365    /// picture as fading the whole: the pieces tile the destination without
5366    /// overlapping. Upstream's `NinePatchConverter` draws nine image
5367    /// rectangles with the one paint, alpha included, and no layer.
5368    ///
5369    /// A center reaching an edge leaves pieces of no width or height, and
5370    /// those are skipped rather than drawn empty. A center outside the image
5371    /// entirely is refused, since there is no reading of it that leaves nine
5372    /// pieces.
5373    pub fn draw_image_nine(
5374        &mut self,
5375        slot: u32,
5376        size: Extent2D,
5377        center: Rect,
5378        into: Rect,
5379        paint: &Paint,
5380    ) -> Result<&mut Self> {
5381        self.prepare_destination(paint.blend);
5382        if size.width == 0 || size.height == 0 || into.is_empty() {
5383            return Ok(self);
5384        }
5385        let (w, h) = (size.width as f32, size.height as f32);
5386        if center.left < 0.0
5387            || center.top < 0.0
5388            || center.right > w
5389            || center.bottom > h
5390            || center.right < center.left
5391            || center.bottom < center.top
5392        {
5393            return Err(Error::Unsupported(
5394                "a nine-patch center must lie within the image it divides",
5395            ));
5396        }
5397        if paint.mask_blur > 0.0 {
5398            // A nine-patch is nine quads, and each is drawn on its own. A mask
5399            // blur asked for here would soften each of them separately -- nine
5400            // haloes with seams between them rather than one softened patch --
5401            // which is not what was asked for and is not worth guessing at.
5402            //
5403            // Refused deliberately, because it used to be refused by accident:
5404            // the pieces are drawn with an image paint, and a mask blur over
5405            // anything that varied was refused wholesale further down. That is
5406            // no longer true, so the reason has to live where it applies.
5407            return Err(Error::Unsupported(
5408                "a mask blur over a nine-patch; its pieces are drawn separately \
5409                 and would each be softened on their own",
5410            ));
5411        }
5412
5413        // The three spans along each axis, in texels and then in the
5414        // destination. The outer two keep their size and the middle takes
5415        // whatever is left, which is the whole of the rule.
5416        let source_x = [0.0, center.left, center.right, w];
5417        let source_y = [0.0, center.top, center.bottom, h];
5418        let left_keep = center.left;
5419        let right_keep = w - center.right;
5420        let top_keep = center.top;
5421        let bottom_keep = h - center.bottom;
5422        // A destination too small to hold both fixed edges would give the
5423        // middle a negative size, so the edges are scaled down together rather
5424        // than one of them overrunning the other.
5425        let squeeze_x = ((into.right - into.left) / (left_keep + right_keep)).min(1.0);
5426        let squeeze_y = ((into.bottom - into.top) / (top_keep + bottom_keep)).min(1.0);
5427        let dest_x = [
5428            into.left,
5429            into.left + left_keep * squeeze_x,
5430            into.right - right_keep * squeeze_x,
5431            into.right,
5432        ];
5433        let dest_y = [
5434            into.top,
5435            into.top + top_keep * squeeze_y,
5436            into.bottom - bottom_keep * squeeze_y,
5437            into.bottom,
5438        ];
5439
5440        // One mesh rather than nine draws, which is what this used to be.
5441        //
5442        // Each patch reads a different part of the image into a different
5443        // place, and the obvious way to say that is a shader per patch with
5444        // its own source rectangle -- nine paints, nine draws. Carrying the
5445        // coordinates on the vertices instead says the same thing in one
5446        // draw, which is how `draw_atlas` has always done it, and a nine-patch
5447        // is the same shape of work: several quads out of one sheet.
5448        //
5449        // What made the nine separate is that a per-draw source rectangle also
5450        // *clamps* to itself, so a patch could not sample its neighbor. Merged
5451        // naively that clamping goes and the seams bleed -- measured, twelve
5452        // hundred pixels of a hundred-and-twenty-eight-square frame, by as
5453        // much as a hundred and seventy levels, which on the one primitive
5454        // whose whole purpose is stretching without artifacts is not a
5455        // trade worth making.
5456        //
5457        // The half-texel inset below is what buys it back. A linear sample
5458        // reaches exactly half a texel past its coordinate, so pulling each
5459        // patch's edge in by that much removes the reach across the boundary
5460        // rather than compensating for it. With it the merged draw is
5461        // byte-identical to the nine: zero pixels differ, at the same worst
5462        // case of zero. The sampling is this call's own rather than the
5463        // caller's, and is linear, which is what makes half a texel the right
5464        // number rather than a guess.
5465        let (half_u, half_v) = (0.5 / w, 0.5 / h);
5466        let mut positions = Vec::with_capacity(36);
5467        let mut coords = Vec::with_capacity(36);
5468        let mut indices = Vec::with_capacity(54);
5469        for row in 0..3 {
5470            for column in 0..3 {
5471                let source = Rect::new(
5472                    source_x[column] / w,
5473                    source_y[row] / h,
5474                    source_x[column + 1] / w,
5475                    source_y[row + 1] / h,
5476                );
5477                let destination = Rect::new(
5478                    dest_x[column],
5479                    dest_y[row],
5480                    dest_x[column + 1],
5481                    dest_y[row + 1],
5482                );
5483                if source.is_empty() || destination.is_empty() {
5484                    continue;
5485                }
5486                // Inset toward the middle, and never past it: a patch one texel
5487                // across has nothing to give up, and an inset that crossed
5488                // would turn the quad inside out.
5489                let mid_u = (source.left + source.right) * 0.5;
5490                let mid_v = (source.top + source.bottom) * 0.5;
5491                let u0 = (source.left + half_u).min(mid_u);
5492                let u1 = (source.right - half_u).max(mid_u);
5493                let v0 = (source.top + half_v).min(mid_v);
5494                let v1 = (source.bottom - half_v).max(mid_v);
5495
5496                let base = positions.len() as u32;
5497                positions.extend([
5498                    Vec2::new(destination.left, destination.top),
5499                    Vec2::new(destination.right, destination.top),
5500                    Vec2::new(destination.right, destination.bottom),
5501                    Vec2::new(destination.left, destination.bottom),
5502                ]);
5503                coords.extend([
5504                    Vec2::new(u0, v0),
5505                    Vec2::new(u1, v0),
5506                    Vec2::new(u1, v1),
5507                    Vec2::new(u0, v1),
5508                ]);
5509                indices.extend([base, base + 1, base + 2, base, base + 2, base + 3]);
5510            }
5511        }
5512        if positions.is_empty() {
5513            return Ok(self);
5514        }
5515
5516        let mesh = crate::vertices::Vertices::indexed(
5517            crate::vertices::VertexMode::Triangles,
5518            positions,
5519            coords,
5520            indices,
5521        )?;
5522        // The paint supplies everything but the shader -- its blend, its
5523        // filters, whether it antialiases -- and the shader is the sheet, read
5524        // by the coordinates the vertices carry.
5525        // The paint's own shader is replaced, and its transform with it.
5526        let painted = paint
5527            .clone()
5528            .with_shader(Shader::Image {
5529                slot,
5530                rect: into,
5531                alpha: 1.0,
5532                tile: [TileMode::Clamp; 2],
5533                source: Rect::new(0.0, 0.0, 1.0, 1.0),
5534                tint: Color::WHITE,
5535                sampling: Sampling::Linear,
5536            })
5537            .with_shader_transform(Transform2D::IDENTITY);
5538        self.draw_vertices(&mesh, &painted)
5539    }
5540
5541    /// A line, and for a hairline one snapped to a pixel.
5542    ///
5543    /// The snap is the third part of upstream's minimum-size rule and the one
5544    /// that decides whether a hairline *looks* like one. A line one pixel wide
5545    /// whose center sits on a pixel boundary covers half of each of the two rows
5546    /// it straddles, so it draws gray and two pixels soft; the same line centered
5547    /// in a row covers it and draws black and one pixel crisp. Upstream moves it:
5548    /// `LineGeometry::GetPositionBuffer` carries the endpoints into device space,
5549    /// drops the transform, and rounds the constant coordinate to a half with
5550    /// `RoundToHalf` -- which is a pixel's middle.
5551    ///
5552    /// Gated exactly as upstream gates it, on `width_ == 0.f` and
5553    /// `IsTranslationScaleOnly`. A width the caller stated is a width to respect,
5554    /// and under a rotation or a shear no axis-aligned line stays one.
5555    ///
5556    /// Narrower than upstream in one way, which is deliberate: a paint wanting a
5557    /// layer keeps the ordinary path. A mask blur's sigma is stated in user space
5558    /// and this draws in device space, so the two would disagree under a scale --
5559    /// and a snap is worth half a pixel, not a wrong blur.
5560    pub fn draw_line(&mut self, from: Vec2, to: Vec2, paint: &Paint) -> Result<&mut Self> {
5561        self.prepare_destination(paint.blend);
5562        if let Some((p0, p1)) = self.hairline_snap(from, to, paint) {
5563            let mut b = PathBuilder::new();
5564            b.move_to(p0).line_to(p1);
5565            let path = b.build();
5566            // Drawn in device space, so the widening reads a basis of one and
5567            // gives exactly the pixel the snap aligned it to.
5568            let held = self.transform;
5569            self.transform = Transform2D::IDENTITY;
5570            let drawn = self.draw_path(&path, paint).map(|_| ());
5571            self.transform = held;
5572            drawn?;
5573            return Ok(self);
5574        }
5575        let mut b = PathBuilder::new();
5576        b.move_to(from).line_to(to);
5577        let path = b.build();
5578        self.draw_path(&path, paint)
5579    }
5580
5581    /// The device-space endpoints of a hairline worth snapping, or `None`.
5582    ///
5583    /// `None` covers every case that keeps the ordinary path: a stated width, a
5584    /// transform that is not a translation and a scale, a paint that wants a
5585    /// layer, and a line that is not axis-aligned once transformed.
5586    fn hairline_snap(&self, from: Vec2, to: Vec2, paint: &Paint) -> Option<(Vec2, Vec2)> {
5587        let Style::Stroke(stroke) = &paint.style else {
5588            return None;
5589        };
5590        if stroke.width != 0.0 {
5591            return None;
5592        }
5593        if paint.mask_blur > 0.0 || !paint.image_filter.is_identity() {
5594            return None;
5595        }
5596        // A solid color only, and this is the guard that matters most. Every
5597        // other shader is *mapped* by the transform -- a gradient's stops are
5598        // stated in the space the draw was recorded in, an image's source
5599        // rectangle likewise -- and this draw hands the batch an identity
5600        // transform, so the mapping would be taken without the scale. Measured
5601        // while writing this: a hairline under a doubling read its gradient at
5602        // sixteen per cent where the same line a pixel wide read it at four.
5603        //
5604        // Such a hairline keeps the ordinary path and stays half a pixel off
5605        // center, which is the right way round: a snap is worth half a pixel,
5606        // and a shader read in the wrong place is worth nothing.
5607        if !matches!(paint.shader, Shader::Solid(_)) {
5608            return None;
5609        }
5610        let affine = self.transform.to_affine()?;
5611        // A translation and a scale, which is what leaves an axis-aligned line
5612        // axis-aligned. Read off the matrix rather than tracked, so a caller who
5613        // arrived here through `concat` is judged on what they actually have.
5614        let m = affine.matrix2;
5615        if m.x_axis.y != 0.0 || m.y_axis.x != 0.0 {
5616            return None;
5617        }
5618        let (p0, p1) = (affine.transform_point2(from), affine.transform_point2(to));
5619        if !p0.is_finite() || !p1.is_finite() {
5620            return None;
5621        }
5622        // A pixel's middle, which is where a one-pixel line has to sit to cover
5623        // one pixel. Upstream's `RoundToHalf`.
5624        let to_half = |v: f32| v.floor() + 0.5;
5625        // Vertical first, matching upstream's order, and either branch leaves
5626        // the other coordinate alone -- the line's length is the caller's.
5627        if (p0.x - p1.x).abs() < CLOSE_ENOUGH {
5628            let x = to_half(p0.x);
5629            return Some((Vec2::new(x, p0.y), Vec2::new(x, p1.y)));
5630        }
5631        if (p0.y - p1.y).abs() < CLOSE_ENOUGH {
5632            let y = to_half(p0.y);
5633            return Some((Vec2::new(p0.x, y), Vec2::new(p1.x, y)));
5634        }
5635        None
5636    }
5637
5638    /// Close a layer: file its pass, and composite it onto the parent.
5639    /// The device-space rectangle a finished layer's draws actually cover.
5640    ///
5641    /// Read off the geometry rather than accumulated draw by draw, because the
5642    /// geometry is what gets rasterized. Anything covering the whole target --
5643    /// a `clear`, a fill the size of the frame -- has a quad that says so, so
5644    /// the cases upstream has to name as "unbounded content" need no special
5645    /// case here: their coverage comes out as the whole target and nothing is
5646    /// narrowed.
5647    ///
5648    /// Vertices are homogeneous clip positions for `target`, so this is the
5649    /// inverse of the projection they went through:
5650    /// `viewport_projection` maps a device offset `d` to `2d/extent - 1` in x
5651    /// and `1 - 2d/extent` in y.
5652    ///
5653    /// `None` where there is no geometry, and where any vertex sits at or past
5654    /// the vanishing line -- the first has nothing to bound, and the second has
5655    /// no finite bound to give.
5656    fn covered(batch: &Batch, target: Target) -> Option<Rect> {
5657        let (w, h) = (target.extent.width as f32, target.extent.height as f32);
5658        let (mut left, mut top) = (f32::INFINITY, f32::INFINITY);
5659        let (mut right, mut bottom) = (f32::NEG_INFINITY, f32::NEG_INFINITY);
5660        for vertex in batch.vertices() {
5661            let [x, y, w_clip] = vertex.position;
5662            // The rasterizer divides by this, so a vertex on the vanishing line
5663            // has no device position at all and one just past it has a position
5664            // on the wrong side. Neither can be bounded, and the honest answer
5665            // is to narrow nothing.
5666            if !w_clip.is_finite() || w_clip.abs() <= 1e-6 || !x.is_finite() || !y.is_finite() {
5667                return None;
5668            }
5669            let dx = (x / w_clip + 1.0) * 0.5 * w;
5670            let dy = (1.0 - y / w_clip) * 0.5 * h;
5671            left = left.min(dx);
5672            right = right.max(dx);
5673            top = top.min(dy);
5674            bottom = bottom.max(dy);
5675        }
5676        if !(right > left && bottom > top) {
5677            return None;
5678        }
5679        Some(Rect::new(
5680            target.origin.x + left,
5681            target.origin.y + top,
5682            target.origin.x + right,
5683            target.origin.y + bottom,
5684        ))
5685    }
5686
5687    /// The target a layer's content would fit in, if it is worth narrowing to.
5688    ///
5689    /// `None` keeps the target the layer was opened with, which is the whole
5690    /// parent. That is the answer whenever the content covers it anyway, and
5691    /// whenever the arithmetic cannot be trusted to cover everything the pass
5692    /// will draw.
5693    fn narrowed(
5694        &self,
5695        batch: &Batch,
5696        filter: Option<&ImageFilter>,
5697        paint: Layer,
5698        basis: BlurBasis,
5699        layer: Target,
5700    ) -> Option<Target> {
5701        // A layer composited with a mode that changes the destination where the
5702        // source drew nothing has to cover everything it might affect, not just
5703        // what it covered. `DstIn` is the one that shows it: narrowed to its
5704        // content, it stops taking the alpha out of everything outside that,
5705        // and a mask leaves the rest of the picture opaque.
5706        //
5707        // The same condition upstream spells `flood_output_coverage` in
5708        // `ComputeSaveLayerCoverage`, over the same nine modes.
5709        if paint.blend.is_destructive() {
5710            return None;
5711        }
5712        let content = Self::covered(batch, layer)?;
5713        // The same expansion the caller-bounded path makes, and for the same
5714        // reason: the content is where the draws are, and how far the layer's
5715        // own blur carries them past that is this renderer's arithmetic.
5716        let reach = paint.reach(basis);
5717        let (min, max) = (
5718            Vec2::new(content.left - reach.x, content.top - reach.y),
5719            Vec2::new(content.right + reach.x, content.bottom + reach.y),
5720        );
5721        // A filter given to the layer as a whole reaches past what it is
5722        // handed, and by how much is the filter's own arithmetic rather than
5723        // anything this can assume: a composition asks both halves, a matrix
5724        // carrying content across the vanishing line widens to everything, and
5725        // a color filter needs exactly what it was given. `covering` is the
5726        // same question a draw carrying an image filter already asks before it
5727        // opens its own layer.
5728        //
5729        // After the layer's own blur and morphology, because that is the order
5730        // `finish_layer` applies them in: the filter sees what those produced.
5731        let (min, max) = match filter {
5732            Some(filter) => filter.covering(min, max, &|sigma| basis.reach(sigma)),
5733            None => (min, max),
5734        };
5735        let left = min.x.floor().max(layer.origin.x);
5736        let top = min.y.floor().max(layer.origin.y);
5737        let right = max.x.ceil().min(layer.origin.x + layer.extent.width as f32);
5738        let bottom = max
5739            .y
5740            .ceil()
5741            .min(layer.origin.y + layer.extent.height as f32);
5742        if !(right > left && bottom > top) {
5743            return None;
5744        }
5745        let narrowed = Target {
5746            origin: Vec2::new(left, top),
5747            extent: Extent2D::new((right - left) as u32, (bottom - top) as u32),
5748        };
5749        // Nothing gained, and a viewport that offsets by zero into a target of
5750        // the same size is a slower way to spell what it already was.
5751        if narrowed.extent == layer.extent {
5752            return None;
5753        }
5754        Some(narrowed)
5755    }
5756
5757    fn finish_layer(&mut self, frame: LayerFrame) {
5758        // Read before the frame is taken apart below, and only these two are
5759        // needed: whether a whole-layer filter is in play, and the layer's own
5760        // blur and morphology, which decide how far past its content the pass
5761        // will draw.
5762        let (filter, paint) = (frame.filter.clone(), frame.paint);
5763        let mut batch = std::mem::replace(&mut self.batch, frame.batch);
5764        let sources = std::mem::replace(&mut self.sources, frame.sources);
5765
5766        // A layer clears to transparent rather than to the frame's background:
5767        // it is composited over what is already there, so anywhere it drew
5768        // nothing must contribute nothing. Clearing to the background instead
5769        // would paint an opaque rectangle over the parent.
5770        let opened = self.target;
5771        // What the layer's draws turned out to cover. A layer opened with no
5772        // bounds was given the whole parent, because nothing was known then
5773        // about where its content would land; now the content is recorded and
5774        // its own geometry says. Narrowing here rather than at `save_layer` is
5775        // what makes the derived bound possible at all.
5776        //
5777        // The geometry is *not* rewritten to suit the smaller target -- it is
5778        // in clip space, and so are the materials, and a radial gradient's
5779        // center among them. The pass keeps the space it was recorded against
5780        // and carries a viewport that lands it on the narrowed target, which
5781        // crops instead of scaling. See `PassViewport`.
5782        let layer = match self.narrowed(&batch, filter.as_ref(), paint, frame.blur_basis, opened) {
5783            Some(narrowed) => {
5784                let (dx, dy) = (
5785                    (narrowed.origin.x - opened.origin.x) as u32,
5786                    (narrowed.origin.y - opened.origin.y) as u32,
5787                );
5788                // The one recorded thing the move reaches: a scissor is in
5789                // target pixels where the geometry is in clip space.
5790                batch.rebase_scissors(dx, dy, narrowed.extent);
5791                narrowed
5792            }
5793            None => opened,
5794        };
5795        let viewport = (layer.extent != opened.extent).then(|| PassViewport {
5796            offset: [
5797                layer.origin.x - opened.origin.x,
5798                layer.origin.y - opened.origin.y,
5799            ]
5800            .map(|v| -v),
5801            extent: opened.extent,
5802        });
5803        self.aim_at(frame.parent);
5804
5805        if !self.keep_hidden_draws {
5806            batch.cull_occluded(layer.extent);
5807        }
5808        self.finished.push(Pass {
5809            batch,
5810            descriptor: PassDescriptor {
5811                clear: Some([0.0; 4]),
5812                samples: self.pass_samples(),
5813                viewport,
5814            },
5815            sources,
5816            extent: layer.extent,
5817        });
5818        // After the pass above, which is the one the layer's own draws went
5819        // into, and before the composite below, which is an image quad that
5820        // multisampling cannot change.
5821        self.anti_alias = frame.anti_alias;
5822        self.seeded_by_redraw = frame.seeded_by_redraw;
5823        let mut index = self.finished.len() - 1;
5824        if frame.paint.blur.max_element() > 0.0 {
5825            index = self.blur_passes(index, layer, frame.paint.blur, frame.blur_basis);
5826        }
5827        // After the blur, because that is the order the reach above assumes
5828        // when a layer asks for both: the blur softens the content and the
5829        // morphology then works on what the blur produced.
5830        if let Some(morphology) = frame.paint.morphology {
5831            index = self.morphology_passes(index, layer, morphology, frame.blur_basis);
5832        }
5833        // Last, so a filter given to the layer as a whole sees whatever the
5834        // layer's own fields produced rather than the other way round. That is
5835        // the order a composition states: the outermost filter is peeled first
5836        // and becomes this layer, and anything inner was applied by the draw
5837        // inside it.
5838        //
5839        // The failure is swallowed rather than returned, and it is the one
5840        // place in this file that does so: `restore` has no result, and the
5841        // only filter that can refuse here is a matrix, which the two callers
5842        // that can supply one already refuse before opening the layer. So this
5843        // is unreachable rather than ignored.
5844        if let Some(filter) = frame.filter.clone() {
5845            if let Ok(filtered) = self.filter_passes(index, layer, &filter, frame.blur_basis) {
5846                index = filtered;
5847            }
5848        }
5849        // Before the layer's slot is taken in the parent: a cut for an
5850        // advanced composite moves the parent's slots to the pass it finishes.
5851        self.prepare_destination(frame.paint.blend);
5852        let slot = self.slot_for(TextureSource::Layer(index));
5853
5854        // Where the layer sits in the parent's clip space, and how much of that
5855        // space one unit of the layer's texture spans. Clip space runs from -1
5856        // to 1 and upward, so the axes are halved and Y is negated; the ratio
5857        // of the two extents is what makes a layer smaller than its parent
5858        // sample across its own full width rather than a fraction of it.
5859        //
5860        // For a full-size layer this comes out to the identity mapping between
5861        // the target and the image — origin at the top-left of clip space,
5862        // axes halved — which is what it was before bounds existed.
5863        let parent = frame.parent;
5864        let offset = layer.origin - parent.origin;
5865        let anchor = Vec2::new(
5866            -1.0 + 2.0 * offset.x / parent.extent.width as f32,
5867            1.0 - 2.0 * offset.y / parent.extent.height as f32,
5868        );
5869        let scale = Mat2::from_diagonal(Vec2::new(
5870            0.5 * parent.extent.width as f32 / layer.extent.width as f32,
5871            -0.5 * parent.extent.height as f32 / layer.extent.height as f32,
5872        ));
5873        // Stated in the direction the shader reads it: a fragment's clip
5874        // position to the texel it samples, with the anchor inside the matrix
5875        // rather than packed beside it.
5876        let clip_to_texture = Affine2::from_mat2(scale) * Affine2::from_translation(-anchor);
5877        // A layer asking to be transformed on the way back needs both halves
5878        // moved, and moving only the geometry is the mistake worth naming: the
5879        // mapping below carries a fragment's clip position to a texel, so
5880        // geometry moved without it shows the layer through a window that
5881        // moved rather than showing a layer that moved.
5882        // A matrix that folds the plane has no inverse, so there is no mapping
5883        // saying which texel a fragment reads -- and no geometry either, since
5884        // the rectangle collapses to a line. Both halves are dropped together:
5885        // dropping only the mapping leaves a layer drawn through a singular
5886        // matrix, which is nothing at all, and the fallback would be invisible.
5887        //
5888        // The matrix is stated in device pixels and the mapping is in clip
5889        // space, so it is conjugated into clip space and composed ahead of the
5890        // mapping in inverse. Both are resolved here, once, rather than tested
5891        // in one place and taken in another -- the geometry below moves by the
5892        // first and the mapping by the second, and a pair either exists or
5893        // neither half does.
5894        let projection = self.target.projection();
5895        let placement = frame.paint.matrix.and_then(|matrix| {
5896            let in_clip = projection * matrix * projection.inverse()?;
5897            in_clip.is_finite().then_some(())?;
5898            Some((matrix, in_clip.inverse()?))
5899        });
5900        let clip_to_texture = Transform2D::from(clip_to_texture);
5901        let clip_to_texture = match placement {
5902            None => clip_to_texture,
5903            Some((_, undo)) => clip_to_texture * undo,
5904        };
5905        let material = Material::Image {
5906            to_local: to_local_columns(clip_to_texture),
5907            slot,
5908            alpha: frame.paint.alpha,
5909            tile: [TileMode::Clamp; 2],
5910            // A layer composites at its own size, so nothing is between texels
5911            // to choose between.
5912            sampling: Sampling::Linear,
5913            source: [0.0, 0.0, 1.0, 1.0],
5914            tint: [1.0, 1.0, 1.0, 1.0],
5915        };
5916        let paint = RenderPaint {
5917            material,
5918            filter: frame.paint.color_filter,
5919            blend: frame.paint.blend,
5920            clip: self.clip,
5921            stencil: ClipState::content(self.depth),
5922        };
5923        // Exactly the layer's own rectangle, stated in device pixels and drawn
5924        // through the identity: a layer's contents are already where they
5925        // belong, the transform having been applied to the shapes inside it
5926        // rather than again to the finished image. Covering more than the layer
5927        // would sample outside it, which the clamped sampler answers by
5928        // smearing the edge texels across the rest of the frame.
5929        let whole = layer.path();
5930        let _ = self.renderer.fill_into(
5931            &mut self.batch,
5932            &whole,
5933            placement.map_or(Transform2D::IDENTITY, |(matrix, _)| matrix),
5934            &paint,
5935        );
5936    }
5937
5938    /// Run an image filter over a pass, and answer which pass now holds it.
5939    ///
5940    /// The one place that knows how each kind of filter becomes passes, so a
5941    /// caller with an `ImageFilter` and a pass does not have to. A composition
5942    /// is its inner half then its outer, which is what composing means and is
5943    /// the order `peel` takes them apart in.
5944    ///
5945    /// A matrix does not become a pass. Every other kind reads its input where
5946    /// the fragment is and writes there; a matrix *moves* the image, so as a
5947    /// pass it would need a target sized for where the content went rather than
5948    /// where it was. A backdrop's matrix never gets here -- `backdrop_pass`
5949    /// peels it off and folds it into the seed, which draws into a target that
5950    /// was already the right size -- so what reaches this arm is a matrix
5951    /// somewhere inside a composition, where the seed is not what reads it, and
5952    /// that is refused rather than approximated.
5953    fn filter_passes(
5954        &mut self,
5955        source: usize,
5956        target: Target,
5957        filter: &ImageFilter,
5958        basis: BlurBasis,
5959    ) -> Result<usize> {
5960        Ok(match filter {
5961            ImageFilter::None => source,
5962            ImageFilter::Blur { sigma_x, sigma_y } => {
5963                self.blur_passes(source, target, Vec2::new(*sigma_x, *sigma_y), basis)
5964            }
5965            ImageFilter::Dilate { radius_x, radius_y } => self.morphology_passes(
5966                source,
5967                target,
5968                Morphology::dilate(*radius_x, *radius_y),
5969                basis,
5970            ),
5971            ImageFilter::Erode { radius_x, radius_y } => self.morphology_passes(
5972                source,
5973                target,
5974                Morphology::erode(*radius_x, *radius_y),
5975                basis,
5976            ),
5977            ImageFilter::Runtime { program, uniforms } => {
5978                self.runtime_pass(source, target, *program, uniforms)
5979            }
5980            ImageFilter::Color(recolor) => self.recolor_pass(source, target, *recolor),
5981            ImageFilter::Compose { outer, inner } => {
5982                let inner = self.filter_passes(source, target, inner, basis)?;
5983                self.filter_passes(inner, target, outer, basis)?
5984            }
5985            ImageFilter::Matrix { .. } => {
5986                return Err(Error::Unsupported(
5987                    "a matrix inside a composition is not available as a filter; it \
5988                     moves the image rather than recomputing it in place, and only \
5989                     the outermost one folds into a backdrop's seed",
5990                ))
5991            }
5992        })
5993    }
5994
5995    /// A color filter run over a pass, and the pass it landed at.
5996    ///
5997    /// The image material with the filter on the paint rather than on the
5998    /// material, which is where a color filter lives: it acts on whatever the
5999    /// fragment computed, and here what the fragment computed is the texel.
6000    fn recolor_pass(&mut self, source: usize, target: Target, recolor: ColorFilter) -> usize {
6001        let to_local = to_local_columns(Transform2D::from(
6002            Affine2::from_mat2(Mat2::from_diagonal(Vec2::new(0.5, -0.5)))
6003                * Affine2::from_translation(Vec2::new(1.0, -1.0)),
6004        ));
6005        self.filter_pass_recolored(
6006            source,
6007            target,
6008            Material::Image {
6009                to_local,
6010                slot: 0,
6011                alpha: 1.0,
6012                tile: [TileMode::Clamp; 2],
6013                sampling: Sampling::Linear,
6014                source: [0.0, 0.0, 1.0, 1.0],
6015                tint: [1.0, 1.0, 1.0, 1.0],
6016            },
6017            recolor,
6018        )
6019    }
6020
6021    /// A caller's program run over a finished layer, and the pass it landed at.
6022    ///
6023    /// The whole of what a runtime image filter is, and it is short for the
6024    /// reason recorded on [`ImageFilter::Runtime`]: a filter pass covers a
6025    /// target the size of its source, so a fragment's clip position is already
6026    /// its texture coordinate and the program needs no mapping handed to it.
6027    /// Upstream re-rasterizes its input to arrange the same thing.
6028    ///
6029    /// Slot zero, because `filter_pass` gives the pass one source and that
6030    /// source is the layer being filtered. A program declaring the binding
6031    /// every draw already fills reads it and nothing further is bound.
6032    /// `region`'s rectangle of `source`, a pass the size of `parent`, as a
6033    /// pass the size of `region`: what lets a filter that reads a pass texel
6034    /// for pixel work on part of a capture. The mapping is the one
6035    /// `draw_whole_pass` seeds with, in the same direction.
6036    fn crop_pass(&mut self, source: usize, parent: Target, region: Target) -> usize {
6037        let offset = region.origin - parent.origin;
6038        let (rw, rh) = (region.extent.width as f32, region.extent.height as f32);
6039        let (pw, ph) = (parent.extent.width as f32, parent.extent.height as f32);
6040        let anchor = Vec2::new(-1.0 - 2.0 * offset.x / rw, 1.0 + 2.0 * offset.y / rh);
6041        let scale = Mat2::from_diagonal(Vec2::new(0.5 * rw / pw, -0.5 * rh / ph));
6042        let to_local = to_local_columns(Transform2D::from(
6043            Affine2::from_mat2(scale) * Affine2::from_translation(-anchor),
6044        ));
6045        self.filter_pass(
6046            source,
6047            region,
6048            Material::Image {
6049                to_local,
6050                slot: 0,
6051                alpha: 1.0,
6052                tile: [TileMode::Clamp; 2],
6053                // A texel to a pixel, both targets on the same grid.
6054                sampling: Sampling::Nearest,
6055                source: [0.0, 0.0, 1.0, 1.0],
6056                tint: [1.0, 1.0, 1.0, 1.0],
6057            },
6058        )
6059    }
6060
6061    fn runtime_pass(
6062        &mut self,
6063        source: usize,
6064        target: Target,
6065        program: u32,
6066        uniforms: &[f32],
6067    ) -> usize {
6068        let mut textures = [None; emblema_hal::MAX_EFFECT_TEXTURES];
6069        textures[0] = Some(0);
6070        self.filter_pass(
6071            source,
6072            target,
6073            Material::Runtime {
6074                program,
6075                uniforms: uniforms.to_vec(),
6076                textures,
6077            },
6078        )
6079    }
6080
6081    /// One pass covering `target`, drawing `material` over all of it, and the
6082    /// index it landed at.
6083    ///
6084    /// What every image filter is made of. The material carries the mapping
6085    /// from the quad's clip position to the sampled texture's coordinates --
6086    /// the same pair a layer composite uses at zero offset, since a filter's
6087    /// target is the same size as its source -- and the filtering itself. The
6088    /// composite that follows is untouched, and still applies the layer's alpha
6089    /// and blend: keeping the filter passes pure means neither has to know
6090    /// about compositing.
6091    fn filter_pass(&mut self, source: usize, target: Target, material: Material) -> usize {
6092        self.filter_pass_recolored(source, target, material, ColorFilter::None)
6093    }
6094
6095    /// The same, with a color filter applied to what the material produced.
6096    fn filter_pass_recolored(
6097        &mut self,
6098        source: usize,
6099        target: Target,
6100        material: Material,
6101        recolor: ColorFilter,
6102    ) -> usize {
6103        // A pass of its own, so its slot table starts empty and the one slot it
6104        // uses is the pass it samples.
6105        let mut batch = Batch::new();
6106        let sources = vec![TextureSource::Layer(source)];
6107        let paint = RenderPaint {
6108            material,
6109            filter: recolor,
6110            // Replaces rather than blends: the target is cleared and this
6111            // covers all of it, so anything else would blend against the clear
6112            // for no reason.
6113            blend: BlendMode::Src,
6114            clip: None,
6115            stencil: ClipState::UNCLIPPED,
6116        };
6117        let quad = target.path();
6118        // The canvas's own renderer, aimed at the filter target for the one
6119        // draw and put back afterward. A fresh `Renderer` here would build a
6120        // pair of tessellators per pass per filtered layer per frame, for a
6121        // quad -- and would be the kind of allocation that never shows up in a
6122        // profile as itself.
6123        self.renderer.set_viewport(target.origin, target.extent);
6124        let _ = self
6125            .renderer
6126            .fill_into(&mut batch, &quad, Affine2::IDENTITY, &paint);
6127        self.renderer
6128            .set_viewport(self.target.origin, self.target.extent);
6129
6130        self.finished.push(Pass {
6131            batch,
6132            descriptor: PassDescriptor {
6133                clear: Some([0.0; 4]),
6134                // One sample: this reads a resolved image and writes another,
6135                // so multisampling it would resolve twice for no difference.
6136                samples: 1,
6137                viewport: None,
6138            },
6139            sources,
6140            extent: target.extent,
6141        });
6142        self.finished.len() - 1
6143    }
6144
6145    /// Spread or shrink a finished layer, and answer which pass holds the
6146    /// result.
6147    ///
6148    /// One pass per axis where the radius fits the shader's tap budget, and
6149    /// more where it does not. Splitting is exact rather than an
6150    /// approximation: dilating by `a` and then by `b` dilates by `a + b`,
6151    /// because the structuring elements add, and the same holds for erosion.
6152    /// So a radius of eighty runs as thirty-two, thirty-two and sixteen, and
6153    /// the picture is the one a single pass of eighty would have given.
6154    ///
6155    /// An axis with no radius contributes no passes at all. A dilation of ten
6156    /// horizontally and none vertically is one pass, not two, and the second
6157    /// would only have copied the image.
6158    fn morphology_passes(
6159        &mut self,
6160        source: usize,
6161        target: Target,
6162        morphology: Morphology,
6163        basis: BlurBasis,
6164    ) -> usize {
6165        // A filter pass covers the whole target, so its mapping is the fixed
6166        // one from clip space to the unit square and carries no transform of
6167        // the caller's at all. That is what keeps `step` -- a constant offset
6168        // between taps, in texels -- meaning the same thing at every fragment,
6169        // which a mapping with perspective would not.
6170        let to_local = to_local_columns(Transform2D::from(
6171            Affine2::from_mat2(Mat2::from_diagonal(Vec2::new(0.5, -0.5)))
6172                * Affine2::from_translation(Vec2::new(1.0, -1.0)),
6173        ));
6174        // Clamped to what the target can tell apart. The loop below emits a
6175        // pass per `MORPHOLOGY_TAPS` texels of radius, so without this a
6176        // caller's float decides how many passes a recording holds --
6177        // `Morphology::applied_radius` has the arithmetic and the case that
6178        // found it.
6179        let radius = morphology.applied_radius(target.extent);
6180        // Along the caller's axes once the transform has turned them, not the
6181        // target's -- the same arrangement and the same arithmetic as
6182        // `blur_passes`, for the same reason `non-parity.md` 14 gives: a layer's
6183        // content cannot be re-rendered into a space of its own choosing after
6184        // the fact, so the passes turn instead of the space. A unit device
6185        // direction moves `d.x` texels across and `d.y` down, so in normalized
6186        // coordinates it is `d` divided componentwise by the extent, which
6187        // reduces to the pair of axis steps this used to state whenever the
6188        // directions are the axes.
6189        //
6190        // A dilation is a maximum over a set of sample positions, and turning
6191        // the set is what makes a rotated square dilate to a square rather than
6192        // to one standing on the screen's axes.
6193        let (w, h) = (target.extent.width as f32, target.extent.height as f32);
6194        let [u, v] = basis.directions;
6195        let axes = [
6196            ([u.x / w, u.y / h], radius[0]),
6197            ([v.x / w, v.y / h], radius[1]),
6198        ];
6199
6200        let mut sampled = source;
6201        for (step, radius) in axes {
6202            let mut left = radius;
6203            while left > 0.0 {
6204                let taken = left.min(MORPHOLOGY_TAPS as f32);
6205                left -= taken;
6206                let material = Material::Morphology {
6207                    to_local,
6208                    slot: 0,
6209                    step,
6210                    radius: taken,
6211                    dilate: morphology.dilate,
6212                };
6213                sampled = self.filter_pass(sampled, target, material);
6214            }
6215        }
6216        sampled
6217    }
6218
6219    /// Blur a finished layer, and answer which pass now holds the result.
6220    ///
6221    /// Two passes, one per axis, because a two-dimensional Gaussian is the
6222    /// product of two one-dimensional ones: the same picture as a square of
6223    /// taps, at a fraction of the work. Each renders a quad covering its whole
6224    /// target and samples the pass before it.
6225    ///
6226    /// Both are the size of the layer, so a bounded layer's blur costs what the
6227    /// bound says and not what the frame is. The composite that follows is
6228    /// unchanged, and still applies the layer's alpha and blend -- keeping the
6229    /// blur passes pure means neither has to know about compositing.
6230    /// Halve a pass into a target of half its size, by sampling it.
6231    ///
6232    /// A linear sample taken at the center of a two-by-two block averages
6233    /// exactly those four texels, so halving with the sampler *is* a box
6234    /// filter and needs no kernel of its own. That is the whole reason the
6235    /// reduction below is a chain of halvings rather than one jump to the
6236    /// final size: a single bilinear tap spanning an eight-by-eight block
6237    /// reads four of its sixty-four texels and calls the rest absent, which is
6238    /// how a downsample turns a smooth image into a crawling one.
6239    fn halve_pass(&mut self, source: usize, into: Target) -> usize {
6240        // Clip space to the unit square, the same fixed mapping a blur pass
6241        // uses: a filter covers its whole target and samples the whole of what
6242        // it was given, whatever the two sizes are.
6243        let to_local = to_local_columns(Transform2D::from(
6244            Affine2::from_mat2(Mat2::from_diagonal(Vec2::new(0.5, -0.5)))
6245                * Affine2::from_translation(Vec2::new(1.0, -1.0)),
6246        ));
6247        self.filter_pass(
6248            source,
6249            into,
6250            Material::Image {
6251                to_local,
6252                slot: 0,
6253                alpha: 1.0,
6254                tile: [TileMode::Clamp; 2],
6255                sampling: Sampling::Linear,
6256                source: [0.0, 0.0, 1.0, 1.0],
6257                tint: [1.0, 1.0, 1.0, 1.0],
6258            },
6259        )
6260    }
6261
6262    /// How far to shrink a target before blurring it, as a power of two.
6263    ///
6264    /// The taps are one per texel while the radius fits in the budget and
6265    /// spread apart once it does not, which keeps a wide blur wide but samples
6266    /// it more and more coarsely -- past a deviation of about nineteen the gaps
6267    /// between taps open and a smooth ramp starts to show them. Upstream
6268    /// answers this by blurring a smaller copy, so the taps stay one per texel
6269    /// and it is the *image* that loses detail rather than the kernel. For a
6270    /// blur this wide that detail was leaving anyway.
6271    ///
6272    /// A power of two so that every step is an exact halving, which is what
6273    /// makes the sampler a box filter above.
6274    fn blur_downsample(sigma: f32, extent: u32) -> u32 {
6275        // A sigma that is not a length asks for no reduction. `with_blur_xy`
6276        // refuses one, but `Layer::blur` is a public field and a struct literal
6277        // carries whatever it likes past that -- and an infinite sigma makes the
6278        // condition below true however far the reduction goes, leaving the extent
6279        // as the loop's only stop.
6280        if !sigma.is_finite() || sigma <= 0.0 {
6281            return 1;
6282        }
6283        let mut scale = 1u32;
6284        // Stopped once the axis would round to nothing. The extent is floored
6285        // at one texel where it is built, so this is not what keeps a target
6286        // from having no pixels -- it is what keeps the reduction from spending
6287        // passes halving a single texel into itself, which a deviation of a few
6288        // hundred against a small layer will otherwise ask for.
6289        //
6290        // Written as `scale <= extent / 2` rather than `extent / (scale * 2) >= 1`,
6291        // which says the same thing and computes `scale * 2`. That product
6292        // overflows once `scale` reaches two to the thirty-first, which a layer
6293        // whose bounds make the extent that large reaches -- and the overflow was
6294        // not the worse half: in release the multiply wraps to zero and the
6295        // division that followed it panicked instead, so both profiles died on the
6296        // same input. Found by a generated sequence of canvas calls.
6297        while blur_radius(sigma / scale as f32) > BLUR_MAX_TAPS && scale <= extent / 2 {
6298            scale *= 2;
6299        }
6300        scale
6301    }
6302
6303    fn blur_passes(
6304        &mut self,
6305        source: usize,
6306        target: Target,
6307        sigma: Vec2,
6308        basis: BlurBasis,
6309    ) -> usize {
6310        // Clip space spans two units and runs upward, so this is the mapping
6311        // that turns a full-target quad's clip position into the texture
6312        // coordinates of the pass it samples -- the same pair a layer
6313        // composite uses at zero offset, since these targets are the same size.
6314        // A filter pass covers the whole target, so its mapping is the fixed
6315        // one from clip space to the unit square and carries no transform of
6316        // the caller's at all. That is what keeps `step` -- a constant offset
6317        // between taps, in texels -- meaning the same thing at every fragment,
6318        // which a mapping with perspective would not.
6319        let to_local = to_local_columns(Transform2D::from(
6320            Affine2::from_mat2(Mat2::from_diagonal(Vec2::new(0.5, -0.5)))
6321                * Affine2::from_translation(Vec2::new(1.0, -1.0)),
6322        ));
6323        // Past the tap budget the image is shrunk rather than the taps spread,
6324        // which is upstream's answer and keeps the taps one per texel. Halved
6325        // repeatedly, so each step is an exact box filter; the deviation shrinks
6326        // with the image, and the composite that puts the layer back scales it
6327        // up again -- it maps clip space to a normalized coordinate, so it does
6328        // not care what resolution answers.
6329        // Per axis, because the deviations are. An axis blurred hard needs its
6330        // reduction and an axis blurred not at all must not be reduced with it
6331        // -- shrinking and enlarging a sharp axis for the sake of the other one
6332        // would soften it, which is the whole difference between a directional
6333        // blur and a soft smear.
6334        //
6335        // Only where the passes run along the target's own axes, though. Turned
6336        // off them, reducing one axis and not the other would shear the
6337        // directions the steps are stated in: two perpendicular directions in a
6338        // stretched image are no longer perpendicular, and separability is
6339        // exactly the property that would be lost. So a turned blur reduces both
6340        // axes together, which is a similarity and leaves the angle alone.
6341        let scale = if basis.is_axis_aligned() {
6342            [
6343                Self::blur_downsample(sigma.x, target.extent.width),
6344                Self::blur_downsample(sigma.y, target.extent.height),
6345            ]
6346        } else {
6347            let smallest = target.extent.width.min(target.extent.height);
6348            let together = Self::blur_downsample(sigma.x, smallest)
6349                .max(Self::blur_downsample(sigma.y, smallest));
6350            [together, together]
6351        };
6352        let reduced = |by: [u32; 2]| Target {
6353            origin: target.origin,
6354            extent: Extent2D::new(
6355                (target.extent.width / by[0]).max(1),
6356                (target.extent.height / by[1]).max(1),
6357            ),
6358        };
6359        let blurred = reduced(scale);
6360        let sigma = Vec2::new(sigma.x / scale[0] as f32, sigma.y / scale[1] as f32);
6361
6362        let mut source = source;
6363        let mut step_scale = [1u32; 2];
6364        while step_scale[0] < scale[0] || step_scale[1] < scale[1] {
6365            // Each iteration halves whichever axes are still above their own
6366            // target, so every step remains at most a halving per axis and
6367            // therefore an exact box filter, which is the property the
6368            // reduction rests on.
6369            for axis in 0..2 {
6370                if step_scale[axis] < scale[axis] {
6371                    step_scale[axis] *= 2;
6372                }
6373            }
6374            source = self.halve_pass(source, reduced(step_scale));
6375        }
6376
6377        // A step of one texel along each axis, in the sampled texture's own
6378        // coordinates. The shader cannot derive this: it does not know the size
6379        // of what it is sampling.
6380        //
6381        // A unit device direction moves `d.x` texels across and `d.y` down, so
6382        // in normalized coordinates it is `d` divided componentwise by the
6383        // extent. That reduces to the pair of axis steps this used to state when
6384        // the directions are the axes, and it is the whole of what makes a blur
6385        // turn with its caller.
6386        let (w, h) = (blurred.extent.width as f32, blurred.extent.height as f32);
6387        let [u, v] = basis.directions;
6388        let steps = [(sigma.x, [u.x / w, u.y / h]), (sigma.y, [v.x / w, v.y / h])];
6389
6390        let mut sampled = source;
6391        for (sigma, step) in steps {
6392            // Skipped rather than run with a deviation of zero. A zero-sigma
6393            // pass is the identity in arithmetic and a resample in fact, and a
6394            // blur stated along one axis is exactly the case where the other
6395            // pass must leave the image alone.
6396            if !ImageFilter::blurs(sigma) {
6397                continue;
6398            }
6399            sampled = self.filter_pass(
6400                sampled,
6401                blurred,
6402                Material::Blur {
6403                    to_local,
6404                    slot: 0,
6405                    step,
6406                    sigma,
6407                },
6408            );
6409        }
6410        sampled
6411    }
6412
6413    /// Point both the canvas and its renderer at a target.
6414    ///
6415    /// Together rather than separately: the canvas derives a paint's mapping
6416    /// from the target and the renderer derives the geometry's, and the two
6417    /// have to agree or a shape lands in one place while its gradient runs
6418    /// through another.
6419    fn aim_at(&mut self, target: Target) {
6420        self.target = target;
6421        self.renderer.set_viewport(target.origin, target.extent);
6422    }
6423
6424    /// The sample count a pass renders at.
6425    fn pass_samples(&self) -> u32 {
6426        // One sample unless something asked for antialiasing, because
6427        // multisampling costs bandwidth and a frame of solid rectangles gains
6428        // nothing from it.
6429        if self.anti_alias {
6430            self.samples
6431        } else {
6432            1
6433        }
6434    }
6435
6436    /// Leave in the parts of each draw a later opaque draw would cover.
6437    ///
6438    /// `Batch::cull_occluded` claims to be pixel-identical. The only way to check a
6439    /// claim like that is to render the same recording with it and without it and
6440    /// compare the results, which needs a way to turn it off.
6441    ///
6442    /// Hidden because it is not a choice a caller should make: it asks for the same
6443    /// picture at more cost. Alongside `Tessellator::fill_general`, which exists for the
6444    /// same reason.
6445    #[doc(hidden)]
6446    pub fn keep_hidden_draws(&mut self) -> &mut Self {
6447        self.keep_hidden_draws = true;
6448        self
6449    }
6450
6451    /// Finish recording.
6452    pub fn finish(mut self) -> Recording {
6453        // A layer left open is a caller mistake, and the useful recovery is to
6454        // composite it anyway: the alternative is silently dropping everything
6455        // drawn since the unbalanced `save_layer`, which looks like a rendering
6456        // fault rather than like the missing `restore` it is.
6457        while self.stack.iter().any(|s| s.layer.is_some()) {
6458            self.restore();
6459        }
6460
6461        let samples = self.pass_samples();
6462        if !self.keep_hidden_draws {
6463            let extent = self.extent;
6464            self.batch.cull_occluded(extent);
6465        }
6466        let root = Pass {
6467            batch: self.batch,
6468            descriptor: PassDescriptor {
6469                clear: self
6470                    .background
6471                    .map(|c| c.to_array())
6472                    .or_else(|| self.seeded_by_redraw.then_some([0.0; 4])),
6473                samples,
6474                // The root pass renders into the caller's surface, which is the
6475                // space its geometry was recorded against.
6476                viewport: None,
6477            },
6478            sources: self.sources,
6479            extent: self.extent,
6480        };
6481        let mut passes = self.finished;
6482        passes.push(root);
6483        Recording {
6484            passes,
6485            extent: self.extent,
6486            ramps: self.ramps,
6487        }
6488    }
6489}
6490
6491/// How much a transform magnifies, for converting a length into device pixels.
6492///
6493/// The larger of the two basis lengths, which is what upstream's
6494/// `GetMaxBasisLengthXY` gives and what `thin_stroke` already uses for the same
6495/// kind of conversion. A projective transform has no single answer -- it
6496/// magnifies differently at every point -- so it converts by its affine part,
6497/// which is exact wherever the perspective is mild and is the same reading the
6498/// stroke widening takes.
6499fn max_scale_of(transform: Transform2D) -> f32 {
6500    match transform.to_affine() {
6501        Some(affine) => max_scale(&affine),
6502        None => 1.0,
6503    }
6504}
6505
6506/// How far each of the caller's own axes is stretched, separately.
6507///
6508/// `max_scale_of` answers the same question with one number, which is the right
6509/// answer for a length that has no axis -- a stroke's width, a tessellation
6510/// tolerance -- and the wrong one for a pair of lengths that do. Under
6511/// `scale(2, 5)` it reports five for both, so a radius stated per axis comes out
6512/// five times too long on one of them.
6513///
6514/// The lengths of the transformed basis vectors, which is what upstream's
6515/// `ExtractScale` takes. A rotation therefore contributes nothing to either,
6516/// which is correct: it turns the axes rather than stretching them, and
6517/// `BlurBasis` is what carries the turn.
6518///
6519/// Falls back to the single factor where there is no basis to read -- a
6520/// transform with perspective has no constant one -- so the axis-free answer is
6521/// what a filter gets exactly where a per-axis answer would be invented.
6522fn axis_scales_of(transform: Transform2D) -> Vec2 {
6523    let Some(affine) = transform.to_affine() else {
6524        return Vec2::splat(max_scale_of(transform));
6525    };
6526    let lengths = Vec2::new(
6527        affine.matrix2.x_axis.length(),
6528        affine.matrix2.y_axis.length(),
6529    );
6530    if !lengths.x.is_finite() || !lengths.y.is_finite() || lengths.min_element() <= 0.0 {
6531        return Vec2::splat(max_scale_of(transform));
6532    }
6533    lengths
6534}
6535
6536/// The constant that makes four cubics approximate a circle.
6537const KAPPA: f32 = 0.552_284_8;
6538
6539/// The smallest a stroke is drawn, in device pixels.
6540///
6541/// Upstream's `kMinStrokeSize`, and the same value for the same reason: a
6542/// stroke narrower than a pixel has no way to cover one, so it either lands on
6543/// a sample or misses it. Widening to exactly one and paying for the width in
6544/// alpha is what makes a thin line fade instead of flicker.
6545const MIN_STROKE_PIXELS: f32 = 1.0;
6546
6547/// The width a stroke is drawn at, and the alpha that pays for the difference.
6548///
6549/// A stroke narrower than a device pixel cannot be drawn at the width it asks
6550/// for. Multisampling quantizes it: at four samples the only coverages a
6551/// sub-pixel line can have are none, a quarter, a half and three quarters, so
6552/// a line a fifth of a pixel wide draws at a quarter or vanishes outright
6553/// depending on where it falls. Measured here before this existed, a stroke of
6554/// 0.18 device pixels and one of 0.3 drew identically, and one of 0.15 drew
6555/// nothing at all.
6556///
6557/// So the geometry is widened to a whole pixel and the alpha is scaled down to
6558/// pay for it, which is what upstream does — `ComputePixelHalfWidth` takes
6559/// `max(width, kMinStrokeSize / max_basis)` and `ComputeStrokeAlphaCoverage`
6560/// returns `clamp(scaled_width * 2, 0, 1)`, a factor its own comment calls
6561/// eyeballed from Skia. Both are carried rather than improved on: the whole
6562/// point is that a Flutter app's hairlines look here as they look there, and a
6563/// different constant would be a different picture at every sub-pixel width.
6564///
6565/// **Zero is a hairline**, which is upstream's reading and `dart:ui`'s
6566/// documented one: "Defaults to 0.0, which correspond to a hairline width".
6567/// Upstream spells it as an explicit exception rather than letting it fall out
6568/// of the arithmetic — `ComputeStrokeAlphaCoverage` opens with
6569/// `if (scaled_stroke_width == 0.0 || scaled_stroke_width >= kMinStrokeSize)
6570/// return 1.0`, so zero takes the widening to a whole pixel and pays nothing in
6571/// alpha for it.
6572///
6573/// This renderer read zero as no stroke until 2026-09-17, on the reasoning that
6574/// a caller animating a width to nothing should dim continuously rather than
6575/// jump back to full at the end. That reasoning is sound and it is not
6576/// upstream's: the jump is in upstream on purpose, and zero is the *default*
6577/// value of `Paint.strokeWidth` rather than an edge a caller has to ask for --
6578/// so a Flutter app that strokes without setting a width drew a hairline there
6579/// and nothing here. Parity wins, and the discontinuity comes with it.
6580///
6581/// Which zero means which is what [`Zero`] carries. The analytic route spells a
6582/// *fill* as a stroke width of zero, and widening that one would put a
6583/// one-pixel outline around every filled shape, so the distinction cannot be
6584/// left to the number.
6585///
6586/// A projective transform is left alone too. The widening asks how much a
6587/// transform stretches, which for a homography is a different answer at every
6588/// point; upstream guards the same case with `HasPerspective2D`.
6589fn thin_stroke(transform: Transform2D, width: f32, zero: Zero) -> (f32, f32) {
6590    let Some(affine) = transform.to_affine() else {
6591        return (width, 1.0);
6592    };
6593    if !width.is_finite() || width < 0.0 {
6594        return (width, 1.0);
6595    }
6596    if width == 0.0 && zero == Zero::IsNotAStroke {
6597        return (width, 1.0);
6598    }
6599    let basis = max_scale(&affine);
6600    if !basis.is_finite() || basis <= 0.0 {
6601        return (width, 1.0);
6602    }
6603    let scaled = basis * width;
6604    if scaled >= MIN_STROKE_PIXELS {
6605        return (width, 1.0);
6606    }
6607    // Upstream's exception, and the reason it is one: the dimming below would
6608    // take a width of zero to an alpha of zero, which is a hairline nobody can
6609    // see rather than the thinnest line the device can draw.
6610    let coverage = match scaled == 0.0 {
6611        true => 1.0,
6612        false => (scaled * 2.0).clamp(0.0, 1.0),
6613    };
6614    (MIN_STROKE_PIXELS / basis, coverage)
6615}
6616
6617/// The radius a point is drawn at, which for a small one is wider than asked.
6618///
6619/// The same problem `thin_stroke` solves and a different constant, both taken
6620/// from upstream. A point smaller than a pixel lands on a sample or misses it,
6621/// so `PointFieldGeometry` widens the *radius* to `0.5f / max_basis` --
6622/// `std::max(radius_, min_size)`, half a pixel, so the point comes out one pixel
6623/// across. A stroke's constant is a whole pixel because a stroke width spans the
6624/// line rather than reaching from its middle.
6625///
6626/// Nothing is dimmed to pay for it, which is upstream's rule and not an omission
6627/// here: a stroke fades as it thins and a point does not. A point is a disc
6628/// whose area falls away as the square of its radius, so dimming it as well
6629/// would take it to nothing twice over, and a field of them is a scatter plot
6630/// whose small marks are the ones a reader has to see.
6631///
6632/// A projective transform is left alone, as it is for a stroke: the stretch a
6633/// homography applies is a different answer at every point.
6634fn point_radius(transform: Transform2D, width: f32) -> f32 {
6635    let radius = width / 2.0;
6636    let Some(affine) = transform.to_affine() else {
6637        return radius;
6638    };
6639    if !radius.is_finite() || radius < 0.0 {
6640        return radius;
6641    }
6642    let basis = max_scale(&affine);
6643    if !basis.is_finite() || basis <= 0.0 {
6644        return radius;
6645    }
6646    radius.max(MIN_POINT_RADIUS_PIXELS / basis)
6647}
6648
6649/// When two coordinates are the same coordinate, for deciding axis alignment.
6650///
6651/// Upstream's `kEhCloseEnough`, and the same value. A line off vertical by less
6652/// than this covers the same pixels a vertical one does, so treating it as
6653/// vertical moves nothing a reader could see.
6654const CLOSE_ENOUGH: f32 = 1e-3;
6655
6656/// Half a device pixel, so the smallest point drawn covers one.
6657///
6658/// Upstream's `min_size` in `PointFieldGeometry::GetPositionBuffer`, which is
6659/// `0.5f / max_basis` rather than [`MIN_STROKE_PIXELS`] over it, for the reason
6660/// [`point_radius`] gives: this one is a radius.
6661const MIN_POINT_RADIUS_PIXELS: f32 = 0.5;
6662
6663/// What a stroke width of zero means at a call site, which is not always the
6664/// same thing.
6665///
6666/// A caller asking for a zero-width stroke wants a hairline. The analytic route
6667/// reaches [`thin_stroke`] through `analytic_stroke`, which reports a *fill* as
6668/// a width of zero -- and a fill widened to a pixel would grow an outline it
6669/// never asked for. So the two are told apart here rather than by the number,
6670/// which they share.
6671#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6672enum Zero {
6673    /// A stroke of no width, which draws the thinnest line the device can.
6674    IsAHairline,
6675    /// Not a stroke at all, so there is no width to widen.
6676    IsNotAStroke,
6677}
6678
6679/// A color at `factor` of its opacity.
6680///
6681/// The analytic route's materials carry one color rather than a material this
6682/// can be asked of, so the two spellings of the same dimming sit beside each
6683/// other: [`Material::with_opacity`] and this.
6684fn dimmed(color: crate::Color, factor: f32) -> [f32; 4] {
6685    let mut c = color.to_array();
6686    c[3] *= factor;
6687    c
6688}
6689
6690/// The stroke width a paint implies for a fragment-evaluated shape, if one can
6691/// be drawn that way at all.
6692///
6693/// `Some(0.0)` fills, `Some(w)` traces an outline, and `None` means this paint
6694/// has to be tessellated: without antialiasing there is nothing a distance
6695/// field offers that triangles do not, and a width that is not finite and
6696/// positive is not a stroke.
6697///
6698/// The joins and caps a stroke style also carries are ignored rather than
6699/// refused. These shapes are closed curves with no corners to join and no ends
6700/// to cap, so every setting produces the same outline -- which is why a stroked
6701/// one can take this path at all.
6702fn analytic_stroke(paint: &Paint) -> Option<f32> {
6703    if !paint.anti_alias {
6704        return None;
6705    }
6706    // The shape is drawn on a quad larger than itself and emits a fragment
6707    // everywhere on it, so a mode that discards the destination where the
6708    // source is transparent would erase what is behind it in the gap between
6709    // the two -- and in the corner of a rounded rectangle that gap is most of
6710    // the corner. Tessellating covers only the shape and has no such gap.
6711    if !paint.blend.respects_coverage() {
6712        return None;
6713    }
6714    // A distance field describes a continuous outline and has no notion of a
6715    // position along it, so a dashed stroke cannot be expressed this way at
6716    // all. Falling back to tessellation is what makes the dash appear; without
6717    // this the rounded rectangle and the circle would draw a solid outline and
6718    // silently ignore the pattern, which is the shape of bug the analytic path
6719    // is most able to hide -- the result looks like a stroke, because it is
6720    // one.
6721    if paint.dash.as_ref().is_some_and(|dash| dash.is_usable()) {
6722        return None;
6723    }
6724    // A mask blur is a layer around the draw, and a distance field evaluated on
6725    // a quad is not a shape that can be put inside one and blurred: the quad is
6726    // larger than the shape and the layer would blur its edges too.
6727    if paint.mask_blur > 0.0 {
6728        return None;
6729    }
6730    // An image filter is a layer around the draw for the same reason, and this
6731    // guard was missing when image filters were added -- so a blurred or moved
6732    // circle drew as though neither had been asked for. Nothing failed: the
6733    // shape was still a shape, and only a test comparing where it landed said
6734    // otherwise. Every route that needs a layer has to be refused here, which
6735    // is worth stating as the rule rather than as three cases.
6736    if !paint.image_filter.is_identity() {
6737        return None;
6738    }
6739    match &paint.style {
6740        Style::Fill => Some(0.0),
6741        Style::Stroke(stroke) => {
6742            let width = stroke.width;
6743            (width.is_finite() && width > 0.0).then_some(width)
6744        }
6745    }
6746}
6747
6748/// An ellipse inscribed in a rectangle, as four cubics.
6749///
6750/// The same construction a circle uses, with a different radius on each axis:
6751/// the constant that makes a cubic approximate a quarter turn does not care
6752/// which, since it scales with the axis it belongs to.
6753fn oval_path(bounds: Rect) -> Path {
6754    let (cx, cy) = (
6755        (bounds.left + bounds.right) / 2.0,
6756        (bounds.top + bounds.bottom) / 2.0,
6757    );
6758    let (rx, ry) = (bounds.width() / 2.0, bounds.height() / 2.0);
6759    let (kx, ky) = (KAPPA * rx, KAPPA * ry);
6760    let mut b = PathBuilder::new();
6761    b.move_to(Vec2::new(cx + rx, cy))
6762        .cubic_to(
6763            Vec2::new(cx + rx, cy + ky),
6764            Vec2::new(cx + kx, cy + ry),
6765            Vec2::new(cx, cy + ry),
6766        )
6767        .cubic_to(
6768            Vec2::new(cx - kx, cy + ry),
6769            Vec2::new(cx - rx, cy + ky),
6770            Vec2::new(cx - rx, cy),
6771        )
6772        .cubic_to(
6773            Vec2::new(cx - rx, cy - ky),
6774            Vec2::new(cx - kx, cy - ry),
6775            Vec2::new(cx, cy - ry),
6776        )
6777        .cubic_to(
6778            Vec2::new(cx + kx, cy - ry),
6779            Vec2::new(cx + rx, cy - ky),
6780            Vec2::new(cx + rx, cy),
6781        )
6782        .close();
6783    b.build()
6784}
6785
6786fn circle_path(center: Vec2, radius: f32) -> Path {
6787    let (cx, cy) = (center.x, center.y);
6788    let r = radius;
6789    let k = KAPPA * r;
6790    let mut b = PathBuilder::new();
6791    // Recorded for the same reason a rounded rectangle's is: a shadow arrives
6792    // as a path, and a circle is the one oval the blurred-rectangle expression
6793    // describes exactly -- corners of half the side, on a square.
6794    b.as_rounded_rect(
6795        GeometryRect::new(Vec2::new(cx - r, cy - r), Vec2::new(cx + r, cy + r)),
6796        r,
6797    );
6798    b.move_to(Vec2::new(cx + r, cy))
6799        .cubic_to(
6800            Vec2::new(cx + r, cy + k),
6801            Vec2::new(cx + k, cy + r),
6802            Vec2::new(cx, cy + r),
6803        )
6804        .cubic_to(
6805            Vec2::new(cx - k, cy + r),
6806            Vec2::new(cx - r, cy + k),
6807            Vec2::new(cx - r, cy),
6808        )
6809        .cubic_to(
6810            Vec2::new(cx - r, cy - k),
6811            Vec2::new(cx - k, cy - r),
6812            Vec2::new(cx, cy - r),
6813        )
6814        .cubic_to(
6815            Vec2::new(cx + k, cy - r),
6816            Vec2::new(cx + r, cy - k),
6817            Vec2::new(cx + r, cy),
6818        )
6819        .close();
6820    b.build()
6821}
6822
6823/// How far a shadow's blur reaches per unit of elevation, as a kernel radius.
6824///
6825/// The light's radius over its height, which is the ratio that decides how
6826/// quickly a shadow softens as its caster rises. Upstream writes it
6827/// `constexpr Scalar kLightRadius = 800 / 600;` in the dispatcher that draws
6828/// the shadow, and those are integer literals: the division happens in `int`
6829/// and the constant is one, not the one and a third the comment beside it
6830/// describes.
6831///
6832/// One is what this uses, because parity is against what upstream does rather
6833/// than against what it appears to have meant. This did carry the ratio the
6834/// comment states, and combined with reading the result as a deviation instead
6835/// of a radius it made every shadow here about twice as soft as the same
6836/// elevation gives upstream.
6837///
6838/// Note that `DlCanvas` has a second pair of these, `kShadowLightRadius` over
6839/// `kShadowLightHeight`, which are `DlScalar` and so do divide to one and a
6840/// third. Those size the shadow's *bounds*; this one draws it. Reading the
6841/// wrong pair is easy and gives a shadow a third too wide.
6842const LIGHT_RADIUS: f32 = 1.0;
6843
6844/// Kernel radius per deviation, for turning one into the other.
6845///
6846/// The square root of three, matching upstream's `kKernelRadiusPerSigma`. A
6847/// shadow's elevation gives a radius, and the blur takes a deviation, so the
6848/// conversion is not optional -- and upstream's is affine rather than a plain
6849/// scale, adding half a pixel so that a radius shrinking to nothing still
6850/// leaves a deviation the blur can act on.
6851const KERNEL_RADIUS_PER_SIGMA: f32 = 1.732_050_8;
6852
6853/// The deviation upstream blurs a shadow of this radius by.
6854///
6855/// `Radius::operator Sigma` in `impeller/geometry/sigma.cc`, which is
6856/// `radius / kKernelRadiusPerSigma + 0.5` for a positive radius and zero
6857/// otherwise.
6858fn sigma_for_radius(radius: f32) -> f32 {
6859    if radius > 0.0 {
6860        radius / KERNEL_RADIUS_PER_SIGMA + 0.5
6861    } else {
6862        0.0
6863    }
6864}
6865
6866/// What fraction of the stated color's alpha a shadow starts from.
6867///
6868/// A quarter, matching Impeller. A shadow is a suggestion of occlusion rather
6869/// than an absence of light, and at full alpha it reads as a hole. This is what
6870/// the tonal remap below begins with rather than the alpha a shadow ends up
6871/// drawn at -- for anything but a gray it raises the alpha again.
6872const SHADOW_ALPHA: f32 = 0.25;
6873
6874/// A shadow's color, tonally adjusted the way upstream adjusts it.
6875///
6876/// Ported from `DlDispatcherBase::drawShadow`, which says it ports
6877/// `SkShadowUtils::ComputeTonalColors`. The rule is that a colored shadow does
6878/// not read as a gray one tinted: a saturated shadow needs more alpha and less
6879/// saturation than the number a caller gave it, or it looks like a colored
6880/// object lying on the surface rather than an absence of light.
6881///
6882/// The arithmetic runs on **sRGB-encoded** components rather than on light,
6883/// because upstream's do: its pipeline holds encoded values throughout, so the
6884/// luminance this keys on is a luminance of encoded numbers. Computing it on
6885/// linear light would be the same formula answering a different question, and
6886/// would part company with upstream by more than the remap is worth.
6887///
6888/// It is the identity for a black shadow, which is nearly every shadow: at zero
6889/// luminance the color term falls out and the alpha is left at the quarter
6890/// above. What it changes is a colored one, and by a lot -- a fully saturated
6891/// red at full alpha comes out at better than twice the alpha and about
6892/// five eighths of the red.
6893fn tonal_shadow_color(color: Color) -> Color {
6894    let [r, g, b, a] = color.to_srgb();
6895    let alpha = a * SHADOW_ALPHA;
6896
6897    let luminance = (r.min(g).min(b) + r.max(g).max(b)) * 0.5;
6898
6899    let alpha_adjust = (2.6 + (-2.666_67 + 1.066_67 * alpha) * alpha) * alpha;
6900    let color_alpha = (3.544_762 + (-4.891_428 + 2.346_6 * luminance) * luminance) * luminance;
6901    let color_alpha = (alpha_adjust * color_alpha).clamp(0.0, 1.0);
6902
6903    let grayscale_alpha = (alpha * (1.0 - 0.4 * luminance)).clamp(0.0, 1.0);
6904
6905    let color_scale = color_alpha * (1.0 - grayscale_alpha);
6906    let tonal_alpha = color_scale + grayscale_alpha;
6907    // Guarded because a fully transparent shadow leaves both terms at zero, and
6908    // the ratio below is the only place that could divide by it.
6909    let unpremul_scale = if tonal_alpha != 0.0 {
6910        color_scale / tonal_alpha
6911    } else {
6912        0.0
6913    };
6914
6915    Color::srgb(
6916        unpremul_scale * r,
6917        unpremul_scale * g,
6918        unpremul_scale * b,
6919        tonal_alpha,
6920    )
6921}
6922
6923/// How far past its content a blur of this deviation reaches.
6924///
6925/// `(sigma - 0.5) * sqrt(3)`, which is upstream's `CalculateBlurRadius` and is
6926/// also where the shader stops taking taps -- so a target sized by this covers
6927/// everything the blur will actually read, and no more. It was three
6928/// deviations, which covered more of the curve than upstream does and made
6929/// every blur here wider than the same request gives it.
6930///
6931/// Shared rather than written twice. A bounded layer sizes its target with it,
6932/// and a mask blur style that combines the blurred coverage with the shape's
6933/// own has to size the layer holding both by the same rule -- which it did not
6934/// at first, and the halo was cut off square at the shape's own bounds.
6935/// The widest deviation a blur is asked for, matching upstream's `kMaxSigma`.
6936///
6937/// Not a limitation so much as the end of the useful range: at five hundred a
6938/// blur of anything smaller than a wall is a flat wash, and the reduction that
6939/// keeps the taps affordable has long since taken the image down to a handful
6940/// of texels.
6941pub(crate) const MAX_SIGMA: f32 = 500.0;
6942
6943/// The most taps a blur takes each way from center.
6944///
6945/// Must match `max_taps` in the blur shader, which is where the budget is
6946/// actually spent; this is the copy that decides when to shrink the image
6947/// instead of spreading the taps across it.
6948/// The largest side a recorded target may have, in texels.
6949///
6950/// Not a device limit -- this side of the renderer has no device -- but a
6951/// bound on what a *recording* may describe. Every current part reports a
6952/// maximum texture side of 16,384 or less, so a target twice that is already
6953/// past anything that could be rendered, and the number's job is to be
6954/// obviously larger than a real surface while small enough that a filter
6955/// emitting a pass per `MORPHOLOGY_TAPS` texels of radius stays countable.
6956///
6957/// It exists because `f32 as u32` saturates rather than wrapping or refusing:
6958/// without a ceiling a finite width of `3.4e38` becomes an extent of
6959/// `u32::MAX`, and a morphology over that asks for a hundred and thirty-four
6960/// million passes.
6961pub(crate) const MAX_TARGET_SIDE: f32 = 32_768.0;
6962
6963pub(crate) const BLUR_MAX_TAPS: f32 = 32.0;
6964
6965/// The kernel radius a deviation gives, in texels of whatever it is blurring.
6966///
6967/// Upstream's `CalculateBlurRadius`, which is `Radius(Sigma(sigma))`. Shared
6968/// so that the rule deciding how far a blur reaches, the rule sizing a target
6969/// to hold it, and the rule deciding whether it needs shrinking first cannot
6970/// drift apart -- they are the same question asked by three callers.
6971/// The error function, to about seven digits.
6972///
6973/// The same rational approximation the shader evaluates, and it has to be the
6974/// same one: `scale` is computed here and the fade there, so two different
6975/// approximations would normalize the shape against a curve it is not drawn
6976/// with. Upstream keeps a copy on each side for the same reason.
6977pub(crate) fn erf7(value: f32) -> f32 {
6978    let x = value * std::f32::consts::FRAC_2_SQRT_PI;
6979    let xx = x * x;
6980    let series = x + (0.24295 + (0.03395 + 0.0104 * xx) * xx) * (x * xx);
6981    series / (1.0 + series * series).sqrt()
6982}
6983
6984pub(crate) fn blur_radius(sigma: f32) -> f32 {
6985    ((sigma - 0.5) * KERNEL_RADIUS_PER_SIGMA).max(0.0)
6986}
6987
6988pub(crate) fn blur_reach(sigma: f32) -> f32 {
6989    if sigma > 0.0 {
6990        blur_radius(sigma).ceil()
6991    } else {
6992        0.0
6993    }
6994}
6995
6996/// A color in the form a vertex carries one.
6997///
6998/// Premultiplied, because a vertex color is interpolated across a triangle and
6999/// straight color interpolated between differing alphas is wrong at every point
7000/// between the ends.
7001/// The largest number of sections a vertex-interpolated gradient will emit.
7002///
7003/// Sections are geometry, so stop count is not bounded here the way the paint
7004/// block's four are -- but it is not unbounded either: each section is four
7005/// vertices and six indices, and past some count the fragment walk is cheaper
7006/// than the vertices. The shader route is always available, so the cap is a
7007/// fallback rather than a refusal.
7008const MAX_GRADIENT_SECTIONS: usize = 64;
7009
7010/// Whether this gradient can be drawn by interpolating across vertices instead
7011/// of evaluating per fragment, and the sections to draw if so.
7012///
7013/// Upstream's `CanApplyFastGradient` asks three things, and so does this: the
7014/// gradient is axis-aligned, its endpoints land on the edges of the rectangle
7015/// being covered, and the geometry is a rectangle at all. When they hold, the
7016/// parameter runs exactly zero to one across the shape, so one quad per pair of
7017/// stops with the stop colors on its corners is the same picture the fragment
7018/// walk produces -- see §19 of `docs/non-parity.md` for the measured agreement.
7019///
7020/// Axis-aligned means the two endpoints share a coordinate: an x for a vertical
7021/// wash, a y for a horizontal one. Landing on the edges is the strict half.
7022///
7023/// **`Clamp` only, and the reasoning that admitted every tile mode was wrong.**
7024/// It said that endpoints on the edges make the mode irrelevant, the parameter
7025/// never leaving `[0, 1]` inside the shape. That holds only while the edges fall
7026/// between pixels. Give the rectangle a fractional edge and the rasterizer
7027/// covers pixels whose centers lie just outside the gradient's span, so the
7028/// fragment walk's parameter does leave the interval -- and `Repeat` wraps it to
7029/// the far end, which is a whole stop's difference rather than a rounding one.
7030/// Sections cannot wrap: their vertices carry the end colors and interpolation
7031/// stays between them.
7032///
7033/// Measured by `gradient_routes.rs` on lavapipe at Mesa 26.2.3: a vertical
7034/// gradient on a rectangle whose edges sit at `y = 38.5003` and `62.5003`,
7035/// tiling by `Repeat`, differs between the two routes by **56 of 255** -- the
7036/// full range of the only channel its stops move. `Clamp` is what the two agree
7037/// on, because clamping is what interpolation already does.
7038///
7039/// Returned in rectangle space. The caller transforms the corners, which is
7040/// what keeps this independent of the transform: a rotated or skewed rectangle
7041/// is still a rectangle in its own space, and the gradient still runs along one
7042/// of its axes.
7043/// One quad of a vertex-interpolated gradient: the corners in the rectangle's
7044/// own space, and the premultiplied color at each.
7045///
7046/// Wound top-left, top-right, bottom-right, bottom-left, which is what
7047/// `draw_gradient_sections` indexes against.
7048struct GradientSection {
7049    corners: [Vec2; 4],
7050    colors: [[f32; 4]; 4],
7051}
7052
7053fn fast_gradient_sections(rect: Rect, shader: &Shader) -> Option<Vec<GradientSection>> {
7054    let Shader::LinearGradient {
7055        start,
7056        end,
7057        stops,
7058        tile,
7059    } = shader
7060    else {
7061        return None;
7062    };
7063    // See the note above: only clamping agrees with what sections do at an edge.
7064    if *tile != TileMode::Clamp {
7065        return None;
7066    }
7067    if stops.len() < 2 || stops.len() > MAX_GRADIENT_SECTIONS + 1 {
7068        return None;
7069    }
7070    // Non-decreasing and inside the unit interval. A stop list that is neither
7071    // is the shader route's to interpret, not this one's to guess at.
7072    if stops.first()?.offset != 0.0 || stops.last()?.offset != 1.0 {
7073        return None;
7074    }
7075    if stops.windows(2).any(|w| w[1].offset < w[0].offset) {
7076        return None;
7077    }
7078    // One alpha across the list, and this is not a conservatism -- it is the
7079    // one case where the two routes do not produce the same picture.
7080    //
7081    // A gradient is interpolated in *straight* color, which is what `dart:ui`
7082    // and Skia do: the fragment walk interpolates the stops and premultiplies
7083    // the result. A vertex color cannot work that way. What the rasterizer
7084    // interpolates is what gets multiplied in, so the colors have to be
7085    // premultiplied before they reach it -- and premultiplying then
7086    // interpolating is not interpolating then premultiplying unless alpha is
7087    // constant. Measured at 58 of 255 between the two routes on a two-stop
7088    // gradient from alpha one to alpha a tenth.
7089    //
7090    // Uniform alpha is the ordinary case -- a wash is opaque, and a fading one
7091    // is usually a layer's opacity rather than the gradient's -- so the route
7092    // keeps the gradients it was built for and gives up the ones it would get
7093    // wrong.
7094    let alpha = stops[0].color.to_array()[3];
7095    if stops.iter().any(|s| s.color.to_array()[3] != alpha) {
7096        return None;
7097    }
7098
7099    // Which axis varies, and the two coordinates it runs between.
7100    let horizontal = start.y == end.y && start.x != end.x;
7101    let vertical = start.x == end.x && start.y != end.y;
7102    let (from, to) = if horizontal {
7103        (start.x, end.x)
7104    } else if vertical {
7105        (start.y, end.y)
7106    } else {
7107        return None;
7108    };
7109
7110    // The endpoints are the shape's own edges, in either order. Exact, because
7111    // anything else leaves a parameter outside `[0, 1]` somewhere in the shape
7112    // and the tile mode starts to matter.
7113    let (low, high) = if horizontal {
7114        (rect.left, rect.right)
7115    } else {
7116        (rect.top, rect.bottom)
7117    };
7118    if (from.min(to), from.max(to)) != (low, high) {
7119        return None;
7120    }
7121
7122    let mut sections = Vec::with_capacity(stops.len() - 1);
7123    for pair in stops.windows(2) {
7124        let (a, b) = (&pair[0], &pair[1]);
7125        // A zero-width section contributes nothing and would be a degenerate
7126        // quad; a repeated offset is how a caller asks for a hard edge, and
7127        // skipping it is what produces one.
7128        if a.offset == b.offset {
7129            continue;
7130        }
7131        let at = |t: f32| from + (to - from) * t;
7132        let (p, q) = (at(a.offset), at(b.offset));
7133        let (ca, cb) = (premultiplied(a.color), premultiplied(b.color));
7134        // Wound the same way for both orientations -- top-left, top-right,
7135        // bottom-right, bottom-left of the section -- so the colors differ
7136        // instead of the corners. Which corners sit at the section's start
7137        // depends on which axis varies: along x it is the first and last, along
7138        // y the first two.
7139        let (corners, colors) = if horizontal {
7140            (
7141                [
7142                    Vec2::new(p, rect.top),
7143                    Vec2::new(q, rect.top),
7144                    Vec2::new(q, rect.bottom),
7145                    Vec2::new(p, rect.bottom),
7146                ],
7147                [ca, cb, cb, ca],
7148            )
7149        } else {
7150            (
7151                [
7152                    Vec2::new(rect.left, p),
7153                    Vec2::new(rect.right, p),
7154                    Vec2::new(rect.right, q),
7155                    Vec2::new(rect.left, q),
7156                ],
7157                [ca, ca, cb, cb],
7158            )
7159        };
7160        sections.push(GradientSection { corners, colors });
7161    }
7162    (!sections.is_empty()).then_some(sections)
7163}
7164
7165fn premultiplied(color: Color) -> [f32; 4] {
7166    let [r, g, b, a] = color.to_array();
7167    [r * a, g * a, b * a, a]
7168}
7169
7170#[cfg(test)]
7171mod tests {
7172    use super::*;
7173
7174    fn canvas() -> Canvas {
7175        Canvas::new(Extent2D::new(128, 128))
7176    }
7177
7178    /// A backdrop layer opened under a clip is the size of the clip.
7179    ///
7180    /// It used to be the size of the parent, whatever the clip said, so a
7181    /// frosted panel a fortieth of the frame's area recorded a frame-sized
7182    /// target. The clip binds the layer's content and the draw that composites
7183    /// it alike, so there is nothing outside it for the layer to hold.
7184    ///
7185    /// The extents are asserted rather than the pixels because the pixels do
7186    /// not change: the sibling test below is what says they do not.
7187    #[test]
7188    fn a_backdrop_layer_under_a_clip_is_no_larger_than_the_clip() {
7189        let mut canvas = canvas();
7190        canvas.clear(Color::srgb(0.2, 0.3, 0.4, 1.0));
7191        canvas
7192            .draw_rect(
7193                Rect::new(0.0, 0.0, 128.0, 128.0),
7194                &Paint::fill(Color::srgb(0.9, 0.2, 0.2, 1.0)),
7195            )
7196            .expect("the ground");
7197        canvas.save();
7198        canvas
7199            .clip_rect(Rect::new(40.0, 40.0, 80.0, 80.0))
7200            .expect("the clip");
7201        canvas.save_layer(Layer::opacity(1.0).with_backdrop_blur(4.0));
7202        canvas
7203            .draw_rect(
7204                Rect::new(40.0, 40.0, 80.0, 80.0),
7205                &Paint::fill(Color::srgb(1.0, 0.6, 0.0, 0.6)),
7206            )
7207            .expect("the panel");
7208        canvas.restore();
7209        canvas.restore();
7210
7211        let recording = canvas.finish();
7212        let frame = recording.extent;
7213        let narrowed: Vec<_> = recording
7214            .passes
7215            .iter()
7216            .map(|pass| pass.extent)
7217            .filter(|extent| *extent != frame)
7218            .collect();
7219        // The layer's own target, the crop of its region out of the capture,
7220        // and both passes of the backdrop's blur. What stays frame-sized is
7221        // the pass being captured and the one the frame ends in, and neither
7222        // is allocated for this layer.
7223        assert_eq!(
7224            narrowed.len(),
7225            4,
7226            "four passes should be sized to the clip, and {} are: {:?}",
7227            narrowed.len(),
7228            recording
7229                .passes
7230                .iter()
7231                .map(|pass| pass.extent)
7232                .collect::<Vec<_>>()
7233        );
7234        for extent in narrowed {
7235            assert!(
7236                extent.width <= 48 && extent.height <= 48,
7237                "a pass came out {}x{} for a clip forty pixels across",
7238                extent.width,
7239                extent.height
7240            );
7241        }
7242    }
7243
7244    /// A layer sharing a backdrop key is narrowed too, and its capture is not.
7245    ///
7246    /// These two are separate regions and were once excluded together. The
7247    /// layer's own target is bound by the clip exactly as an unshared one is.
7248    /// What the key shares is the capture and the filtered image over it, and
7249    /// those have to cover every group naming the key -- so they stay the
7250    /// parent's size, and a second group somewhere else reads the same pass.
7251    #[test]
7252    fn a_shared_backdrop_layer_is_narrowed_while_its_capture_is_not() {
7253        let mut canvas = canvas();
7254        canvas.clear(Color::srgb(0.2, 0.3, 0.4, 1.0));
7255        let panel = |canvas: &mut Canvas, clip: Rect| {
7256            canvas.save();
7257            canvas.clip_rect(clip).expect("the clip");
7258            canvas.save_layer(
7259                Layer::opacity(1.0)
7260                    .with_backdrop_blur(4.0)
7261                    .with_backdrop_id(7),
7262            );
7263            canvas
7264                .draw_rect(clip, &Paint::fill(Color::srgb(1.0, 0.6, 0.0, 0.6)))
7265                .expect("the panel");
7266            canvas.restore();
7267            canvas.restore();
7268        };
7269        // Opposite corners, so nothing can pass by covering one with the other.
7270        panel(&mut canvas, Rect::new(8.0, 8.0, 48.0, 48.0));
7271        panel(&mut canvas, Rect::new(80.0, 80.0, 120.0, 120.0));
7272
7273        let recording = canvas.finish();
7274        let frame = recording.extent;
7275        let extents: Vec<_> = recording.passes.iter().map(|pass| pass.extent).collect();
7276        let narrowed: Vec<_> = extents.iter().filter(|e| **e != frame).collect();
7277        // One target per panel, and nothing else: the capture and the two
7278        // passes its blur takes are shared, and all three cover the parent.
7279        assert_eq!(
7280            narrowed.len(),
7281            2,
7282            "one narrowed target per panel and no more, in {extents:?}"
7283        );
7284        for extent in narrowed {
7285            assert!(
7286                extent.width <= 40 && extent.height <= 40,
7287                "a panel target came out {}x{} for a clip forty pixels across",
7288                extent.width,
7289                extent.height
7290            );
7291        }
7292        // The second panel pays for its own target and nothing else: the cut,
7293        // and the two passes of the blur over it, are taken once between them.
7294        // Six in all -- the cut, the blur's two, a target each, and the pass
7295        // the frame ends in, which holds both composites.
7296        assert_eq!(
7297            extents.len(),
7298            6,
7299            "a cut, two blur passes, a target each, and the frame's own, in \
7300             {extents:?}"
7301        );
7302    }
7303
7304    /// And it draws what stating the clip as the layer's bounds would.
7305    ///
7306    /// The narrowing above is an optimization, so the thing to check is that it
7307    /// is only that. A caller who writes the bounds out has always taken the
7308    /// bounded path; a caller who relies on the clip now takes it too, and the
7309    /// two recordings have to describe the same picture.
7310    #[test]
7311    fn narrowing_to_the_clip_records_what_stating_it_would() {
7312        let build = |bounded: bool| {
7313            let mut canvas = canvas();
7314            canvas.clear(Color::srgb(0.1, 0.1, 0.1, 1.0));
7315            canvas
7316                .draw_rect(
7317                    Rect::new(0.0, 20.0, 128.0, 60.0),
7318                    &Paint::fill(Color::srgb(0.9, 0.4, 0.1, 1.0)),
7319                )
7320                .expect("the ground");
7321            let clip = Rect::new(24.0, 34.0, 104.0, 94.0);
7322            canvas.save();
7323            canvas.clip_rect(clip).expect("the clip");
7324            let layer = Layer::opacity(1.0).with_backdrop_blur(6.0);
7325            if bounded {
7326                canvas.save_layer_bounds(layer, clip);
7327            } else {
7328                canvas.save_layer(layer);
7329            }
7330            canvas.restore();
7331            canvas.restore();
7332            canvas.finish()
7333        };
7334        let from_clip = build(false);
7335        let from_bounds = build(true);
7336        assert_eq!(from_clip.passes.len(), from_bounds.passes.len());
7337        for (a, b) in from_clip.passes.iter().zip(from_bounds.passes.iter()) {
7338            assert_eq!(a.extent, b.extent, "the two spellings size a pass alike");
7339            assert_eq!(
7340                a.batch.vertices(),
7341                b.batch.vertices(),
7342                "the two spellings record the same geometry"
7343            );
7344        }
7345    }
7346
7347    /// How far a blur reaches, which four comments in this tree got wrong.
7348    ///
7349    /// The kernel is truncated at `(sigma - 0.5) * sqrt(3)` -- upstream's
7350    /// `kKernelRadiusPerSigma` -- and every layer sized to hold a blur asks
7351    /// `blur_reach` for it. Nothing pinned the arithmetic, so the prose drifted
7352    /// to "three deviations" in four places and stayed there: a test written
7353    /// against that phrase expected 88 where the renderer gives 68, and the
7354    /// phrase was wrong rather than the renderer.
7355    ///
7356    /// Pinned here because the number is not free to change. It decides how
7357    /// wide a halo is, so moving it moves every blurred picture away from
7358    /// upstream's -- and it decides a target's size, so getting it *smaller*
7359    /// cuts the halo off square, which reads as a shadow with a straight edge
7360    /// rather than as arithmetic.
7361    #[test]
7362    fn a_blur_reaches_the_radius_its_kernel_is_truncated_at() {
7363        // Sqrt three per deviation, less the half pixel upstream subtracts, and
7364        // rounded out to a whole texel because a target is whole texels.
7365        assert_eq!(blur_reach(8.0), 13.0, "ceil(7.5 * sqrt(3))");
7366        assert_eq!(blur_reach(2.0), 3.0, "ceil(1.5 * sqrt(3))");
7367
7368        // Not three deviations, which is what the prose used to say. Stated as
7369        // its own assertion because the two agree closely enough at small sigma
7370        // that a spot check would not tell them apart.
7371        assert!(
7372            blur_reach(50.0) < 3.0 * 50.0,
7373            "the kernel is truncated nearer one and three quarter deviations \
7374             than three"
7375        );
7376
7377        // A sigma that describes no blur reaches nowhere, and a layer asking
7378        // for one gets no widening rather than half a pixel of it.
7379        assert_eq!(blur_reach(0.0), 0.0);
7380        assert_eq!(blur_reach(0.5), 0.0, "the half pixel is subtracted first");
7381        assert_eq!(blur_reach(-1.0), 0.0);
7382
7383        // And it never shrinks as the blur widens, which is what makes a target
7384        // sized from it safe.
7385        let mut previous = 0.0;
7386        for tenth in 0..600 {
7387            let reach = blur_reach(tenth as f32 / 10.0);
7388            assert!(
7389                reach >= previous,
7390                "reach fell at sigma {}",
7391                tenth as f32 / 10.0
7392            );
7393            previous = reach;
7394        }
7395    }
7396
7397    #[test]
7398    fn drawing_accumulates_into_one_batch() {
7399        let mut canvas = canvas();
7400        let paint = Paint::fill(Color::WHITE);
7401        canvas
7402            .draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &paint)
7403            .unwrap();
7404        canvas
7405            .draw_rect(Rect::new(20.0, 20.0, 30.0, 30.0), &paint)
7406            .unwrap();
7407
7408        // Two shapes, one batch: describing the frame before submitting is what
7409        // lets them share a pass.
7410        //
7411        // And one *draw*, which is stronger and newer. Both take the analytic
7412        // route, and that route carries the shape's own space on its vertices
7413        // rather than in its material, so two rectangles of a size differing
7414        // only in where they sit are the same material and merge. It was two
7415        // until then, with the placement inside the material making every
7416        // instance unequal to every other.
7417        let recording = canvas.finish();
7418        assert_eq!(recording.draw_count(), 1);
7419    }
7420
7421    #[test]
7422    fn an_invisible_paint_records_nothing() {
7423        let mut canvas = canvas();
7424        let invisible = Paint::fill(Color::WHITE.with_alpha(0.0));
7425        canvas
7426            .draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &invisible)
7427            .unwrap();
7428        canvas
7429            .draw_circle(Vec2::new(5.0, 5.0), 4.0, &invisible)
7430            .unwrap();
7431
7432        // Rejecting early keeps empty geometry out of the batch rather than
7433        // tessellating it and discovering it was empty.
7434        assert!(canvas.finish().is_empty());
7435    }
7436
7437    #[test]
7438    fn outsetting_grows_every_side_and_negating_it_shrinks_back() {
7439        let rect = Rect::new(10.0, 20.0, 40.0, 60.0);
7440        let grown = rect.outset(5.0);
7441        assert_eq!(
7442            (grown.left, grown.top, grown.right, grown.bottom),
7443            (5.0, 15.0, 45.0, 65.0)
7444        );
7445        // Symmetric, which is what lets a caller undo one: a blur's reach is
7446        // the same in both directions and a target sized by it has to be too.
7447        let back = grown.outset(-5.0);
7448        assert_eq!(
7449            (back.left, back.top, back.right, back.bottom),
7450            (rect.left, rect.top, rect.right, rect.bottom)
7451        );
7452    }
7453
7454    #[test]
7455    fn degenerate_shapes_record_nothing() {
7456        let mut canvas = canvas();
7457        let paint = Paint::fill(Color::WHITE);
7458        canvas
7459            .draw_rect(Rect::new(10.0, 10.0, 10.0, 20.0), &paint)
7460            .unwrap();
7461        canvas.draw_circle(Vec2::ZERO, 0.0, &paint).unwrap();
7462        assert!(canvas.finish().is_empty());
7463    }
7464
7465    #[test]
7466    fn save_and_restore_return_the_previous_transform() {
7467        let mut canvas = canvas();
7468        canvas.translate(10.0, 20.0);
7469        let outer = canvas.transform();
7470
7471        canvas.save();
7472        canvas.scale(3.0, 3.0).rotate(0.5);
7473        assert_ne!(canvas.transform(), outer);
7474
7475        canvas.restore();
7476        assert_eq!(canvas.transform(), outer);
7477        assert_eq!(canvas.save_depth(), 0);
7478    }
7479
7480    #[test]
7481    fn saves_nest() {
7482        let mut canvas = canvas();
7483        let identity = canvas.transform();
7484        canvas.save();
7485        canvas.translate(5.0, 0.0);
7486        canvas.save();
7487        canvas.translate(5.0, 0.0);
7488        assert_eq!(canvas.save_depth(), 2);
7489
7490        canvas.restore();
7491        assert_eq!(
7492            canvas.transform(),
7493            Transform2D::from(Affine2::from_translation(Vec2::new(5.0, 0.0)))
7494        );
7495        canvas.restore();
7496        assert_eq!(canvas.transform(), identity);
7497    }
7498
7499    #[test]
7500    fn restoring_too_often_leaves_the_transform_alone() {
7501        let mut canvas = canvas();
7502        canvas.translate(7.0, 3.0);
7503        let current = canvas.transform();
7504        // An unbalanced restore is a caller bug, but taking down a frame loop
7505        // for it is worse than continuing with a transform that is still right.
7506        canvas.restore().restore().restore();
7507        assert_eq!(canvas.transform(), current);
7508    }
7509
7510    #[test]
7511    fn transforms_compose_in_the_order_applied() {
7512        let mut canvas = canvas();
7513        canvas.translate(10.0, 0.0).scale(2.0, 2.0);
7514        // Scale then translate, or translate then scale, place a point very
7515        // differently; the later call applies in the frame the earlier set up.
7516        let mapped = canvas.transform().project_point2(Vec2::new(1.0, 0.0));
7517        assert!((mapped - Vec2::new(12.0, 0.0)).length() < 1e-5);
7518    }
7519
7520    #[test]
7521    fn antialiasing_is_off_unless_something_asks_for_it() {
7522        let mut canvas = canvas();
7523        let aliased = Paint::fill(Color::WHITE).with_anti_alias(false);
7524        canvas
7525            .draw_rect(Rect::from_size(10.0, 10.0), &aliased)
7526            .unwrap();
7527        // Multisampling costs bandwidth, and a frame of solid rectangles gains
7528        // nothing from it.
7529        assert_eq!(canvas.finish().root().descriptor.samples, 1);
7530    }
7531
7532    #[test]
7533    fn one_antialiased_shape_antialiases_the_frame() {
7534        let mut canvas = canvas();
7535        canvas
7536            .draw_rect(
7537                Rect::from_size(10.0, 10.0),
7538                &Paint::fill(Color::WHITE).with_anti_alias(false),
7539            )
7540            .unwrap();
7541        // A path, because it has to be tessellated. A circle or a rounded
7542        // rectangle would antialias itself from a distance field and would
7543        // rightly leave the pass alone -- which the test below is about.
7544        let mut triangle = PathBuilder::new();
7545        triangle
7546            .move_to(Vec2::new(20.0, 20.0))
7547            .line_to(Vec2::new(40.0, 20.0))
7548            .line_to(Vec2::new(20.0, 40.0))
7549            .close();
7550        canvas
7551            .draw_path(&triangle.build(), &Paint::fill(Color::WHITE))
7552            .unwrap();
7553
7554        // Sampling is a property of the pass, so it cannot vary per shape.
7555        // Honoring the request for the frame beats silently ignoring it.
7556        assert!(canvas.finish().root().descriptor.samples > 1);
7557    }
7558
7559    #[test]
7560    fn a_shape_that_antialiases_itself_leaves_the_pass_alone() {
7561        // The saving that comes with the distance field, and the reason it is
7562        // worth having beyond the vertex count: a frame whose only antialiased
7563        // shapes compute their own coverage does not have to multisample, which
7564        // is four times the fill and four times the bandwidth for an edge it
7565        // was already going to get right.
7566        let mut canvas = canvas();
7567        canvas
7568            .draw_circle(Vec2::splat(20.0), 8.0, &Paint::fill(Color::WHITE))
7569            .unwrap();
7570        canvas
7571            .draw_rrect(
7572                Rect::new(30.0, 30.0, 60.0, 50.0),
7573                6.0,
7574                &Paint::fill(Color::WHITE),
7575            )
7576            .unwrap();
7577        assert_eq!(
7578            canvas.finish().root().descriptor.samples,
7579            1,
7580            "an analytic shape should not multisample the pass"
7581        );
7582    }
7583
7584    /// A black shadow is untouched by the tonal remap; a colored one is not.
7585    ///
7586    /// Both halves matter. The remap exists for colored shadows, and if it
7587    /// moved a black one it would change nearly every shadow anybody draws --
7588    /// so the identity is the safety property and the change is the feature.
7589    ///
7590    /// The figures are upstream's formula evaluated by hand rather than
7591    /// recorded from this implementation, which is the only way a test of a
7592    /// port can fail when the port is wrong.
7593    #[test]
7594    fn a_colored_shadow_is_tonally_adjusted_and_a_black_one_is_not() {
7595        // Black: at zero luminance the color term vanishes and the alpha is
7596        // left at the quarter it started from.
7597        let black = super::tonal_shadow_color(Color::srgb(0.0, 0.0, 0.0, 1.0));
7598        let [r, g, b, a] = black.to_srgb();
7599        assert_eq!([r, g, b], [0.0, 0.0, 0.0], "a black shadow gained color");
7600        assert!(
7601            (a - 0.25).abs() < 1e-6,
7602            "a black shadow should keep the quarter alpha, got {a}"
7603        );
7604
7605        // Saturated red at full alpha. Luminance is a half, so:
7606        //   alpha_adjust    = (2.6 + (-2.66667 + 1.06667*0.25)*0.25)*0.25 = 0.5
7607        //   color_alpha     = (3.544762 + (-4.891428 + 2.3466*0.5)*0.5)*0.5
7608        //                   = 0.842849, times alpha_adjust  = 0.421424
7609        //   grayscale_alpha = 0.25 * (1 - 0.4*0.5)           = 0.2
7610        //   color_scale     = 0.421424 * 0.8                 = 0.337140
7611        //   tonal_alpha     = 0.537140
7612        //   unpremul_scale  = 0.337140 / 0.537140            = 0.627650
7613        let red = super::tonal_shadow_color(Color::srgb(1.0, 0.0, 0.0, 1.0));
7614        let [r, g, b, a] = red.to_srgb();
7615        assert!(
7616            (a - 0.537_140).abs() < 1e-4,
7617            "the tonal alpha for a red shadow is {a}, not 0.53714"
7618        );
7619        assert!(
7620            (r - 0.627_650).abs() < 1e-4,
7621            "the tonal red for a red shadow is {r}, not 0.62765"
7622        );
7623        assert_eq!([g, b], [0.0, 0.0], "a red shadow gained other channels");
7624
7625        // And it is emphatically not what taking a quarter of the alpha gives,
7626        // which is what this used to do.
7627        assert!(
7628            a > 0.5,
7629            "the remap left the alpha near the naive quarter: {a}"
7630        );
7631
7632        // A mid-tone, which is the case that says *which space* this runs in.
7633        // Neither of the colors above can: zero and one are fixed points of the
7634        // transfer function, so a saturated primary is the same number encoded
7635        // or linear and the two readings agree by accident. Here they do not --
7636        // the same formula on linear light gives (0.137, 0.032, 0.004) at an
7637        // alpha of 0.410, against upstream's (0.345, 0.173, 0.058) at 0.506.
7638        let midtone = super::tonal_shadow_color(Color::srgb(0.6, 0.3, 0.1, 1.0));
7639        let [r, g, b, a] = midtone.to_srgb();
7640        for (got, want, name) in [
7641            (a, 0.506_265, "alpha"),
7642            (r, 0.345_193, "red"),
7643            (g, 0.172_596, "green"),
7644            (b, 0.057_532, "blue"),
7645        ] {
7646            assert!(
7647                (got - want).abs() < 1e-4,
7648                "the tonal {name} for a mid-tone shadow is {got}, not {want} -- \
7649                 which is what running the remap on light rather than on encoded \
7650                 values would give"
7651            );
7652        }
7653    }
7654
7655    #[test]
7656    fn clearing_sets_the_background_rather_than_recording_a_draw() {
7657        let mut canvas = canvas();
7658        canvas.clear(Color::rgba8(20, 30, 40, 255));
7659        let recording = canvas.finish();
7660        // A clear is a pass property; recording it as a full-target rectangle
7661        // would cost a draw and defeat the load operation.
7662        assert!(recording.is_empty());
7663        assert!(recording.root().descriptor.clear.is_some());
7664    }
7665
7666    /// A morphology radius cannot decide how many passes a recording holds.
7667    ///
7668    /// The loop emits a pass per `MORPHOLOGY_TAPS` texels, so before the clamp a
7669    /// radius of a million gave sixty-two thousand passes and `1e20` exhausted
7670    /// memory -- through `Morphology::dilate`, whose sanitizing rejects only what
7671    /// is negative or not finite. Nothing about that input was malformed.
7672    #[test]
7673    fn a_huge_morphology_radius_is_bounded_by_what_the_target_can_show() {
7674        // The morphology materials a radius produces, in order. Compared rather
7675        // than counted, because the clamp's justification is that a wider window
7676        // cannot change a pixel -- and identical materials over identical passes
7677        // is that claim in a form a machine can check without a device. It says
7678        // the two requests are not merely the same size but the same recording,
7679        // and the shader is a function of what it is handed.
7680        let filters = |radius: f32| {
7681            let mut canvas = canvas();
7682            canvas.clear(Color::BLACK);
7683            canvas.save_layer(
7684                Layer::opacity(1.0).with_morphology(Morphology::dilate(radius, radius)),
7685            );
7686            canvas
7687                .draw_rect(Rect::new(8.0, 8.0, 56.0, 56.0), &Paint::fill(Color::WHITE))
7688                .expect("a rectangle is a rectangle");
7689            canvas.restore();
7690            let recording = canvas.finish();
7691            let morphology: Vec<Material> = recording
7692                .passes
7693                .iter()
7694                .flat_map(|pass| pass.batch.draws())
7695                .filter(|draw| matches!(draw.material, Material::Morphology { .. }))
7696                .map(|draw| draw.material.clone())
7697                .collect();
7698            (recording.passes.len(), morphology)
7699        };
7700
7701        // A 128-square target, so each axis saturates at 128 texels: four passes
7702        // an axis at thirty-two taps each, plus the root and the composite.
7703        let (passes, saturated) = filters(128.0);
7704        assert!(passes < 16, "{passes} passes to saturate a 128 square");
7705        assert_eq!(saturated.len(), 8, "{saturated:?}");
7706        for radius in [1e3f32, 1e6, 1e20, f32::MAX] {
7707            let (grew, wider) = filters(radius);
7708            assert_eq!(
7709                grew, passes,
7710                "a radius of {radius:e} cost more passes than saturating the target"
7711            );
7712            assert_eq!(
7713                wider, saturated,
7714                "a radius of {radius:e} asked for a different filter than saturating the target"
7715            );
7716        }
7717    }
7718
7719    /// Infinity terminates, which it did not before.
7720    ///
7721    /// `Morphology::dilate` maps it to zero, so this reaches the loop the only way
7722    /// left: the fields are public, so a struct literal skips the constructor.
7723    /// Subtracting the taps from infinity leaves infinity, so the loop never ended
7724    /// and each turn of it allocated a pass.
7725    #[test]
7726    fn a_non_finite_morphology_radius_is_no_filter_rather_than_no_end() {
7727        for radius in [f32::INFINITY, f32::NEG_INFINITY, f32::NAN] {
7728            let morphology = Morphology {
7729                radius: [radius, radius],
7730                dilate: true,
7731            };
7732            assert_eq!(
7733                morphology.applied_radius(Extent2D::new(128, 128)),
7734                [0.0, 0.0],
7735                "a radius of {radius} survived as something to apply"
7736            );
7737            let mut canvas = canvas();
7738            canvas.clear(Color::BLACK);
7739            canvas.save_layer(Layer {
7740                morphology: Some(morphology),
7741                ..Layer::opacity(1.0)
7742            });
7743            canvas.restore();
7744            // Reaching here at all is the assertion.
7745            assert!(!canvas.finish().passes.is_empty());
7746        }
7747    }
7748
7749    /// The clamp is per axis, and is the extent of that axis.
7750    #[test]
7751    fn the_applied_radius_is_clamped_to_each_axis_separately() {
7752        let morphology = Morphology {
7753            radius: [1e9, 7.0],
7754            dilate: false,
7755        };
7756        assert_eq!(
7757            morphology.applied_radius(Extent2D::new(64, 256)),
7758            [64.0, 7.0],
7759            "the clamp took the wrong axis or clamped what did not need it"
7760        );
7761        // Negative is refused rather than reflected, as `sane` does.
7762        let negative = Morphology {
7763            radius: [-5.0, -0.0],
7764            dilate: true,
7765        };
7766        assert_eq!(negative.applied_radius(Extent2D::new(64, 64)), [0.0, 0.0]);
7767    }
7768
7769    /// A blur's reduction terminates whatever the sigma and the extent.
7770    ///
7771    /// The reduction doubles a divisor until the kernel fits the tap budget or
7772    /// the axis runs out. An infinite sigma never satisfies the first, so the
7773    /// extent is the only stop -- and against a very large extent the divisor
7774    /// reached two to the thirty-first, where the old condition's `scale * 2`
7775    /// overflowed. Release was worse rather than better: the product wrapped to
7776    /// zero and the division panicked.
7777    ///
7778    /// A struct literal is how a non-finite sigma gets here at all, since
7779    /// `Layer::with_blur_xy` maps one to zero. `Layer::blur` is a public field.
7780    ///
7781    /// Found by `a_sequence_of_any_operations_records_something_addressable`,
7782    /// which generated a layer with an infinite blur inside bounds of `-1e20`.
7783    #[test]
7784    fn the_blur_reduction_terminates_for_any_sigma_and_extent() {
7785        // Reaching the end of this at all is most of the assertion.
7786        for extent in [0u32, 1, 2, 3, 128, u32::MAX / 2, u32::MAX - 1, u32::MAX] {
7787            for sigma in [
7788                f32::INFINITY,
7789                f32::NEG_INFINITY,
7790                f32::NAN,
7791                -1.0,
7792                0.0,
7793                1e30,
7794                f32::MAX,
7795                500.0,
7796                8.0,
7797            ] {
7798                let scale = Canvas::blur_downsample(sigma, extent);
7799                assert!(
7800                    scale.is_power_of_two(),
7801                    "sigma {sigma:e} over {extent} gave a divisor of {scale}, which \
7802                     is not a power of two, so the halvings are not exact"
7803                );
7804                assert!(
7805                    scale == 1 || scale <= extent,
7806                    "sigma {sigma:e} reduced a {extent}-texel axis by {scale}, which \
7807                     is more than the axis has"
7808                );
7809            }
7810        }
7811
7812        // A sigma that is not a length reduces nothing, on the same terms as
7813        // `with_blur_xy` refusing it and `Morphology::applied_radius` refusing a
7814        // non-finite radius.
7815        for sigma in [f32::INFINITY, f32::NAN, -1.0, 0.0] {
7816            assert_eq!(
7817                Canvas::blur_downsample(sigma, u32::MAX),
7818                1,
7819                "a sigma of {sigma} asked for a reduction"
7820            );
7821        }
7822
7823        // And a real one still reduces, so the guard above did not turn the
7824        // reduction off for everything.
7825        assert!(
7826            Canvas::blur_downsample(500.0, 4096) > 1,
7827            "a wide blur on a large target stopped reducing, which is what the tap \
7828             budget exists to avoid"
7829        );
7830    }
7831
7832    /// Which route a rounded rectangle took is read off what it recorded:
7833    /// the field is one quad, the tessellated outline is many vertices.
7834    fn draw_rounded(canvas: &mut Canvas, paint: &Paint) {
7835        canvas
7836            .draw_rrect(Rect::new(10.3, 12.7, 90.1, 70.6), 12.0, paint)
7837            .expect("a rounded rectangle");
7838    }
7839
7840    /// A canvas whose pass is already multisampled: a background, and a fill
7841    /// `draw_rect` tessellates with antialiasing, placed off the pixel grid.
7842    fn multisampled() -> Canvas {
7843        let mut canvas = canvas();
7844        canvas.clear(Color::BLACK);
7845        canvas
7846            .draw_rect(
7847                Rect::new(100.5, 100.5, 120.5, 120.5),
7848                &Paint::fill(Color::WHITE),
7849            )
7850            .expect("a rectangle");
7851        canvas
7852    }
7853
7854    fn root_pass(canvas: Canvas) -> (u32, usize) {
7855        let recording = canvas.finish();
7856        let pass = recording.passes.last().expect("a root pass");
7857        (pass.descriptor.samples, pass.batch.vertices().len())
7858    }
7859
7860    /// A fill is tessellated once the pass is multisampled, and takes the field
7861    /// before that. See `draw_rrect` for the measurement.
7862    #[test]
7863    fn a_rounded_fill_is_tessellated_once_the_pass_is_multisampled() {
7864        let paint = Paint::fill(Color::WHITE);
7865        let (_, rectangle) = root_pass(multisampled());
7866
7867        let mut after = multisampled();
7868        draw_rounded(&mut after, &paint);
7869        let (samples, vertices) = root_pass(after);
7870        assert_eq!(samples, 4);
7871        assert!(
7872            vertices - rectangle > 4,
7873            "tessellated, so more than a quad: {}",
7874            vertices - rectangle
7875        );
7876
7877        // Nothing has multisampled the pass, so the field keeps it at one
7878        // sample, background or not.
7879        let mut first = canvas();
7880        first.clear(Color::BLACK);
7881        draw_rounded(&mut first, &paint);
7882        assert_eq!(root_pass(first), (1, 4));
7883        let mut over_the_surface = canvas();
7884        draw_rounded(&mut over_the_surface, &paint);
7885        assert_eq!(root_pass(over_the_surface), (1, 4));
7886    }
7887
7888    /// A stroke keeps the field in a pass that is already multisampled.
7889    #[test]
7890    fn a_rounded_stroke_keeps_the_field_in_a_multisampled_pass() {
7891        let (_, rectangle) = root_pass(multisampled());
7892        let mut canvas = multisampled();
7893        draw_rounded(&mut canvas, &Paint::stroke(Color::WHITE, 3.0));
7894        let (samples, vertices) = root_pass(canvas);
7895        assert_eq!(samples, 4);
7896        assert_eq!(vertices - rectangle, 4, "one quad from the field");
7897    }
7898}