valo_dl/shader.rs
1use valo_geometry::{Color, Matrix, Point};
2
3/// `Shader` determines the color painted at each point of a drawing operation.
4///
5/// Shader coordinates begin in the draw's local coordinate space, so shaders
6/// follow the same transforms as their geometry.
7// Serialize ONLY, now that a pattern can hold an `Image`: the dump records a
8// texture's identity, and no deserializer can turn that back into a live GPU
9// handle. Same call `Path` already makes.
10#[derive(Clone, Debug, PartialEq)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize))]
12pub enum Shader {
13 /// `Linear` interpolates colors along the line from `start` to `end`.
14 Linear {
15 /// `start` is the zero-offset point in local coordinates.
16 start: Point,
17 /// `end` is the one-offset point in local coordinates.
18 end: Point,
19 /// `stops` defines the colors along the gradient.
20 stops: Vec<GradientStop>,
21 /// `spread` controls colors outside the zero-to-one span.
22 spread: SpreadMode,
23 /// `local` transforms the shader independently of the drawn geometry.
24 ///
25 /// Use [`Matrix::IDENTITY`] when no additional transform is needed.
26 local: Matrix,
27 },
28 /// `Radial` interpolates between a start circle and an end circle.
29 Radial {
30 /// `center` is the end circle's center in local coordinates.
31 center: Point,
32 /// `radius` is the end circle's radius in local coordinates.
33 radius: f32,
34 /// `stops` defines the colors along the gradient.
35 stops: Vec<GradientStop>,
36 /// `spread` controls colors outside the zero-to-one span.
37 spread: SpreadMode,
38 /// `focus` is the optional start circle.
39 ///
40 /// `None` starts at a zero-radius circle centered on `center`.
41 focus: Option<FocalCircle>,
42 /// `local` transforms the shader independently of the drawn geometry.
43 local: Matrix,
44 },
45 /// `Sweep` interpolates colors around `center`, from `start_angle` to
46 /// `end_angle`: Skia's `SkGradientShader::MakeSweep` and Flutter's
47 /// `Gradient.sweep`.
48 ///
49 /// The angle of a point is measured from +x, clockwise in Valo's y-down
50 /// coordinates, from 0 up to one full turn; it is not wrapped round to
51 /// the start angle. So the offset at a point is how far its angle lies
52 /// from `start_angle` toward `end_angle`, and points whose angle lies
53 /// outside the two take their colour from `spread`. A full turn from
54 /// zero (`0.0` to [`std::f32::consts::TAU`]) is the whole circle;
55 /// a full turn from any other start with [`SpreadMode::Repeat`] is the
56 /// whole circle rotated to begin at it, which is Canvas2D's
57 /// `createConicGradient`.
58 Sweep {
59 /// `center` is the sweep origin in local coordinates.
60 center: Point,
61 /// `start_angle` is the angle of offset zero, in radians.
62 start_angle: f32,
63 /// `end_angle` is the angle of offset one, in radians; it must be
64 /// greater than `start_angle`, as Skia and dart:ui require.
65 end_angle: f32,
66 /// `stops` defines the colors around the sweep.
67 stops: Vec<GradientStop>,
68 /// `spread` controls colors at angles outside the two.
69 spread: SpreadMode,
70 /// `local` transforms the shader independently of the drawn geometry.
71 local: Matrix,
72 },
73 /// `Image` samples an image across the drawn geometry.
74 Image {
75 /// `image` supplies the sampled pixels.
76 image: crate::Image,
77 /// `sampling` controls filtering, mipmaps, and tiling.
78 sampling: crate::Sampling,
79 /// `local` transforms the image pattern independently of the geometry.
80 local: Matrix,
81 },
82 /// `Runtime` colours each pixel with a runtime effect's `shade` function.
83 /// The effect is made by
84 /// [`RuntimeEffect::shader`](crate::RuntimeEffect::shader); see
85 /// [`Shader::runtime`].
86 Runtime(crate::RuntimeShader),
87}
88
89/// `SpreadMode` controls a gradient outside its zero-to-one span.
90#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
91#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
92pub enum SpreadMode {
93 /// `Pad` extends the nearest edge color.
94 #[default]
95 Pad,
96 /// `Repeat` repeats the gradient in the same direction.
97 Repeat,
98 /// `Reflect` repeats the gradient with alternating direction.
99 Reflect,
100 /// `Decal` paints nothing outside the span: Skia's `SkTileMode::kDecal`
101 /// and dart:ui's `TileMode.decal`. A decal gradient leaves transparent
102 /// whatever its span does not reach, however opaque its stops.
103 Decal,
104}
105
106/// `GradientStop` assigns a color to one position along a gradient.
107#[derive(Clone, Copy, Debug, PartialEq)]
108#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
109pub struct GradientStop {
110 /// `offset` is the position from zero to one.
111 ///
112 /// Supply stops in nondecreasing offset order.
113 pub offset: f32,
114 /// `color` is the straight-alpha sRGB color at this offset.
115 pub color: Color,
116}
117
118/// `FocalCircle` defines the start circle of a radial gradient.
119#[derive(Clone, Copy, Debug, PartialEq)]
120#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
121pub struct FocalCircle {
122 /// `center` is the start circle's center in local coordinates.
123 pub center: Point,
124 /// `radius` is the start circle's radius.
125 ///
126 /// Zero represents a focal point.
127 pub radius: f32,
128}
129
130impl FocalCircle {
131 /// `point` creates a zero-radius focal circle.
132 pub fn point(center: Point) -> Self {
133 Self {
134 center,
135 radius: 0.0,
136 }
137 }
138}
139
140/// `MAX_GRADIENT_STOPS` is the largest gradient stored directly in uniforms.
141///
142/// Gradients with more stops use a cached texture ramp.
143pub const MAX_GRADIENT_STOPS: usize = 8;
144
145impl Shader {
146 /// `stops` returns this gradient's stops or an empty slice for image shaders.
147 pub fn stops(&self) -> &[GradientStop] {
148 match self {
149 Shader::Linear { stops, .. }
150 | Shader::Radial { stops, .. }
151 | Shader::Sweep { stops, .. } => stops,
152 Shader::Image { .. } | Shader::Runtime(_) => &[],
153 }
154 }
155
156 /// `spread` returns how this gradient spreads past its span, or `None`
157 /// for image and runtime shaders.
158 pub fn spread(&self) -> Option<SpreadMode> {
159 match self {
160 Shader::Linear { spread, .. }
161 | Shader::Radial { spread, .. }
162 | Shader::Sweep { spread, .. } => Some(*spread),
163 Shader::Image { .. } | Shader::Runtime(_) => None,
164 }
165 }
166
167 /// `fold_color_filter` applies a color filter directly to gradient stops.
168 ///
169 /// It returns `false` for image shaders, whose colors must be filtered
170 /// during sampling.
171 pub fn fold_color_filter(&mut self, filter: &crate::ColorFilter) -> bool {
172 let stops = match self {
173 Shader::Linear { stops, .. }
174 | Shader::Radial { stops, .. }
175 | Shader::Sweep { stops, .. } => stops,
176 // A pattern's colours live in texels; the image fragment applies
177 // the filter as it samples.
178 Shader::Image { .. } | Shader::Runtime(_) => return false,
179 };
180 for stop in stops.iter_mut() {
181 stop.color = filter.folded_into(stop.color);
182 }
183 true
184 }
185
186 /// `runtime` creates a shader from a runtime paint shader effect with one
187 /// draw's inputs; a filter's effect, or an image left unset, is refused.
188 pub fn runtime(shader: crate::RuntimeShader) -> Result<Self, crate::EffectError> {
189 match shader.effect.kind() {
190 crate::EffectKind::Shader => {
191 shader.check_images_set()?;
192 Ok(Shader::Runtime(shader))
193 }
194 crate::EffectKind::Filter(_) => Err(crate::EffectError::Contract(
195 "a paint shader's effect is made by `RuntimeEffect::shader`".to_owned(),
196 )),
197 }
198 }
199
200 /// `linear` creates a two-color padded linear gradient.
201 pub fn linear(start: Point, end: Point, from: Color, to: Color) -> Self {
202 Shader::Linear {
203 start,
204 end,
205 stops: vec![
206 GradientStop {
207 offset: 0.0,
208 color: from,
209 },
210 GradientStop {
211 offset: 1.0,
212 color: to,
213 },
214 ],
215 spread: SpreadMode::Pad,
216 local: Matrix::IDENTITY,
217 }
218 }
219}