Skip to main content

valo_dl/
paint.rs

1use std::sync::Arc;
2
3use valo_geometry::{Color, Matrix, Point, Rect, Stroke};
4
5use crate::{Bounds, Sampling, TileMode};
6
7/// `BlendMode` controls how source pixels combine with destination pixels.
8///
9/// [`BlendMode::SrcOver`] is the default. Advanced modes that read destination
10/// pixels may require an additional render-pass break and snapshot.
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
12#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
13pub enum BlendMode {
14    Clear,
15    Src,
16    Dst,
17    #[default]
18    SrcOver,
19    DstOver,
20    SrcIn,
21    DstIn,
22    SrcOut,
23    DstOut,
24    SrcAtop,
25    DstAtop,
26    Xor,
27    /// `Plus` adds source and destination, clamped at one: Core Graphics'
28    /// `kCGBlendModePlusLighter` and Core Animation's `plusL` filter.
29    ///
30    /// Over premultiplied colour it is `R = min(1, S + D)`, alpha included
31    /// (`CGContext.h`); Core Image's `_plusLighter` kernel is `src + dst`, so
32    /// the clamp is the target's own and a float target keeps the sum, as
33    /// the blend unit does here.
34    Plus,
35    Modulate,
36    Screen,
37    // Destination-reading advanced modes require a target snapshot.
38    Overlay,
39    Darken,
40    Lighten,
41    ColorDodge,
42    ColorBurn,
43    HardLight,
44    SoftLight,
45    Difference,
46    Exclusion,
47    Multiply,
48    Hue,
49    Saturation,
50    Color,
51    Luminosity,
52    /// `PlusDarker` adds source and destination toward black: Core
53    /// Graphics' `kCGBlendModePlusDarker`, Core Animation's `plusD` filter
54    /// and Core Image's `CIPlusDarkerCompositing`. It is not one of
55    /// Flutter's modes.
56    ///
57    /// Over premultiplied colour it is Core Image's `_plusDarker` kernel, as
58    /// CoreImage ships it in macOS 27: `Ra = min(1, Sa + Da)` and
59    /// `Rc = Ra − min(1, (Sa − Sc) + (Da − Dc))`, which for opaque colours
60    /// is `R = max(0, 1 − ((1 − D) + (1 − S)))` (the comment in
61    /// `CGContext.h` drops the outer `1 −`; Core Graphics draws the kernel's
62    /// values). A transparent source leaves the destination as it is, and
63    /// over a transparent destination the source shows unchanged. It reads
64    /// the destination, so like `Overlay` it breaks the render pass.
65    PlusDarker,
66}
67
68impl BlendMode {
69    /// `is_destructive` reports whether transparent source pixels can change
70    /// destination pixels outside the source ink.
71    pub fn is_destructive(self) -> bool {
72        matches!(
73            self,
74            BlendMode::Clear
75                | BlendMode::Src
76                | BlendMode::SrcIn
77                | BlendMode::DstIn
78                | BlendMode::SrcOut
79                | BlendMode::DstOut
80                | BlendMode::DstAtop
81                | BlendMode::Xor
82                | BlendMode::Modulate
83        )
84    }
85}
86
87/// `BlurStyle` controls where blurred coverage appears relative to a shape.
88#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
89#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
90pub enum BlurStyle {
91    /// `Normal` blurs coverage inside and outside the shape.
92    #[default]
93    Normal,
94    /// `Solid` keeps a sharp interior and blurs outside.
95    Solid,
96    /// `Inner` blurs inside and leaves the exterior empty.
97    Inner,
98    /// `Outer` blurs outside and leaves the interior empty.
99    Outer,
100}
101
102/// `MaskBlur` applies a Gaussian blur to a draw's coverage mask.
103///
104/// Sigma is measured in local units and follows the draw's transform.
105#[derive(Clone, Copy, Debug, PartialEq)]
106#[cfg_attr(feature = "serde", derive(serde::Serialize))]
107pub struct MaskBlur {
108    /// `sigma` is the nonnegative Gaussian standard deviation in local units.
109    pub sigma: f32,
110    /// `style` controls which side of the original coverage remains visible.
111    pub style: BlurStyle,
112}
113
114impl MaskBlur {
115    /// `new` creates a normal mask blur.
116    pub fn new(sigma: f32) -> Self {
117        Self::styled(sigma, BlurStyle::Normal)
118    }
119
120    /// `solid` creates a blur with a sharp interior.
121    pub fn solid(sigma: f32) -> Self {
122        Self::styled(sigma, BlurStyle::Solid)
123    }
124
125    /// `inner` creates a blur visible only inside the shape.
126    pub fn inner(sigma: f32) -> Self {
127        Self::styled(sigma, BlurStyle::Inner)
128    }
129
130    /// `outer` creates a blur visible only outside the shape.
131    pub fn outer(sigma: f32) -> Self {
132        Self::styled(sigma, BlurStyle::Outer)
133    }
134
135    /// `styled` clamps sigma to keep effect bounds from shrinking.
136    fn styled(sigma: f32, style: BlurStyle) -> Self {
137        Self {
138            sigma: sigma.max(0.0),
139            style,
140        }
141    }
142}
143
144/// `ColorFilter` transforms the pixels produced by a draw or layer.
145///
146/// Color filters run before mask blur, so the blur spreads the filtered result.
147#[derive(Clone, Copy, Debug, PartialEq)]
148#[cfg_attr(feature = "serde", derive(serde::Serialize))]
149pub enum ColorFilter {
150    /// `Matrix` is a row-major 4×5 transform over straight color in 0..1.
151    ///
152    /// Each output
153    /// channel is `row · [r, g, b, a, 1]`, clamped. Skia's `SkColorMatrix`
154    /// convention.
155    ///
156    /// Flutter's `ColorFilter.matrix` hands the translation column in
157    /// unnormalized 0..255 space instead, so a Flutter matrix needs entries
158    /// 4, 9, 14 and 19 divided by 255 before it arrives here. Getting that
159    /// wrong still produces a plausible-looking image, which is why it is
160    /// called out rather than absorbed.
161    Matrix([f32; 20]),
162    /// `Blend` composites a constant source color over each produced pixel.
163    Blend(Color, BlendMode),
164    /// `LinearToSrgbGamma` encodes linear-light values with the sRGB transfer
165    /// curve.
166    ///
167    /// The curve runs on the red, green and blue values as they are stored,
168    /// on straight colour, and leaves alpha alone; no texture changes colour
169    /// space. Flutter's `ColorFilter.linearToSrgbGamma`.
170    LinearToSrgbGamma,
171    /// `SrgbToLinearGamma` decodes sRGB-encoded values to linear light, the
172    /// inverse of [`ColorFilter::LinearToSrgbGamma`].
173    ///
174    /// Decoded values stored in an 8-bit target keep little precision in the
175    /// shadows, so a decode, blur, encode chain bands in dark areas.
176    /// Flutter's `ColorFilter.srgbToLinearGamma`.
177    SrgbToLinearGamma,
178}
179
180impl ColorFilter {
181    /// `folded_into` applies this filter to one solid color on the CPU.
182    pub fn folded_into(&self, color: Color) -> Color {
183        crate::color_filter::apply(*self, color)
184    }
185
186    /// `modifies_transparent_black` reports whether this filter can create
187    /// visible output from a transparent input pixel.
188    pub fn modifies_transparent_black(&self) -> bool {
189        self.folded_into(Color::TRANSPARENT).a > 0.0
190    }
191}
192
193/// `ImageFilter` transforms a rasterized draw or layer.
194///
195/// In a composition, the inner filter runs first and feeds the outer filter.
196#[derive(Clone, Debug, PartialEq)]
197#[cfg_attr(feature = "serde", derive(serde::Serialize))]
198pub enum ImageFilter {
199    /// `Blur` applies a Gaussian blur in local x and y units.
200    Blur {
201        /// `sigma_x` is the horizontal standard deviation.
202        sigma_x: f32,
203        /// `sigma_y` is the vertical standard deviation.
204        sigma_y: f32,
205        /// `bounds` limits what the blur reads to a rectangle in local units,
206        /// placed by the transform where the filter applies, so a rotation
207        /// turns it with the content.
208        ///
209        /// Pixels outside it count as transparent, and each result is divided
210        /// by its own alpha: content near the edge stays opaque instead of
211        /// fading or taking in colour from beyond the edge, and translucent
212        /// content comes out opaque. The output is not clipped; it spreads
213        /// past the bounds as far as an unbounded blur's would, so pair it
214        /// with a clip. `None` blurs everything. Flutter's
215        /// `ImageFilter.blur(bounds:)`.
216        bounds: Option<Rect>,
217        /// `tile_mode` is how the blur reads past the edge of what it blurs:
218        /// transparent ([`TileMode::Decal`]), the edge pixels extended, or
219        /// the picture mirrored or repeated.
220        ///
221        /// `None` leaves it to where the filter is used, as dart:ui does for
222        /// an `ImageFilter.blur` without a `tileMode`: decal on a layer and
223        /// on most draws, clamp on an image draw and inside a composition,
224        /// mirror for a backdrop.
225        tile_mode: Option<TileMode>,
226    },
227    /// `Color` applies a color filter after rasterization.
228    Color(ColorFilter),
229    /// `DropShadow` composites the input over a blurred, colored copy of its alpha.
230    DropShadow {
231        /// `offset` moves the shadow in local coordinates.
232        offset: Point,
233        /// `sigma_x` is the horizontal standard deviation.
234        sigma_x: f32,
235        /// `sigma_y` is the vertical standard deviation.
236        sigma_y: f32,
237        /// `color` colors the shadow.
238        color: Color,
239    },
240    /// `Compose` applies `inner` and then `outer`.
241    Compose {
242        /// `outer` receives the filtered result of `inner`.
243        outer: Arc<ImageFilter>,
244        /// `inner` receives the original input.
245        inner: Arc<ImageFilter>,
246    },
247    /// `Runtime` shades what the input covers with a runtime effect's `shade`.
248    ///
249    /// An effect made by [`RuntimeEffect::filter`](crate::RuntimeEffect::filter)
250    /// reads the input as `source`, prepared as its
251    /// [`FilterInputs`](crate::FilterInputs) ask, at local positions. One made
252    /// by [`RuntimeEffect::shader`](crate::RuntimeEffect::shader) follows
253    /// Flutter's `ImageFilter.shader`: the input is its first image, the
254    /// input's size in pixels its first uniform, and `position` is in the
255    /// input's pixels. See [`ImageFilter::runtime`].
256    Runtime(crate::RuntimeShader),
257    /// `Matrix` draws the input moved by `matrix`, in local coordinates:
258    /// dart:ui's `ImageFilter.matrix`, Flutter's `DlMatrixImageFilter` and
259    /// Skia's `SkImageFilters::MatrixTransform`. See [`ImageFilter::matrix`].
260    Matrix {
261        /// `matrix` maps the input's local coordinates to where it shows,
262        /// taken through the transform where the filter applies, so a scale
263        /// about a point of the content stays about that point however the
264        /// content is drawn.
265        matrix: Matrix,
266        /// `sampling` is how the moved input is read: its `filter` and
267        /// `mipmap`, as dart:ui's `filterQuality` picks them. The filter
268        /// draws the input's own pixels and nothing past them, so the tile
269        /// modes go unused.
270        sampling: Sampling,
271    },
272}
273
274impl ImageFilter {
275    /// `blur` creates a Gaussian image filter with nonnegative sigmas, its
276    /// tile mode left to where it is used.
277    pub fn blur(sigma_x: f32, sigma_y: f32) -> Self {
278        Self::Blur {
279            sigma_x: sigma_x.max(0.0),
280            sigma_y: sigma_y.max(0.0),
281            bounds: None,
282            tile_mode: None,
283        }
284    }
285
286    /// `bounded_blur` creates a Gaussian image filter that reads only inside
287    /// `bounds`, a rectangle in local units.
288    ///
289    /// It is the frosted-glass blur: colour from beyond the bounds does not
290    /// bleed in at the edges. See the `bounds` field of [`ImageFilter::Blur`].
291    pub fn bounded_blur(sigma_x: f32, sigma_y: f32, bounds: Rect) -> Self {
292        Self::Blur {
293            sigma_x: sigma_x.max(0.0),
294            sigma_y: sigma_y.max(0.0),
295            bounds: Some(bounds),
296            tile_mode: None,
297        }
298    }
299
300    /// `with_tile_mode` sets a blur's tile mode, the way it reads past the
301    /// edge of what it blurs; any other filter is returned as it is. See the
302    /// `tile_mode` field of [`ImageFilter::Blur`].
303    pub fn with_tile_mode(self, tile_mode: TileMode) -> Self {
304        match self {
305            Self::Blur {
306                sigma_x,
307                sigma_y,
308                bounds,
309                ..
310            } => Self::Blur {
311                sigma_x,
312                sigma_y,
313                bounds,
314                tile_mode: Some(tile_mode),
315            },
316            other => other,
317        }
318    }
319
320    /// `color` creates an image filter from a color filter.
321    pub fn color(filter: ColorFilter) -> Self {
322        Self::Color(filter)
323    }
324
325    /// `compose` applies `inner` first and `outer` second.
326    pub fn compose(outer: ImageFilter, inner: ImageFilter) -> Self {
327        Self::Compose {
328            outer: Arc::new(outer),
329            inner: Arc::new(inner),
330        }
331    }
332
333    /// `runtime` creates a filter from a runtime effect with one draw's
334    /// inputs.
335    ///
336    /// A filter's effect reads its input as `source`. A paint shader's effect
337    /// is a filter by Flutter's convention, as `ImageFilter.shader` is: its
338    /// first uniform is a `vec2<f32>` the renderer sets to the input's size in
339    /// pixels, its first image is left unset (`EffectImage::image` is `None`)
340    /// for the renderer to bind the input, sampled as that slot's `sampling`
341    /// says, and `shade` is called at positions in the input's pixels. The
342    /// same effect can then also fill shapes, with its first image set. Each
343    /// kind refuses inputs that break its convention, as dart:ui refuses them.
344    pub fn runtime(shader: crate::RuntimeShader) -> Result<Self, crate::EffectError> {
345        match shader.effect.kind() {
346            crate::EffectKind::Filter(_) => shader.check_images_set()?,
347            crate::EffectKind::Shader => shader.check_filter_input()?,
348        }
349        Ok(Self::Runtime(shader))
350    }
351
352    /// `matrix` creates a filter that draws its input moved by `matrix`, read
353    /// as `sampling` says: dart:ui's `ImageFilter.matrix(matrix4,
354    /// filterQuality:)`.
355    ///
356    /// It is how Flutter's `Transform` with a `filterQuality` and its
357    /// magnifier draw: the content is drawn first, then its pixels are moved,
358    /// so a scale enlarges pixels rather than redrawing at the new size. An
359    /// identity matrix, or one that is not finite, leaves the input as it
360    /// is, as Flutter's `DlMatrixImageFilter::Make` makes no filter of it.
361    pub fn matrix(matrix: Matrix, sampling: Sampling) -> Self {
362        Self::Matrix { matrix, sampling }
363    }
364
365    /// `drop_shadow` creates a shadow that retains the original input.
366    pub fn drop_shadow(offset: Point, sigma_x: f32, sigma_y: f32, color: Color) -> Self {
367        Self::DropShadow {
368            offset,
369            sigma_x: sigma_x.max(0.0),
370            sigma_y: sigma_y.max(0.0),
371            color,
372        }
373    }
374
375    /// `is_nop` reports whether the filter leaves every input pixel unchanged.
376    pub fn is_nop(&self) -> bool {
377        match self {
378            Self::Blur {
379                sigma_x, sigma_y, ..
380            } => *sigma_x <= 0.0 && *sigma_y <= 0.0,
381            Self::Color(_) => false,
382            // An invisible shadow leaves the input exactly as it found it.
383            Self::DropShadow { color, .. } => color.a <= 0.0,
384            Self::Compose { outer, inner } => outer.is_nop() && inner.is_nop(),
385            Self::Runtime(_) => false,
386            Self::Matrix { matrix, .. } => {
387                *matrix == Matrix::IDENTITY || !matrix.to_mat4().is_finite()
388            }
389        }
390    }
391
392    /// `map_local_bounds` is where the filter's output may show when its
393    /// input shows within `bounds`, both in local coordinates: Flutter's
394    /// `DlImageFilter::map_local_bounds`. A blur or a shadow grows them by
395    /// how far it spreads, a matrix moves them, and a composition maps them
396    /// through its inner filter and then its outer one.
397    pub fn map_local_bounds(&self, bounds: Rect) -> Rect {
398        match self {
399            Self::Blur { .. } | Self::DropShadow { .. } => {
400                let [x, y] = self.halo();
401                Rect::from_ltrb(
402                    bounds.x - x,
403                    bounds.y - y,
404                    bounds.right() + x,
405                    bounds.bottom() + y,
406                )
407            }
408            // It shades what its input covers; its margin is what it reads.
409            // A matrix that moves nothing is no filter at all.
410            Self::Color(_) | Self::Runtime(_) => bounds,
411            Self::Matrix { .. } if self.is_nop() => bounds,
412            Self::Compose { outer, inner } => {
413                outer.map_local_bounds(inner.map_local_bounds(bounds))
414            }
415            Self::Matrix { matrix, .. } => matrix.map_rect(&bounds),
416        }
417    }
418
419    /// `map_device_bounds` is where the filter's output may show when its
420    /// input shows within `bounds`, both in device space, the filter
421    /// applying where `transform` maps its local coordinates: Flutter's
422    /// `DlImageFilter::map_device_bounds`. A matrix under a transform that
423    /// cannot be inverted may show anywhere.
424    pub fn map_device_bounds(&self, bounds: &Bounds, transform: &Matrix) -> Bounds {
425        match self {
426            Self::Blur { .. } | Self::DropShadow { .. } => {
427                bounds.expand(device_reach(self.halo(), transform))
428            }
429            Self::Color(_) | Self::Runtime(_) => *bounds,
430            Self::Matrix { .. } if self.is_nop() => *bounds,
431            Self::Compose { outer, inner } => {
432                outer.map_device_bounds(&inner.map_device_bounds(bounds, transform), transform)
433            }
434            Self::Matrix { matrix, .. } => match transform.invert() {
435                Some(inverse) => bounds.map(&transform.then(matrix).then(&inverse)),
436                None => Bounds::Unbounded,
437            },
438        }
439    }
440
441    /// `input_device_bounds` is what the filter's input has to cover for
442    /// its output to cover `output`, both in device space, the filter
443    /// applying where `transform` maps its local coordinates: Flutter's
444    /// `DlImageFilter::get_input_device_bounds`. A matrix that cannot be
445    /// inverted with the transform may need everything.
446    pub fn input_device_bounds(&self, output: &Bounds, transform: &Matrix) -> Bounds {
447        match self {
448            Self::Blur { .. } | Self::DropShadow { .. } => {
449                output.expand(device_reach(self.halo(), transform))
450            }
451            Self::Color(_) | Self::Runtime(_) => *output,
452            Self::Matrix { .. } if self.is_nop() => *output,
453            Self::Compose { outer, inner } => {
454                inner.input_device_bounds(&outer.input_device_bounds(output, transform), transform)
455            }
456            Self::Matrix { matrix, .. } => match transform.then(matrix).invert() {
457                Some(inverse) => output.map(&transform.then(&inverse)),
458                None => Bounds::Unbounded,
459            },
460        }
461    }
462
463    /// `halo` is how far a blur or a drop shadow spreads its input, in local
464    /// x and y units: three σ, and a shadow's offset; nothing for any other
465    /// filter.
466    fn halo(&self) -> [f32; 2] {
467        match self {
468            // The bounds limit what the blur reads, not how far it spreads.
469            Self::Blur {
470                sigma_x, sigma_y, ..
471            } => [(sigma_x * 3.0).ceil(), (sigma_y * 3.0).ceil()],
472            // The halo is symmetric, so a one-sided offset has to be paid on
473            // both sides — the shadow is free to land on either.
474            Self::DropShadow {
475                offset,
476                sigma_x,
477                sigma_y,
478                ..
479            } => [
480                (sigma_x * 3.0).ceil() + offset.x.abs(),
481                (sigma_y * 3.0).ceil() + offset.y.abs(),
482            ],
483            Self::Color(_) | Self::Compose { .. } | Self::Runtime(_) | Self::Matrix { .. } => {
484                [0.0; 2]
485            }
486        }
487    }
488
489    /// `modifies_transparent_black` reports whether this filter can create
490    /// visible output from a transparent input pixel.
491    pub fn modifies_transparent_black(&self) -> bool {
492        match self {
493            Self::Blur { .. } => false,
494            Self::Color(filter) => filter.modifies_transparent_black(),
495            // The shadow is the input's own alpha recoloured, so transparent
496            // input stays transparent however opaque the shadow colour is.
497            Self::DropShadow { .. } => false,
498            Self::Compose { outer, inner } => {
499                outer.modifies_transparent_black() || inner.modifies_transparent_black()
500            }
501            // Flutter's `DlRuntimeEffectImageFilter`: it shades only what its
502            // input covers.
503            Self::Runtime(_) => false,
504            // Flutter's `DlMatrixImageFilter`: transparent pixels moved stay
505            // transparent.
506            Self::Matrix { .. } => false,
507        }
508    }
509}
510
511/// `device_reach` is how far a halo of local x and y units reaches in
512/// device pixels under `transform`, on every side. The half-extent of an
513/// axis-aligned box under a linear map is the component-wise absolute matrix
514/// applied to the half-extent, so the bound holds under rotation and shear.
515fn device_reach(halo: [f32; 2], transform: &Matrix) -> f32 {
516    let [x, y] = halo;
517    if x <= 0.0 && y <= 0.0 {
518        return 0.0;
519    }
520    let [a, b, c, d, ..] = transform.to_affine();
521    let device_x = (x * a).abs() + (y * c).abs();
522    let device_y = (x * b).abs() + (y * d).abs();
523    device_x.max(device_y)
524}
525
526/// `PaintStyle` selects filled geometry or a stroked outline.
527#[derive(Clone, Debug, Default, PartialEq)]
528#[cfg_attr(feature = "serde", derive(serde::Serialize))]
529pub enum PaintStyle {
530    /// `Fill` covers the geometry's interior.
531    #[default]
532    Fill,
533    /// `Stroke` draws the geometry's outline with the supplied stroke parameters.
534    Stroke(Stroke),
535}
536
537/// `Paint` describes how a drawing operation produces and composites pixels.
538///
539/// The default is an opaque black fill using [`BlendMode::SrcOver`].
540#[derive(Clone, Debug, PartialEq)]
541#[cfg_attr(feature = "serde", derive(serde::Serialize))]
542pub struct Paint {
543    /// `color` supplies solid-draw color and the alpha for shader or image draws.
544    ///
545    /// Shader and image draws ignore its RGB channels.
546    pub color: Color,
547    /// `blend_mode` controls compositing with destination pixels.
548    pub blend_mode: BlendMode,
549    /// `shader` replaces the solid color with a per-pixel source.
550    pub shader: Option<crate::Shader>,
551    /// `mask_blur` softens the draw's coverage. A save layer's paint takes
552    /// none: the layer is recorded without it.
553    pub mask_blur: Option<MaskBlur>,
554    /// `color_filter` transforms produced colors before mask blur.
555    pub color_filter: Option<ColorFilter>,
556    /// `image_filter` transforms the rasterized draw or layer.
557    pub image_filter: Option<ImageFilter>,
558    /// `style` selects fill or stroke rendering.
559    pub style: PaintStyle,
560}
561
562impl Default for Paint {
563    fn default() -> Self {
564        Self {
565            color: Color::BLACK,
566            blend_mode: BlendMode::SrcOver,
567            shader: None,
568            mask_blur: None,
569            color_filter: None,
570            image_filter: None,
571            style: PaintStyle::Fill,
572        }
573    }
574}
575
576impl Paint {
577    /// `from_color` creates a solid-color fill paint.
578    pub fn from_color(color: Color) -> Self {
579        Self {
580            color,
581            ..Default::default()
582        }
583    }
584
585    /// `from_shader` creates a fill paint using a per-pixel shader.
586    pub fn from_shader(shader: crate::Shader) -> Self {
587        Self {
588            color: Color::WHITE,
589            shader: Some(shader),
590            ..Default::default()
591        }
592    }
593
594    /// `is_nop` reports whether this paint can produce no visible change.
595    pub fn is_nop(&self) -> bool {
596        // Width ZERO is a hairline, not an empty stroke — Skia and Impeller
597        // both draw it one device pixel wide, and the renderer's hairline
598        // floor is what realises that. Only a negative width draws nothing.
599        let empty_stroke = matches!(&self.style, PaintStyle::Stroke(s) if s.width < 0.0);
600        self.is_invisible() || empty_stroke
601    }
602
603    /// `is_invisible` reports whether what this paint composites shows
604    /// nowhere, whatever it draws: a transparent colour blended `SrcOver`
605    /// with no filter to colour it. A save layer with such a paint records
606    /// nothing inside (Flutter's `PaintResult`).
607    pub(crate) fn is_invisible(&self) -> bool {
608        self.color.a <= 0.0 && self.blend_mode == BlendMode::SrcOver && !self.reveals_transparent()
609    }
610
611    /// `takes_group_opacity` reports whether an enclosing group's opacity
612    /// can be applied to what this paint draws instead of to the group. It
613    /// needs the paint to blend `SrcOver`, and no colour or image filter,
614    /// which would take the alpha in before it filters. Flutter's display
615    /// list asks the same of every op in a group before the group's opacity
616    /// may ride its children (`UpdateCurrentOpacityCompatibility`).
617    pub(crate) fn takes_group_opacity(&self) -> bool {
618        self.blend_mode == BlendMode::SrcOver
619            && self.color_filter.is_none()
620            && self.effective_image_filter().is_none()
621    }
622
623    /// `effective_image_filter` returns the image filter when it changes pixels.
624    pub fn effective_image_filter(&self) -> Option<&ImageFilter> {
625        self.image_filter.as_ref().filter(|f| !f.is_nop())
626    }
627
628    /// `mask_padding` returns conservative local padding for the mask blur.
629    pub fn mask_padding(&self) -> f32 {
630        self.mask_blur.map_or(0.0, |blur| (blur.sigma * 3.0).ceil())
631    }
632
633    /// `effect_bounds` returns where a draw of `bounds` with this paint may
634    /// show, in local coordinates, its effects included: its mask blur's
635    /// spread, then its image filter's mapping (Flutter's
636    /// `AdjustBoundsForPaint`).
637    ///
638    /// A draw whose paint fills its clip ([`Paint::draw_fills_clip`]) is
639    /// unbounded: only its clip bounds it.
640    pub fn effect_bounds(&self, bounds: Rect) -> Bounds {
641        if self.draw_fills_clip() {
642            return Bounds::Unbounded;
643        }
644        let blurred = bounds.expand(self.mask_padding());
645        Bounds::of(match self.effective_image_filter() {
646            Some(filter) => filter.map_local_bounds(blurred),
647            None => blurred,
648        })
649    }
650
651    /// `device_effect_bounds` is where a save layer composited with this
652    /// paint shows when its content shows within `content`, device space:
653    /// the content through the image filter applying under `transform`.
654    pub(crate) fn device_effect_bounds(&self, content: &Bounds, transform: &Matrix) -> Bounds {
655        match self.effective_image_filter() {
656            Some(filter) => filter.map_device_bounds(content, transform),
657            None => *content,
658        }
659    }
660
661    /// `device_effect_input_bounds` is what a save layer composited with
662    /// this paint has to hold for its composite to cover `output`, device
663    /// space: what its image filter, applying under `transform`, reads.
664    pub(crate) fn device_effect_input_bounds(&self, output: &Bounds, transform: &Matrix) -> Bounds {
665        match self.effective_image_filter() {
666            Some(filter) => filter.input_device_bounds(output, transform),
667            None => *output,
668        }
669    }
670
671    /// `draw_fills_clip` reports whether a draw with this paint covers its
672    /// whole clip, whatever its shape: its image filter colours transparent
673    /// pixels, which then show everywhere the clip lets them, as Skia draws
674    /// it.
675    ///
676    /// A colour filter does not: it stays inside the shape it colours
677    /// (Flutter's `AdjustBoundsForPaint`). On a save layer either filter, or
678    /// a destructive blend, fills the clip instead (`Op::SaveLayer`'s
679    /// `floods_clip`).
680    pub fn draw_fills_clip(&self) -> bool {
681        self.image_filter
682            .as_ref()
683            .is_some_and(ImageFilter::modifies_transparent_black)
684    }
685
686    /// `reveals_transparent` reports whether the paint's colour or image
687    /// filter colours transparent pixels, so a transparent colour still
688    /// paints something.
689    pub(crate) fn reveals_transparent(&self) -> bool {
690        self.color_filter
691            .is_some_and(|filter| filter.modifies_transparent_black())
692            || self.draw_fills_clip()
693    }
694
695    /// `stroke_padding` returns conservative stroke expansion at unit scale.
696    pub fn stroke_padding(&self) -> f32 {
697        self.stroke_padding_at_scale(1.0)
698    }
699
700    /// `stroke_padding_at_scale` returns stroke expansion at a device scale.
701    ///
702    /// Hairlines and minified strokes retain at least one device pixel.
703    pub fn stroke_padding_at_scale(&self, scale: f32) -> f32 {
704        match &self.style {
705            PaintStyle::Fill => 0.0,
706            PaintStyle::Stroke(s) => {
707                let spike = match s.join {
708                    valo_geometry::Join::Miter => s.miter_limit.max(1.5),
709                    _ => 1.5,
710                };
711                let effective_width = s.width.max(1.0 / scale.max(1e-3));
712                effective_width * 0.5 * spike
713            }
714        }
715    }
716}
717
718#[cfg(test)]
719mod tests {
720    use super::{ColorFilter, ImageFilter, MaskBlur, Paint, PaintStyle};
721    use valo_geometry::Stroke;
722
723    #[test]
724    fn hairline_padding_stays_large_enough_when_minified() {
725        let paint = Paint {
726            style: PaintStyle::Stroke(Stroke::new(0.0)),
727            ..Paint::default()
728        };
729        let scale = 0.1;
730        let device_padding = paint.stroke_padding_at_scale(scale) * scale;
731        assert!(device_padding >= 0.5);
732    }
733
734    fn ltrb(left: f32, top: f32, right: f32, bottom: f32) -> valo_geometry::Rect {
735        valo_geometry::Rect::from_ltrb(left, top, right, bottom)
736    }
737
738    #[test]
739    fn composed_image_filters_accumulate_blur_coverage() {
740        let filter = ImageFilter::compose(
741            ImageFilter::blur(3.0, 4.0),
742            ImageFilter::compose(
743                ImageFilter::color(ColorFilter::Matrix([0.0; 20])),
744                ImageFilter::blur(2.0, 1.0),
745            ),
746        );
747        assert_eq!(
748            filter.map_local_bounds(ltrb(0.0, 0.0, 10.0, 10.0)),
749            ltrb(-15.0, -15.0, 25.0, 25.0)
750        );
751    }
752
753    #[test]
754    fn drop_shadow_bounds_cover_the_offset_on_both_sides() {
755        let filter = ImageFilter::drop_shadow(
756            valo_geometry::Point::new(4.0, -6.0),
757            2.0,
758            1.0,
759            valo_geometry::Color::BLACK,
760        );
761        assert_eq!(
762            filter.map_local_bounds(ltrb(0.0, 0.0, 10.0, 10.0)),
763            ltrb(-10.0, -9.0, 20.0, 19.0)
764        );
765    }
766
767    // A rotation reaches further than any axis length reports: `max_scale`
768    // is 1 for a pure rotation, so scalar padding would clip this shadow.
769    #[test]
770    fn device_bounds_hold_a_rotated_effect() {
771        use crate::Bounds;
772        use valo_geometry::Matrix;
773        let shadow = ImageFilter::drop_shadow(
774            valo_geometry::Point::new(10.0, 10.0),
775            0.0,
776            0.0,
777            valo_geometry::Color::BLACK,
778        );
779        let quarter_turn = Matrix::rotation(std::f32::consts::FRAC_PI_4);
780        let content = Bounds::of(ltrb(0.0, 0.0, 10.0, 10.0));
781        let reach = 14.142136;
782        let Some(mapped) = shadow.map_device_bounds(&content, &quarter_turn).rect() else {
783            panic!("a shadow of bounded content is bounded");
784        };
785        assert!(
786            (mapped.x + reach).abs() < 1e-3 && (mapped.right() - 10.0 - reach).abs() < 1e-3,
787            "a 45° rotation maps the (10, 10) halo to 14.14 on every side: {mapped:?}"
788        );
789        assert_eq!(
790            shadow.input_device_bounds(&content, &quarter_turn),
791            shadow.map_device_bounds(&content, &quarter_turn),
792            "a blur reads as far as it spreads"
793        );
794    }
795
796    #[test]
797    fn a_mask_blur_grows_a_draw_by_three_sigma() {
798        let paint = Paint {
799            mask_blur: Some(MaskBlur::new(2.0)),
800            ..Paint::default()
801        };
802        assert_eq!(paint.mask_padding(), 6.0);
803        assert_eq!(
804            paint.effect_bounds(ltrb(0.0, 0.0, 10.0, 10.0)),
805            crate::Bounds::of(ltrb(-6.0, -6.0, 16.0, 16.0))
806        );
807    }
808
809    /// Flutter's `DlMatrixImageFilter`: local bounds go through the matrix;
810    /// device bounds through the matrix taken into device space,
811    /// `ctm · matrix · ctm⁻¹`; what it reads is the output taken back,
812    /// `ctm · (ctm · matrix)⁻¹`.
813    #[test]
814    fn a_matrix_filter_moves_its_bounds() {
815        use crate::{Bounds, Sampling};
816        use valo_geometry::Matrix;
817        let scale_about_ten = Matrix::translation(10.0, 10.0)
818            .then(&Matrix::scale(2.0, 2.0))
819            .then(&Matrix::translation(-10.0, -10.0));
820        let filter = ImageFilter::matrix(scale_about_ten, Sampling::default());
821        assert_eq!(
822            filter.map_local_bounds(ltrb(0.0, 0.0, 20.0, 20.0)),
823            ltrb(-10.0, -10.0, 30.0, 30.0)
824        );
825        let ctm = Matrix::translation(100.0, 0.0).then(&Matrix::scale(3.0, 3.0));
826        let device = Bounds::of(ctm.map_rect(&ltrb(0.0, 0.0, 20.0, 20.0)));
827        assert_eq!(
828            filter.map_device_bounds(&device, &ctm),
829            Bounds::of(ctm.map_rect(&ltrb(-10.0, -10.0, 30.0, 30.0)))
830        );
831        assert_eq!(
832            filter.input_device_bounds(
833                &Bounds::of(ctm.map_rect(&ltrb(-10.0, -10.0, 30.0, 30.0))),
834                &ctm
835            ),
836            device
837        );
838        assert!(!filter.modifies_transparent_black());
839        let flat = ImageFilter::matrix(Matrix::scale(0.0, 1.0), Sampling::default());
840        assert_eq!(flat.input_device_bounds(&device, &ctm), Bounds::Unbounded);
841    }
842
843    /// `DlMatrixImageFilter::Make` makes no filter of the identity or of a
844    /// matrix that is not finite.
845    #[test]
846    fn an_identity_or_unfinite_matrix_filter_is_a_nop() {
847        use crate::Sampling;
848        use valo_geometry::Matrix;
849        let nop = |matrix| ImageFilter::matrix(matrix, Sampling::default()).is_nop();
850        assert!(nop(Matrix::IDENTITY));
851        assert!(nop(Matrix::scale(f32::NAN, 1.0)));
852        assert!(!nop(Matrix::scale(2.0, 2.0)));
853        let composed = ImageFilter::compose(
854            ImageFilter::blur(1.0, 1.0),
855            ImageFilter::matrix(Matrix::scale(f32::NAN, 1.0), Sampling::default()),
856        );
857        assert_eq!(
858            composed.map_local_bounds(ltrb(0.0, 0.0, 10.0, 10.0)),
859            ltrb(-3.0, -3.0, 13.0, 13.0),
860            "a composition takes only the side that is a filter"
861        );
862    }
863
864    /// Flutter's rule: a group's opacity rides a `SrcOver` paint with no
865    /// colour filter. valo also keeps it off an image filter, whose colour
866    /// filter would take it in first; a shader or a mask blur takes it after.
867    #[test]
868    fn only_a_source_over_paint_without_filters_takes_group_opacity() {
869        use crate::BlendMode;
870        let takes = |paint: Paint| paint.takes_group_opacity();
871        assert!(takes(Paint::default()));
872        assert!(takes(Paint {
873            mask_blur: Some(MaskBlur::new(2.0)),
874            ..Paint::default()
875        }));
876        assert!(takes(Paint::from_shader(crate::Shader::linear(
877            valo_geometry::Point::new(0.0, 0.0),
878            valo_geometry::Point::new(1.0, 0.0),
879            valo_geometry::Color::BLACK,
880            valo_geometry::Color::WHITE,
881        ))));
882        assert!(!takes(Paint {
883            blend_mode: BlendMode::Plus,
884            ..Paint::default()
885        }));
886        assert!(!takes(Paint {
887            color_filter: Some(ColorFilter::Matrix([0.0; 20])),
888            ..Paint::default()
889        }));
890        assert!(!takes(Paint {
891            image_filter: Some(ImageFilter::blur(2.0, 2.0)),
892            ..Paint::default()
893        }));
894    }
895
896    /// A draw fills its clip only for an image filter that colours
897    /// transparent pixels; a colour filter that does still makes a
898    /// transparent paint paint something.
899    #[test]
900    fn a_draw_fills_its_clip_for_an_image_filter_that_colours_transparent_pixels() {
901        use crate::BlendMode;
902        let fill_red = ColorFilter::Blend(valo_geometry::Color::rgb(1.0, 0.0, 0.0), BlendMode::Src);
903        let transparent = Paint::from_color(valo_geometry::Color::TRANSPARENT);
904        let colour_filtered = Paint {
905            color_filter: Some(fill_red),
906            ..transparent.clone()
907        };
908        let image_filtered = Paint {
909            image_filter: Some(ImageFilter::color(fill_red)),
910            ..transparent.clone()
911        };
912        assert!(transparent.is_nop());
913        assert!(!colour_filtered.draw_fills_clip() && !colour_filtered.is_nop());
914        assert!(image_filtered.draw_fills_clip() && !image_filtered.is_nop());
915        let blurred = Paint {
916            image_filter: Some(ImageFilter::blur(2.0, 2.0)),
917            ..Paint::default()
918        };
919        assert!(!blurred.draw_fills_clip());
920    }
921
922    #[test]
923    fn an_invisible_drop_shadow_is_a_nop() {
924        let filter = ImageFilter::drop_shadow(
925            valo_geometry::Point::new(4.0, 4.0),
926            2.0,
927            2.0,
928            valo_geometry::Color::TRANSPARENT,
929        );
930        assert!(filter.is_nop());
931        assert!(!filter.modifies_transparent_black());
932    }
933}