emblema_core/paint.rs
1//! How a shape is drawn.
2
3use std::borrow::Cow;
4
5use crate::canvas::{Morphology, Rect};
6use crate::color::Color;
7use emblema_geometry::dash::Dash;
8use emblema_geometry::stroke::StrokeStyle;
9use emblema_geometry::transform::{transformed_bounds, unbounded, Transform2D};
10use emblema_hal::{BlendMode, Extent2D, TileMode};
11use emblema_hal::{ColorFilter, Sampling};
12use glam::Vec2;
13
14/// A color stop in a gradient.
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct GradientStop {
17 pub color: Color,
18 /// Position along the gradient, from zero to one.
19 pub offset: f32,
20}
21
22impl GradientStop {
23 pub fn new(color: Color, offset: f32) -> Self {
24 Self { color, offset }
25 }
26}
27
28/// What fills a shape.
29#[derive(Debug, Clone, PartialEq)]
30pub enum Shader {
31 Solid(Color),
32 /// A gradient along the line between two points **in user space**.
33 ///
34 /// The endpoints travel through the canvas transform with the geometry, so
35 /// a gradient rotates and scales with the shape it fills rather than
36 /// staying pinned to the screen.
37 LinearGradient {
38 start: Vec2,
39 end: Vec2,
40 stops: Vec<GradientStop>,
41 /// What fills the shape beyond the two endpoints.
42 ///
43 /// A gradient is defined by two points and a shape is rarely exactly
44 /// that long, so this is not an edge case: clamping holds the end
45 /// colors, repeating tiles the ramp, and decal leaves the outside
46 /// empty. Set with [`Paint::with_tile_mode`], the same call an image
47 /// uses.
48 tile: TileMode,
49 },
50 /// A gradient outward from a center **in user space**, reaching its last
51 /// stop at `radius`.
52 RadialGradient {
53 center: Vec2,
54 radius: f32,
55 stops: Vec<GradientStop>,
56 /// What fills the shape beyond `radius`. See [`Shader::LinearGradient`].
57 tile: TileMode,
58 },
59 /// A texture, mapped onto a rectangle **in user space**.
60 ///
61 /// The rectangle travels through the canvas transform with the geometry, so
62 /// an image rotates and scales with the shape it fills. It is the region
63 /// the image covers, not the region drawn: filling a circle with this paint
64 /// draws a circular piece of the image.
65 ///
66 /// `slot` indexes the table supplied when the recording is drawn. The
67 /// canvas names a slot rather than holding a texture because it records
68 /// without touching a device, and a backend texture is not something it can
69 /// name. Assigning slots is the caller's business for now; a registry that
70 /// did it for them is a separate piece of design.
71 Image {
72 slot: u32,
73 rect: Rect,
74 /// Scales the sampled color, for drawing an image translucently.
75 alpha: f32,
76 /// What happens outside the image, across and then down: an image
77 /// can repeat along x and clamp along y, as dart:ui's `ImageShader`
78 /// and Impeller's tiled texture contents take them. Set both with
79 /// [`Paint::with_tile_mode`], or each with [`Paint::with_tile_modes`].
80 tile: [TileMode; 2],
81 /// Which part of the image to draw, from zero to one in each axis.
82 ///
83 /// The whole image by default. Set it with [`Paint::with_source`], or
84 /// with [`Paint::with_source_pixels`] if you would rather state it in
85 /// texels and hand over the size you uploaded.
86 source: Rect,
87 /// Multiplies the sampled color. White changes nothing.
88 tint: Color,
89 /// How to read between texels. See [`Paint::with_sampling`].
90 sampling: Sampling,
91 },
92 /// A gradient around a center **in user space**, running between two angles
93 /// in radians, measured counter-clockwise from the positive X axis.
94 SweepGradient {
95 center: Vec2,
96 start_angle: f32,
97 end_angle: f32,
98 stops: Vec<GradientStop>,
99 /// What fills the directions the arc does not cover.
100 ///
101 /// A sweep of a full turn covers every direction and this changes
102 /// nothing; it is a partial sweep that has an outside.
103 tile: TileMode,
104 },
105 /// A caller's own fragment program.
106 ///
107 /// The one shader here this renderer did not write. `program` names one
108 /// registered with a context, and `uniforms` are the floats it reads --
109 /// laid out as the program's own declaration expects, which is a contract
110 /// between the caller's shader and the caller's code and not something
111 /// this renderer can check.
112 ///
113 /// At most [`RUNTIME_FLOATS`] of them; the rest are dropped rather than
114 /// overflowing into a block that has no room for them.
115 ///
116 /// [`RUNTIME_FLOATS`]: emblema_hal::RUNTIME_FLOATS
117 RuntimeEffect {
118 program: u32,
119 uniforms: Vec<f32>,
120 /// A texture slot the program may sample, if it declares one.
121 ///
122 /// The same table an image paint names, so a caller supplies them in
123 /// the same array beside the recording, in the order the program
124 /// declares its bindings.
125 ///
126 /// A binding the program declares and this leaves empty reads a
127 /// one-pixel opaque white texture -- what a solid fill binds, and what
128 /// keeps a pipeline's declared binding satisfied. Beyond
129 /// [`MAX_EFFECT_TEXTURES`] a caller is asking for a second descriptor
130 /// set layout, which would be one layout per program; the ceiling is
131 /// what buys a single shared one.
132 ///
133 /// [`MAX_EFFECT_TEXTURES`]: emblema_hal::MAX_EFFECT_TEXTURES
134 images: Vec<u32>,
135 },
136 /// A gradient between two circles **in user space**, reaching its first
137 /// stop on the first circle and its last on the second.
138 ///
139 /// This is the general form: a radial gradient is the case where the first
140 /// circle is a point at the second's center, and the two-point form is what
141 /// `dart:ui` reaches by giving `Gradient.radial` a focal point. It is kept
142 /// separate from [`Shader::RadialGradient`] rather than replacing it,
143 /// because the radial case folds its radius into a matrix and solves no
144 /// quadratic at all, and paying for the general solve on every ordinary
145 /// gradient would be a poor trade on the hardware this targets.
146 ///
147 /// Where no circle in the family passes through a point, nothing is drawn
148 /// there -- which is most of the plane when one circle is far outside the
149 /// other. That is a property of the two circles rather than of the tile
150 /// mode, which acts only where the parameter exists.
151 ConicalGradient {
152 start_center: Vec2,
153 start_radius: f32,
154 end_center: Vec2,
155 end_radius: f32,
156 stops: Vec<GradientStop>,
157 /// What fills the parameter outside the two circles. See
158 /// [`Shader::LinearGradient`].
159 tile: TileMode,
160 },
161}
162
163impl Shader {
164 /// How many color stops this paint carries, or zero where it carries none.
165 ///
166 /// Public because the threshold is: at or below [`MAX_STOPS`] a gradient
167 /// costs nothing beyond its material, and above it the recorder bakes a
168 /// small texture. Neither is visible in the result, so this exists for a
169 /// caller who cares about the cost rather than the picture.
170 ///
171 /// [`MAX_STOPS`]: emblema_hal::MAX_STOPS
172 pub fn stop_count(&self) -> usize {
173 match self {
174 Self::Solid(_) | Self::Image { .. } | Self::RuntimeEffect { .. } => 0,
175 Self::LinearGradient { stops, .. }
176 | Self::RadialGradient { stops, .. }
177 | Self::SweepGradient { stops, .. }
178 | Self::ConicalGradient { stops, .. } => stops.len(),
179 }
180 }
181
182 /// Whether this would draw anything at all.
183 pub fn is_visible(&self) -> bool {
184 match self {
185 Self::Solid(color) => !color.is_invisible(),
186 // What a caller's program draws is not knowable from here.
187 Self::RuntimeEffect { .. } => true,
188 Self::LinearGradient { stops, .. }
189 | Self::RadialGradient { stops, .. }
190 | Self::SweepGradient { stops, .. }
191 | Self::ConicalGradient { stops, .. } => stops.iter().any(|s| !s.color.is_invisible()),
192 // What the texture holds is unknown here, so only a zero alpha or
193 // an empty destination makes an image provably invisible.
194 Self::Image { alpha, rect, .. } => *alpha > 0.0 && !rect.is_empty(),
195 }
196 }
197
198 /// This shader with what it produces multiplied by `opacity`, which
199 /// [`Paint::opacity`] says is between zero and one.
200 ///
201 /// Folded into the colors the shader is stated in, which is exact: a
202 /// gradient interpolates straight color and premultiplies after, so a
203 /// stop's alpha scaled is the result's scaled; an image's alpha already
204 /// scales what it samples. A runtime effect is returned as it is: its
205 /// program writes the color, and upstream's `RuntimeEffectContents` does
206 /// not apply the factor either.
207 pub fn at_opacity(&self, opacity: f32) -> Shader {
208 let mut out = self.clone();
209 let scale = |c: &mut Color| *c = c.with_alpha(c.a * opacity);
210 match &mut out {
211 Self::Solid(color) => scale(color),
212 Self::Image { alpha, .. } => *alpha *= opacity,
213 Self::LinearGradient { stops, .. }
214 | Self::RadialGradient { stops, .. }
215 | Self::SweepGradient { stops, .. }
216 | Self::ConicalGradient { stops, .. } => {
217 stops.iter_mut().for_each(|s| scale(&mut s.color));
218 }
219 Self::RuntimeEffect { .. } => {}
220 }
221 out
222 }
223}
224
225/// Which part of a blurred shape survives.
226///
227/// A mask blur produces two things a picture can be made from: the shape's own
228/// coverage, and that coverage blurred. Every style here is one combination of
229/// the two, and naming them is what `dart:ui` and Skia both do -- a shadow
230/// wants the blur outside and nothing inside, a glow wants it inside, and a
231/// soft-edged solid wants the shape intact with the blur around it.
232#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
233pub enum MaskBlurStyle {
234 /// The blurred coverage, and nothing else. Soft on both sides of the edge.
235 #[default]
236 Normal,
237 /// The shape at full strength, with the blur outside it.
238 Solid,
239 /// The blur outside the shape only. What a drop shadow behind an opaque
240 /// object is: the part that would be hidden is not drawn at all.
241 Outer,
242 /// The blur inside the shape only, which is an inner shadow or a glow
243 /// confined to what it lights.
244 Inner,
245}
246
247/// A function applied to what a paint drew, rather than to the color it
248/// computed.
249///
250/// The distinction from a color filter is what the input is. A color filter
251/// sees one color at a time and cannot know its neighbors; this sees the
252/// picture, which is what a blur needs.
253///
254/// The distinction from [`Paint::mask_blur`] is what is blurred. A mask blur
255/// blurs coverage and then fills, which is only the same picture as blurring
256/// the result when the fill does not vary -- so it takes a solid color and
257/// refuses anything else. This blurs the result, which is defined for every
258/// paint and is what `dart:ui` means by an image filter. For a solid color the
259/// two agree, and there is a test that says so.
260#[derive(Debug, Clone, PartialEq, Default)]
261pub enum ImageFilter {
262 #[default]
263 None,
264 /// Blur what was drawn, by a standard deviation per axis in the space the
265 /// caller is drawing in.
266 ///
267 /// The caller's space rather than device pixels, which is what `dart:ui`
268 /// means by a sigma and what the rest of this renderer does with one: a card
269 /// lifting under a scale blurs by more as its content grows. `scaled_by`
270 /// converts it when the layer opens. This doc said "device pixels" for as
271 /// long as one path failed to convert it, which is the state
272 /// `emblema`'s `filter_space.rs` now rules out.
273 ///
274 /// Two, because `dart:ui`'s `ImageFilter.blur` takes `sigmaX` and
275 /// `sigmaY` separately and upstream's `MakeBlur` passes both through. A
276 /// blur is two separable passes here already, one along each axis, so the
277 /// second deviation costs nothing but the field: each pass uses its own,
278 /// and a pass whose deviation is zero is skipped rather than run as an
279 /// identity that would resample for no reason.
280 ///
281 /// [`Self::blur`] is the isotropic case, which is nearly every use.
282 Blur { sigma_x: f32, sigma_y: f32 },
283 /// Move what was drawn, in device pixels, by resampling it.
284 ///
285 /// Not the same as drawing under the transform, which is what the canvas's
286 /// own stack does. This draws at the size it was written and then moves
287 /// the finished image, so magnifying gives enlarged pixels where the
288 /// transform stack would give the shape redrawn larger. That difference is
289 /// the reason `dart:ui` has both, and a caller wanting the sharp one
290 /// already has `concat`.
291 Matrix { transform: Transform2D },
292 /// Spread what was drawn, taking the largest sample within these radii in
293 /// device pixels.
294 ///
295 /// `ImageFilter.dilate`. On premultiplied color and channel by channel, so
296 /// a translucent shape spreads its coverage along with its color.
297 Dilate { radius_x: f32, radius_y: f32 },
298 /// Shrink what was drawn, taking the smallest sample within these radii in
299 /// device pixels.
300 ///
301 /// `ImageFilter.erode`, and the dual of [`Self::Dilate`]: what one does to
302 /// a shape the other does to the space around it.
303 Erode { radius_x: f32, radius_y: f32 },
304 /// Recolor what was drawn, rather than what the paint computed.
305 ///
306 /// `dart:ui`'s `ColorFilter` is itself an `ImageFilter`, and upstream's
307 /// `DlImageFilter::MakeColorFilter` is the same thing. A paint carries a
308 /// color filter of its own, so the obvious question is what this adds, and
309 /// the answer is narrower than it first looks: **it can be half of a
310 /// [`Self::Compose`], and `Paint::color_filter` cannot.** Recoloring a
311 /// blurred result, or blurring a recolored one, has no other spelling here.
312 ///
313 /// On a single draw with a solid fill it is the same picture as the paint's
314 /// own filter, and a test pins that rather than leaving it to be discovered.
315 /// A paint's image filter applies per draw -- each draw gets a layer of its
316 /// own -- so there is no arrangement of two draws under one paint for the
317 /// two to disagree about. Where they would disagree is inside a
318 /// composition, which is the case this exists for.
319 Color(ColorFilter),
320 /// Run a caller's fragment program over what was drawn.
321 ///
322 /// `dart:ui`'s `ImageFilter.shader`, and upstream's
323 /// `DlImageFilter::MakeRuntimeEffect`. The program reads its input as a
324 /// texture with an identity transform -- the same guarantee upstream
325 /// re-rasterizes to provide, and one this renderer has by construction: a
326 /// filter is a pass whose target is the size of its source, covered by a
327 /// quad, so a fragment's clip position *is* its texture coordinate. A
328 /// program written for this samples exactly as the fixture programs do.
329 ///
330 /// The uniforms are the whole material block, because a program replaces
331 /// the shader that would have read it. `RUNTIME_FLOATS` is the bound and
332 /// anything past it is dropped, as it is for a runtime effect used as a
333 /// paint.
334 Runtime { program: u32, uniforms: Vec<f32> },
335 /// Filter with `inner`, then filter that result with `outer`.
336 ///
337 /// `ImageFilter.compose`, and the reason this type is not `Copy`: a filter
338 /// that holds filters cannot be a fixed size without a bound on the depth,
339 /// and `dart:ui` puts no bound on it.
340 ///
341 /// A caller can already nest [`Canvas::save_layer`] calls to the same
342 /// effect, and did before this existed. What this adds is that the bounds
343 /// come out right without being worked out by hand: the outer layer has to
344 /// be opened wide enough to hold whatever the inner one grew to, which
345 /// means knowing how far each filter in the chain reaches.
346 ///
347 /// [`Canvas::save_layer`]: crate::Canvas::save_layer
348 ///
349 /// # How deep one may go
350 ///
351 /// Two hundred and fifty-six levels, and past that the calls taking a filter
352 /// refuse it rather than crash. Everything that reads a composition walks it
353 /// recursively, and the depth that can be walked is a property of the stack
354 /// rather than of the picture -- a debug build managed two thousand and
355 /// forty-eight and died at three thousand and seventy-two. Each level also
356 /// costs a pass and a target, so the limit is far above any use.
357 ///
358 /// One thing no refusal here can cover: this is a chain of `Box`es, so
359 /// *dropping* a composition recurses as deeply as it nests. A filter built deep
360 /// enough overflows the stack being freed, in the caller's own code, before it
361 /// is handed to anything. Building one is what has to be avoided, not passing
362 /// it.
363 Compose {
364 outer: Box<ImageFilter>,
365 inner: Box<ImageFilter>,
366 },
367}
368
369/// How far a blur of the given deviations reaches, as an outset per target axis.
370///
371/// A function rather than a pair of numbers because the answer depends on which
372/// directions the blur will run along, and those come from the transform in
373/// force where the layer opened -- which `paint.rs` has no view of. See
374/// `BlurBasis` in `canvas.rs`.
375pub(crate) type BlurReach<'a> = &'a dyn Fn(Vec2) -> Vec2;
376
377impl ImageFilter {
378 /// A blur of the same deviation along both axes, which is nearly every use.
379 pub fn blur(sigma: f32) -> Self {
380 Self::Blur {
381 sigma_x: sigma,
382 sigma_y: sigma,
383 }
384 }
385
386 /// A blur with a deviation per axis, as `dart:ui`'s `ImageFilter.blur`
387 /// states one.
388 pub fn blur_xy(sigma_x: f32, sigma_y: f32) -> Self {
389 Self::Blur { sigma_x, sigma_y }
390 }
391
392 /// Whether a deviation describes a blur at all.
393 ///
394 /// Stated positively rather than as a negated comparison, which reads
395 /// badly on a type where two values can be incomparable: a sigma that is
396 /// not finite is not a blur, and neither is one that is zero or less.
397 pub(crate) fn blurs(sigma: f32) -> bool {
398 sigma.is_finite() && sigma > 0.0
399 }
400
401 /// This filter with its lengths converted from the caller's space to device
402 /// pixels.
403 ///
404 /// A caller's sigma is stated in the space they were drawing in, which is
405 /// what `dart:ui` means by it and what upstream honors by scaling with
406 /// `effect_transform.Basis()`. `Layer::scaled_by` does this for the fields a
407 /// `Copy` layer carries, and for a long time nothing did it for the filter
408 /// handed alongside them -- so the same `ImageFilter::Blur` meant a local
409 /// sigma through `Paint::with_image_filter`, which becomes a layer and is
410 /// scaled, and a device sigma through `Canvas::save_layer_filtered`, which
411 /// was not. One value in one type meaning two things depending on which call
412 /// received it, which is the defect this closes rather than a difference
413 /// between the two spellings.
414 ///
415 /// **The lengths scale and the rest does not**, which is not an oversight:
416 ///
417 /// - A blur's deviations and a morphology's radii are lengths in the
418 /// caller's space. The morphology pair used to be left out, on the reading
419 /// that its radius was device pixels here on purpose; that reading rested
420 /// on upstream having no morphology, which was wrong, and both now scale.
421 /// `Layer::scaled_by` does the same to the fields a `Copy` layer carries,
422 /// so the two spellings of a dilation agree -- including which factor each
423 /// takes. Both pairs are converted per axis, each component by the length of
424 /// its own transformed basis vector, which is what upstream takes. A
425 /// deviation took the single largest factor until `non-parity.md` 20 was
426 /// closed, and `Layer::backdrop_blur` still does because it is one number
427 /// rather than a pair.
428 /// - A matrix is not a length. It moves a finished image, and the transform
429 /// is already in the space the image is in.
430 /// - A color filter and a caller's program carry no lengths at all.
431 ///
432 /// Matched arm by arm with no wildcard, so a variant added later fails to
433 /// compile here instead of silently not being converted. That is the whole
434 /// reason this is written out rather than done with an `if let`.
435 pub(crate) fn scaled_by(self, scale: f32, axes: Vec2) -> Self {
436 if !scale.is_finite() || scale <= 0.0 {
437 return self;
438 }
439 match self {
440 Self::Blur { sigma_x, sigma_y } => Self::Blur {
441 sigma_x: sigma_x * axes.x,
442 sigma_y: sigma_y * axes.y,
443 },
444 Self::Dilate { radius_x, radius_y } => Self::Dilate {
445 radius_x: radius_x * axes.x,
446 radius_y: radius_y * axes.y,
447 },
448 Self::Erode { radius_x, radius_y } => Self::Erode {
449 radius_x: radius_x * axes.x,
450 radius_y: radius_y * axes.y,
451 },
452 Self::Compose { outer, inner } => Self::Compose {
453 outer: Box::new(outer.scaled_by(scale, axes)),
454 inner: Box::new(inner.scaled_by(scale, axes)),
455 },
456 Self::None | Self::Matrix { .. } | Self::Color(_) | Self::Runtime { .. } => self,
457 }
458 }
459
460 /// Whether this would change anything.
461 pub fn is_identity(&self) -> bool {
462 match self {
463 Self::None => true,
464 // Stated positively rather than as a negated comparison, which
465 // reads badly on a type where two values can be incomparable: a
466 // sigma that is not finite is not a blur, and neither is one that
467 // is zero or less.
468 Self::Blur { sigma_x, sigma_y } => !Self::blurs(*sigma_x) && !Self::blurs(*sigma_y),
469 // A matrix that changes nothing is one that costs a layer for
470 // nothing, so it is worth recognizing.
471 Self::Matrix { transform } => {
472 !transform.is_finite() || *transform == Transform2D::IDENTITY
473 }
474 // Positive is a filter, however small, and this used to round first
475 // on the reasoning that a radius of a third of a pixel names no
476 // sample the filter could take. That reasoning died with the radius
477 // becoming a length in the caller's space: a third of *what* is not
478 // known here, and a local 0.2 under a scale of ten is two device
479 // texels -- a filter this would have discarded. Whether a radius
480 // rounds to nothing is decided in `Morphology::applied_radius`,
481 // where the scale has been applied.
482 Self::Dilate { radius_x, radius_y } | Self::Erode { radius_x, radius_y } => {
483 let positive = |v: f32| v.is_finite() && v > 0.0;
484 !positive(*radius_x) && !positive(*radius_y)
485 }
486 // Composing two filters that each change nothing changes nothing,
487 // and costs two layers to say so.
488 // A color filter that recolors nothing is one, which keeps a
489 // caller who builds one from a default out of a layer they did not
490 // ask to pay for. Asked of the filter rather than compared against
491 // `ColorFilter::None`, which is what this used to do: a blend in
492 // `Dst` mode returns the destination untouched and an identity
493 // matrix recolors nothing, and both paid for a pass and a resample
494 // to arrive at what they were handed. `ColorFilter::is_identity`
495 // knows all three and is the same question.
496 Self::Color(filter) => filter.is_identity(),
497 // Never. What a caller's program does is the caller's business and
498 // nothing here can read it, so the only safe answer is that it does
499 // something -- and answering otherwise would drop the pass that
500 // runs it.
501 Self::Runtime { .. } => false,
502 Self::Compose { outer, inner } => outer.is_identity() && inner.is_identity(),
503 }
504 }
505
506 /// Filter with `inner` first and then with `outer`.
507 ///
508 /// The order `dart:ui` states, which is the order the names suggest once
509 /// you picture them nested: the inner filter is the one closer to what was
510 /// drawn. A composition where either half does nothing is the other half,
511 /// since the layer it would have taken is a copy of an image.
512 pub fn compose(outer: ImageFilter, inner: ImageFilter) -> Self {
513 if inner.is_identity() {
514 return outer;
515 }
516 if outer.is_identity() {
517 return inner;
518 }
519 Self::Compose {
520 outer: Box::new(outer),
521 inner: Box::new(inner),
522 }
523 }
524
525 /// The outermost filter that is not itself a composition, and everything
526 /// that has to run before it.
527 ///
528 /// A chain is applied innermost first, so drawing one means peeling from
529 /// the other end: open a layer for the outermost, and hand the remainder
530 /// back to be drawn inside it. The remainder is a filter in its own right,
531 /// which is what lets the caller recurse without knowing how deep it is.
532 ///
533 /// Recursive on the *outer* half, and that is the whole point. A first
534 /// version took `outer` to be a leaf and returned it directly, which is
535 /// true for anything `compose` builds left to right and false the moment a
536 /// caller composes two compositions -- `compose(compose(a, b), c)` was
537 /// refused as an unimplemented filter, having been assembled entirely out
538 /// of implemented ones.
539 /// The deepest composition this will walk.
540 ///
541 /// Every function that reads a composition walks it recursively -- `peel`,
542 /// `covering`, `is_identity`, `scaled_by` -- and the passes it turns into are
543 /// built by a recursion too. So the depth that can be serviced is a property of
544 /// the stack rather than of the picture, and a limit stated here is a refusal
545 /// where the absence of one was a fatal stack overflow.
546 ///
547 /// Measured on 2026-09-24 rather than guessed: a debug build serviced a
548 /// composition two thousand and forty-eight deep and died at three thousand and
549 /// seventy-two. A release build has smaller frames and would reach further,
550 /// which is the wrong direction to calibrate from -- a limit has to hold in the
551 /// profile that fails first, and the suite is that profile.
552 ///
553 /// Two hundred and fifty-six is far below it and far above any use. `dart:ui`
554 /// callers compose two or three filters; each level here also costs a pass and
555 /// a target, so a composition this deep is already a recording of two hundred
556 /// and sixty passes over a picture nobody can see the shape of.
557 pub(crate) const MAX_NESTING: usize = 256;
558
559 /// Whether this composition nests deeper than `limit`.
560 ///
561 /// Iterative, with its own worklist, which is the point: a recursive depth
562 /// check would overflow on exactly the input it exists to refuse. Stops as soon
563 /// as the limit is passed rather than measuring the whole tree, so a
564 /// pathological filter costs the limit and not its own size.
565 ///
566 /// A composition is a tree rather than a list -- both halves can compose -- so
567 /// the walk carries a depth per node instead of counting iterations.
568 pub(crate) fn nests_deeper_than(&self, limit: usize) -> bool {
569 let mut work = vec![(self, 0usize)];
570 while let Some((filter, depth)) = work.pop() {
571 if depth > limit {
572 return true;
573 }
574 if let Self::Compose { outer, inner } = filter {
575 work.push((outer, depth + 1));
576 work.push((inner, depth + 1));
577 }
578 }
579 false
580 }
581
582 pub(crate) fn peel(&self) -> (ImageFilter, ImageFilter) {
583 match self {
584 Self::Compose { outer, inner } => {
585 let (outermost, rest) = outer.peel();
586 (outermost, Self::compose(rest, (**inner).clone()))
587 }
588 leaf => (leaf.clone(), Self::None),
589 }
590 }
591
592 /// The region of device pixels a target must cover for this filter to run
593 /// over content occupying `min`..`max`.
594 ///
595 /// Both what goes in and what comes out, which is not the same question for
596 /// every filter and is the one that matters. A blur or a dilation only
597 /// grows, so its output contains its input and the distinction is invisible
598 /// -- the case that makes it visible is a matrix, which *moves* the image.
599 /// A composition puts the inner filter's layer inside the outer one's
600 /// target, and a layer's target is clipped to its parent's, so a target
601 /// sized only for where a matrix filter put things would crop the content
602 /// before the matrix ever ran: the inner layer draws the shape where it was
603 /// written and the composite is what moves it.
604 ///
605 /// Erosion is left alone rather than shrunk. Covering more than the result
606 /// needs costs a little memory; covering less loses drawing.
607 pub(crate) fn covering(&self, min: Vec2, max: Vec2, blur: BlurReach) -> (Vec2, Vec2) {
608 match self {
609 // A color filter changes what a pixel is and never which pixels
610 // there are, so it needs exactly the region it was given. A runtime
611 // effect is the same on the side that matters here: it may read
612 // anywhere in its input, and it writes only where the pass covers.
613 Self::None | Self::Erode { .. } | Self::Color(_) | Self::Runtime { .. } => (min, max),
614 Self::Blur { sigma_x, sigma_y } => {
615 // Per axis, which is the whole reason a filter states two: a
616 // blur along one axis alone must not widen the other, or the
617 // target holding it is bigger than the picture in it.
618 //
619 // Which axes, though, is the caller's to say. A blur runs along
620 // the directions the caller's own axes point once the transform
621 // has been applied, so the outset is the bounding box of the two
622 // reaches laid along those -- and asking here with the target's
623 // axes when the blur will run along turned ones sizes a target
624 // for one blur and fills it with another. That is not a
625 // conservative error: it is short exactly where the blur went.
626 let reach = blur(Vec2::new(*sigma_x, *sigma_y));
627 (min - reach, max + reach)
628 }
629 Self::Dilate { radius_x, radius_y } => {
630 let radius = Morphology::dilate(*radius_x, *radius_y).radius;
631 let reach = Vec2::new(radius[0], radius[1]);
632 (min - reach, max + reach)
633 }
634 Self::Matrix { transform } => {
635 // A matrix that carries the content across the vanishing line
636 // moves it further than a box can state, and this is a
637 // statement about how far a filter reaches -- so it widens to
638 // everything rather than reporting a reach that is too short.
639 let (moved_min, moved_max) =
640 transformed_bounds(*transform, min, max).unwrap_or_else(unbounded);
641 (min.min(moved_min), max.max(moved_max))
642 }
643 Self::Compose { outer, inner } => {
644 let (min, max) = inner.covering(min, max, blur);
645 outer.covering(min, max, blur)
646 }
647 }
648 }
649}
650
651/// Fill the shape, or trace its outline.
652#[derive(Debug, Clone, Copy, PartialEq, Default)]
653pub enum Style {
654 #[default]
655 Fill,
656 /// Stroke with the given width and joinery.
657 ///
658 /// The width is in the coordinate space the shape is drawn in, so it scales
659 /// with the canvas transform. A caller wanting a hairline that stays one
660 /// pixel wide under zoom divides by the current scale.
661 Stroke(StrokeStyle),
662}
663
664/// Everything about how a shape is painted.
665#[derive(Debug, Clone, PartialEq)]
666pub struct Paint {
667 pub shader: Shader,
668 pub style: Style,
669 /// Which part of the blurred shape survives. Ignored without a mask blur.
670 pub mask_blur_style: MaskBlurStyle,
671 /// A function applied to what this paint drew, after the shader and any
672 /// color filter.
673 ///
674 /// Costs a layer: what is drawn goes into a target of its own, is
675 /// filtered, and is composited back. See [`ImageFilter`] for how this
676 /// differs from a color filter and from a mask blur.
677 pub image_filter: ImageFilter,
678 /// A function applied to the color the shader produces, before blending.
679 ///
680 /// Beside the shader rather than inside it because it applies to all of
681 /// them, and after it rather than before because that is where `dart:ui`
682 /// puts a color filter and where it is useful: what is being recolored is
683 /// the result of the fill, not the inputs it was built from.
684 pub color_filter: ColorFilter,
685 /// Cut a stroke into a dash pattern before drawing it.
686 ///
687 /// On the paint rather than inside [`Style::Stroke`] for two reasons. It
688 /// keeps the geometry crate's stroke description a small copyable value,
689 /// which the tessellator wants and a pattern of arbitrary length would
690 /// end. And it says what it is: a dashed stroke is a stroke of a different
691 /// path, so this describes what happens to the path on the way in rather
692 /// than how the outline is built.
693 ///
694 /// Ignored by a fill, which has no length to measure along.
695 pub dash: Option<Dash>,
696 /// Blur the shape's coverage before filling it, in device pixels.
697 ///
698 /// What a soft shadow is made of: the same shape, softened, drawn behind
699 /// the thing casting it. Zero for none.
700 ///
701 /// `dart:ui` states this as blurring the mask and then applying the paint
702 /// through it, and that is what a shape gets. Two orders exist and they
703 /// agree only where the fill does not vary, because a blur is linear:
704 /// `blur(C·α)` is `C·blur(α)` for a constant `C` and for nothing else. A
705 /// solid color therefore takes the cheaper route and is drawn through a
706 /// blurred layer, which is that identity used; anything that varies is
707 /// drawn the way the specification says, with the fill laid across
708 /// everything the blur reaches and blurred coverage composited onto it.
709 ///
710 /// A solid fill of a convex path in the default style takes upstream's own
711 /// route instead, where no analytic shape covers it: a shadow mesh, its
712 /// falloff carried on the vertices (`docs/non-parity.md` section 7). That
713 /// approximates the Gaussian rather than being it, as upstream's does; a
714 /// concave path is blurred through the layer on both sides.
715 ///
716 /// Two things still take a solid color only, and neither is about blurring.
717 /// A glyph run tints one color by its own nature, so a gradient over one is
718 /// refused here exactly as it is when nothing is blurred. And a mesh
719 /// carries a color per vertex, which is a second thing multiplying the
720 /// coverage rather than a fill to lay down.
721 ///
722 /// The three styles that combine a blurred mask with a sharp one need the
723 /// coverage twice and are not built for a varying fill; they take a solid
724 /// color, which is every use a shadow has.
725 pub mask_blur: f32,
726 pub blend: BlendMode,
727 /// How a color carried per vertex or per sprite combines with what this
728 /// paint produced.
729 ///
730 /// `dart:ui` passes this as an argument to `drawVertices` and `drawAtlas`
731 /// rather than on the paint. It sits here instead because those are the
732 /// only two calls that can carry such a color, and an argument every other
733 /// call would have to pass and ignore is worse than a field they leave
734 /// alone. [`BlendMode::Modulate`] multiplies, which is the identity for the
735 /// white a caller who supplied no color gets.
736 ///
737 /// The paint's result is the source and the carried color the
738 /// destination, the order `dart:ui` states for both calls: so `SrcOver`
739 /// lays the paint over the color, and `Dst` keeps the color alone.
740 ///
741 /// Distinct from [`Self::blend`], which decides how the result reaches the
742 /// target. Both colors here are in the shader already, so every mode is
743 /// available to this one without an extension.
744 pub tint_blend: BlendMode,
745 /// Whether to antialias this shape's edges.
746 ///
747 /// Recorded per paint but applied per pass, because multisampling is a
748 /// property of the target rather than of a draw: a canvas that mixes the
749 /// two antialiases everything.
750 pub anti_alias: bool,
751 /// Where the shader's own space sits in the space the paint is used in:
752 /// the shader's local matrix.
753 ///
754 /// An image's rectangle, a gradient's points and radii and a sweep's
755 /// angles are stated in the shader's space, and this carries them into
756 /// the space the shape is drawn in, before the canvas transform. So a
757 /// gradient can be rotated, skewed or put in perspective independently
758 /// of the shape it fills, and an image laid down at any angle: what
759 /// `dart:ui`'s `ImageShader` and `Gradient` take as `matrix4`, and what
760 /// upstream applies as a color source's effect transform.
761 ///
762 /// Composed into the mapping each fragment is located through, so a
763 /// radial gradient under a stretch is an ellipse, as it is upstream, and
764 /// nothing about the shape changes. The identity by default. Ignored by
765 /// a solid color, which has no space, and by a runtime effect, whose
766 /// program locates itself.
767 pub shader_transform: Transform2D,
768 /// What the shader produces is multiplied by this, from zero to one: the
769 /// alpha of `dart:ui`'s paint color, which modulates whatever shader the
770 /// paint has, as upstream's opacity factor does on every color source.
771 ///
772 /// One by default. Kept apart from the shader so it survives
773 /// [`Self::with_shader`], and read through [`Self::effective_shader`], so
774 /// every route draws the same. A value outside zero to one is clamped
775 /// into it, and one that is not a number draws nothing.
776 ///
777 /// A mesh or an atlas with colors of its own is the one place the order
778 /// shows: there it fades what [`Self::tint_blend`] produced, after the
779 /// blend, as upstream's vertices and atlas contents do. Under
780 /// `Modulate` that is the same product either way.
781 pub opacity: f32,
782}
783
784impl Default for Paint {
785 fn default() -> Self {
786 Self {
787 shader: Shader::Solid(Color::BLACK),
788 style: Style::Fill,
789 image_filter: ImageFilter::None,
790 mask_blur_style: MaskBlurStyle::default(),
791 color_filter: ColorFilter::None,
792 dash: None,
793 mask_blur: 0.0,
794 blend: BlendMode::SrcOver,
795 tint_blend: BlendMode::Modulate,
796 anti_alias: true,
797 shader_transform: Transform2D::IDENTITY,
798 opacity: 1.0,
799 }
800 }
801}
802
803impl Paint {
804 /// A solid fill.
805 pub fn fill(color: Color) -> Self {
806 Self {
807 shader: Shader::Solid(color),
808 ..Default::default()
809 }
810 }
811
812 /// A fill that runs between colors along a line in user space.
813 ///
814 /// Any number of them. Up to [`MAX_STOPS`] the colors travel with the
815 /// material; beyond that the recorder tabulates them into a texture the
816 /// shader samples, which costs one small upload per distinct gradient and
817 /// is otherwise invisible. Ask [`Shader::stop_count`] if you want to know
818 /// which will happen.
819 ///
820 /// [`MAX_STOPS`]: emblema_hal::MAX_STOPS
821 pub fn linear_gradient(start: Vec2, end: Vec2, stops: Vec<GradientStop>) -> Self {
822 Self {
823 shader: Shader::LinearGradient {
824 start,
825 end,
826 stops,
827 tile: TileMode::default(),
828 },
829 ..Default::default()
830 }
831 }
832
833 /// A fill that runs outward from a center in user space.
834 ///
835 /// Any number of stops; see [`Paint::linear_gradient`].
836 pub fn radial_gradient(center: Vec2, radius: f32, stops: Vec<GradientStop>) -> Self {
837 Self {
838 shader: Shader::RadialGradient {
839 center,
840 radius,
841 stops,
842 tile: TileMode::default(),
843 },
844 ..Default::default()
845 }
846 }
847
848 /// A fill that runs around a center in user space.
849 ///
850 /// Angles are in radians from the positive X axis, increasing toward
851 /// positive Y: clockwise on screen, where Y points down, as `dart:ui` and
852 /// Skia measure them. At any number of stops; see
853 /// [`Paint::linear_gradient`].
854 pub fn sweep_gradient(
855 center: Vec2,
856 start_angle: f32,
857 end_angle: f32,
858 stops: Vec<GradientStop>,
859 ) -> Self {
860 Self {
861 shader: Shader::SweepGradient {
862 center,
863 start_angle,
864 end_angle,
865 stops,
866 tile: TileMode::default(),
867 },
868 ..Default::default()
869 }
870 }
871
872 /// A fill computed by a program the caller supplied.
873 ///
874 /// See [`Shader::RuntimeEffect`]. The program has to be registered with
875 /// the context that will draw the recording, and the index it was given is
876 /// what goes here.
877 pub fn runtime_effect(program: u32, uniforms: Vec<f32>) -> Self {
878 Self {
879 shader: Shader::RuntimeEffect {
880 program,
881 uniforms,
882 images: Vec::new(),
883 },
884 ..Default::default()
885 }
886 }
887
888 /// Give a runtime effect a texture to sample.
889 ///
890 /// Ignored by every other kind of paint, which either samples nothing or
891 /// already names what it samples. Called more than once, the slots stack up
892 /// in the order the program declares its bindings.
893 pub fn with_effect_image(mut self, slot: u32) -> Self {
894 if let Shader::RuntimeEffect { images, .. } = &mut self.shader {
895 images.push(slot);
896 }
897 self
898 }
899
900 /// Give a runtime effect every texture it samples at once.
901 ///
902 /// The order is the order the program declares its bindings, which for a
903 /// program written in WGSL is the order of the binding numbers rather than
904 /// the order of the declarations.
905 pub fn with_effect_images(mut self, slots: &[u32]) -> Self {
906 if let Shader::RuntimeEffect { images, .. } = &mut self.shader {
907 images.clear();
908 images.extend_from_slice(slots);
909 }
910 self
911 }
912
913 /// A fill that runs between two circles in user space.
914 ///
915 /// The general gradient: the first stop lands on the first circle and the
916 /// last on the second, and every stop between them on a circle
917 /// interpolated between the two. `radial_gradient` is the case where the
918 /// first circle is a point at the second's center, and is worth reaching
919 /// for when that is what you mean -- it does less work per fragment.
920 ///
921 /// Any number of stops; see [`Paint::linear_gradient`].
922 pub fn conical_gradient(
923 start_center: Vec2,
924 start_radius: f32,
925 end_center: Vec2,
926 end_radius: f32,
927 stops: Vec<GradientStop>,
928 ) -> Self {
929 Self {
930 shader: Shader::ConicalGradient {
931 start_center,
932 start_radius,
933 end_center,
934 end_radius,
935 stops,
936 tile: TileMode::default(),
937 },
938 ..Default::default()
939 }
940 }
941
942 /// How to read a texture between its texels.
943 ///
944 /// Linear by default, which is what an image drawn at any size but its own
945 /// wants. [`Sampling::Nearest`] is for the cases where blending is the
946 /// wrong answer: pixel art, and a sprite drawn at exactly its own size
947 /// where certainty that no neighbor bled in matters more than smoothness.
948 ///
949 /// Ignored by a paint with no texture.
950 pub fn with_sampling(mut self, sampling: Sampling) -> Self {
951 if let Shader::Image { sampling: at, .. } = &mut self.shader {
952 *at = sampling;
953 }
954 self
955 }
956
957 /// Keep only part of the blurred shape. See [`MaskBlurStyle`].
958 ///
959 /// Ignored unless a mask blur is set, since there is nothing to take a
960 /// part of otherwise.
961 pub fn with_mask_blur_style(mut self, style: MaskBlurStyle) -> Self {
962 self.mask_blur_style = style;
963 self
964 }
965
966 /// Filter what this paint draws, rather than the color it computes.
967 ///
968 /// Unlike a mask blur this takes any shader, because blurring a result is
969 /// defined whatever produced it. It is the more expensive of the two: a
970 /// layer is allocated, drawn into and composited back, where a mask blur
971 /// of a solid color reaches the same picture the same way but is only
972 /// offered where that equivalence holds.
973 pub fn with_image_filter(mut self, filter: ImageFilter) -> Self {
974 self.image_filter = filter;
975 self
976 }
977
978 /// Apply a function to the color this paint produces, before it blends.
979 ///
980 /// Works on any shader, which is the point: the image tint that came
981 /// before it could only recolor an image. A gradient, a shape, a run of
982 /// glyphs all take one now.
983 pub fn with_color_filter(mut self, filter: ColorFilter) -> Self {
984 self.color_filter = filter;
985 self
986 }
987
988 /// Blur the shape's coverage, for a shadow or a glow.
989 ///
990 /// Ignored unless finite and positive. Applies to a fill or a stroke alike
991 /// -- what is blurred is whatever coverage the shape produces.
992 pub fn with_mask_blur(mut self, sigma: f32) -> Self {
993 self.mask_blur = if sigma.is_finite() && sigma > 0.0 {
994 sigma
995 } else {
996 0.0
997 };
998 self
999 }
1000
1001 /// Dash this paint's stroke, or clear an existing pattern with `None`.
1002 ///
1003 /// The lengths are in the space the shape is drawn in, so a pattern scales
1004 /// with the canvas transform along with the line it cuts. A pattern that
1005 /// cannot be walked -- empty, negative, or summing to zero -- draws the
1006 /// line whole rather than drawing nothing, since an undashed line leads
1007 /// back to the pattern and an absent one leads nowhere.
1008 pub fn with_dash(mut self, dash: impl Into<Option<Dash>>) -> Self {
1009 self.dash = dash.into();
1010 self
1011 }
1012
1013 /// A stroke of the given width, with default caps and joins.
1014 /// A fill that samples an image across a rectangle in user space.
1015 ///
1016 /// `slot` indexes the table supplied when the recording is drawn, and
1017 /// `rect` is the region the image covers rather than the region drawn: the
1018 /// shape being filled decides what is painted, this decides where the image
1019 /// sits under it.
1020 pub fn image(slot: u32, rect: Rect) -> Self {
1021 Self {
1022 shader: Shader::Image {
1023 slot,
1024 rect,
1025 alpha: 1.0,
1026 tile: [TileMode::default(); 2],
1027 source: Rect::new(0.0, 0.0, 1.0, 1.0),
1028 tint: Color::WHITE,
1029 sampling: Sampling::default(),
1030 },
1031 ..Default::default()
1032 }
1033 }
1034
1035 /// Place the shader's space in the paint's. See [`Paint::shader_transform`].
1036 pub fn with_shader_transform(mut self, transform: Transform2D) -> Self {
1037 self.shader_transform = transform;
1038 self
1039 }
1040
1041 /// What happens outside the paint's own extent.
1042 ///
1043 /// Means the same thing for a gradient as for an image, which is why it is
1044 /// one call rather than two: past the end of the ramp, past the radius, or
1045 /// outside the swept arc, the color either holds, or repeats, or stops.
1046 /// Ignored by a solid paint, which has no outside.
1047 pub fn with_tile_mode(mut self, tile: TileMode) -> Self {
1048 match &mut self.shader {
1049 Shader::Image { tile: current, .. } => *current = [tile; 2],
1050 Shader::LinearGradient { tile: current, .. }
1051 | Shader::RadialGradient { tile: current, .. }
1052 | Shader::SweepGradient { tile: current, .. }
1053 | Shader::ConicalGradient { tile: current, .. } => *current = tile,
1054 // Neither has an outside a tile mode could describe: a solid has
1055 // no edge, and where a caller's program stops is the caller's
1056 // arithmetic rather than this renderer's.
1057 Shader::Solid(_) | Shader::RuntimeEffect { .. } => {}
1058 }
1059 self
1060 }
1061
1062 /// What happens outside an image, one mode across and one down.
1063 ///
1064 /// A strip that repeats along its length and stops at its ends, say, which
1065 /// one mode for both axes cannot state. dart:ui's `ImageShader` takes the
1066 /// two separately, and Impeller samples each axis by its own; this is that.
1067 ///
1068 /// Ignored by paints that are not images. A gradient has one parameter to
1069 /// fold, not two coordinates, and one mode is all it has upstream as well;
1070 /// [`Paint::with_tile_mode`] is how it is set.
1071 pub fn with_tile_modes(mut self, x: TileMode, y: TileMode) -> Self {
1072 if let Shader::Image { tile, .. } = &mut self.shader {
1073 *tile = [x, y];
1074 }
1075 self
1076 }
1077
1078 /// Draw only part of the image, in coordinates from zero to one.
1079 ///
1080 /// What a sprite sheet needs, and a nine-patch border. Normalized rather
1081 /// than in texels because a canvas records without touching a device and
1082 /// has never seen the image: it holds a slot, not a texture, and cannot ask
1083 /// how large it is. The caller who uploaded it can, which is what
1084 /// [`Paint::with_source_pixels`] is for.
1085 ///
1086 /// Ignored by paints that are not images.
1087 pub fn with_source(mut self, source: Rect) -> Self {
1088 if let Shader::Image { source: at, .. } = &mut self.shader {
1089 *at = source;
1090 }
1091 self
1092 }
1093
1094 /// The same, stated in texels of an image of the given size.
1095 ///
1096 /// A degenerate size would divide by zero, so it leaves the paint alone --
1097 /// drawing the whole image, which is what the paint already said.
1098 pub fn with_source_pixels(self, source: Rect, size: Extent2D) -> Self {
1099 if size.width == 0 || size.height == 0 {
1100 return self;
1101 }
1102 let (w, h) = (size.width as f32, size.height as f32);
1103 self.with_source(Rect::new(
1104 source.left / w,
1105 source.top / h,
1106 source.right / w,
1107 source.bottom / h,
1108 ))
1109 }
1110
1111 /// Multiply an image paint's sampled color. Ignored by other paints.
1112 ///
1113 /// What turns one monochrome icon sheet into every state a control has:
1114 /// upload the shapes once as white on transparent, and tint per draw. A
1115 /// white tint is the identity, which is what an image that never mentions
1116 /// one already carries.
1117 ///
1118 /// Composes with everything else on the paint, so a tinted sprite from a
1119 /// sheet is one call for the piece and one for the color.
1120 pub fn with_tint(mut self, tint: Color) -> Self {
1121 if let Shader::Image { tint: at, .. } = &mut self.shader {
1122 *at = tint;
1123 }
1124 self
1125 }
1126
1127 /// Multiply what the shader produces. See [`Paint::opacity`].
1128 pub fn with_opacity(mut self, opacity: f32) -> Self {
1129 self.opacity = opacity;
1130 self
1131 }
1132
1133 /// The shader as the paint draws it: [`Self::opacity`] folded in. Every
1134 /// route reads the shader through this.
1135 pub fn effective_shader(&self) -> Cow<'_, Shader> {
1136 let opacity = self.effective_opacity();
1137 if opacity == 1.0 {
1138 Cow::Borrowed(&self.shader)
1139 } else {
1140 Cow::Owned(self.shader.at_opacity(opacity))
1141 }
1142 }
1143
1144 /// [`Paint::opacity`] as it is applied: held to zero to one, and zero for
1145 /// a NaN, which has no amount of fading to stand for.
1146 pub(crate) fn effective_opacity(&self) -> f32 {
1147 if self.opacity.is_nan() {
1148 0.0
1149 } else {
1150 self.opacity.clamp(0.0, 1.0)
1151 }
1152 }
1153
1154 /// Scale an image paint's sampled color. Ignored by other paints.
1155 pub fn with_image_alpha(mut self, alpha: f32) -> Self {
1156 if let Shader::Image { alpha: current, .. } = &mut self.shader {
1157 *current = alpha;
1158 }
1159 self
1160 }
1161
1162 pub fn stroke(color: Color, width: f32) -> Self {
1163 Self {
1164 shader: Shader::Solid(color),
1165 style: Style::Stroke(StrokeStyle::new(width)),
1166 ..Default::default()
1167 }
1168 }
1169
1170 pub fn with_shader(mut self, shader: Shader) -> Self {
1171 self.shader = shader;
1172 self
1173 }
1174
1175 pub fn with_style(mut self, style: Style) -> Self {
1176 self.style = style;
1177 self
1178 }
1179
1180 pub fn with_blend(mut self, blend: BlendMode) -> Self {
1181 self.blend = blend;
1182 self
1183 }
1184
1185 /// How a per-vertex or per-sprite color combines with this paint's result.
1186 ///
1187 /// Ignored by every call that carries no such color, there being nothing to
1188 /// combine.
1189 pub fn with_tint_blend(mut self, tint_blend: BlendMode) -> Self {
1190 self.tint_blend = tint_blend;
1191 self
1192 }
1193
1194 /// Whether this paint's edges are smoothed. On by default.
1195 ///
1196 /// How that is paid for depends on the shape rather than on this flag. A
1197 /// rectangle, rounded rectangle, oval or circle is drawn from a distance
1198 /// field and antialiases itself inside its own fragment shader, costing a
1199 /// pass nothing. Anything that reaches the tessellator instead -- an
1200 /// arbitrary path, a stroke, a line, a double rounded rectangle -- has only
1201 /// triangles to work with, so its pass becomes multisampled.
1202 ///
1203 /// That second case carries a requirement worth knowing before meeting it:
1204 /// a multisampled pass must clear, so the pass it lands in needs something
1205 /// to clear to. Drawn straight onto the frame, that means the canvas needs
1206 /// a background -- see [`crate::Canvas::clear`], which is where a caller
1207 /// refused for this reason should look. Drawn inside a layer it means
1208 /// nothing to the caller, the layer's target clearing to transparent on
1209 /// its own.
1210 pub fn with_anti_alias(mut self, anti_alias: bool) -> Self {
1211 self.anti_alias = anti_alias;
1212 self
1213 }
1214
1215 /// Whether drawing with this paint would change anything.
1216 ///
1217 /// A transparent fill and a zero-width stroke both draw nothing, and
1218 /// skipping them early keeps empty geometry out of the batch rather than
1219 /// tessellating it and discovering it was empty.
1220 pub fn is_visible(&self) -> bool {
1221 if !self.effective_shader().is_visible() {
1222 return false;
1223 }
1224 match &self.style {
1225 Style::Fill => true,
1226 // `can_draw` rather than `is_visible`, and the difference is a
1227 // width of zero: a hairline, which the canvas widens to a device
1228 // pixel before any geometry is built for it.
1229 Style::Stroke(stroke) => stroke.can_draw(),
1230 }
1231 }
1232}
1233
1234#[cfg(test)]
1235mod tests {
1236 use super::*;
1237
1238 #[test]
1239 fn a_default_paint_is_an_opaque_antialiased_fill() {
1240 let paint = Paint::default();
1241 assert_eq!(paint.style, Style::Fill);
1242 assert_eq!(paint.blend, BlendMode::SrcOver);
1243 assert!(paint.anti_alias);
1244 assert!(paint.is_visible());
1245 }
1246
1247 #[test]
1248 fn a_transparent_paint_draws_nothing_whatever_its_style() {
1249 let clear = Color::WHITE.with_alpha(0.0);
1250 assert!(!Paint::fill(clear).is_visible());
1251 assert!(!Paint::stroke(clear, 4.0).is_visible());
1252
1253 // A gradient every stop of which is transparent draws nothing either.
1254 let invisible = Paint::linear_gradient(
1255 Vec2::ZERO,
1256 Vec2::new(1.0, 0.0),
1257 vec![GradientStop::new(clear, 0.0), GradientStop::new(clear, 1.0)],
1258 );
1259 assert!(!invisible.is_visible());
1260 }
1261
1262 #[test]
1263 fn a_zero_width_stroke_draws_nothing() {
1264 // Animating a width to zero should stop drawing rather than emit
1265 // degenerate geometry for the tessellator to discard.
1266 // A width of zero is a hairline rather than nothing, so the paint is
1267 // visible; a negative one still is not a stroke.
1268 assert!(Paint::stroke(Color::BLACK, 0.0).is_visible());
1269 assert!(!Paint::stroke(Color::BLACK, -1.0).is_visible());
1270 assert!(Paint::stroke(Color::BLACK, 0.5).is_visible());
1271 }
1272
1273 #[test]
1274 fn an_image_takes_a_tile_mode_per_axis_and_a_gradient_one() {
1275 let tile_of = |paint: &Paint| match paint.shader {
1276 Shader::Image { tile, .. } => tile,
1277 _ => unreachable!("an image paint"),
1278 };
1279 let rect = Rect::new(0.0, 0.0, 1.0, 1.0);
1280 assert_eq!(tile_of(&Paint::image(0, rect)), [TileMode::Clamp; 2]);
1281 let one = Paint::image(0, rect).with_tile_mode(TileMode::Mirror);
1282 assert_eq!(tile_of(&one), [TileMode::Mirror; 2]);
1283 let each = Paint::image(0, rect).with_tile_modes(TileMode::Repeat, TileMode::Decal);
1284 assert_eq!(tile_of(&each), [TileMode::Repeat, TileMode::Decal]);
1285
1286 // A gradient has one mode, and the per-axis call leaves it alone.
1287 let ramp = Paint::linear_gradient(
1288 Vec2::ZERO,
1289 Vec2::new(1.0, 0.0),
1290 vec![
1291 GradientStop::new(Color::BLACK, 0.0),
1292 GradientStop::new(Color::WHITE, 1.0),
1293 ],
1294 )
1295 .with_tile_modes(TileMode::Repeat, TileMode::Decal);
1296 assert!(matches!(
1297 ramp.shader,
1298 Shader::LinearGradient {
1299 tile: TileMode::Clamp,
1300 ..
1301 }
1302 ));
1303 }
1304}