emblema_hal/material.rs
1//! What fills a shape.
2//!
3//! A material is the paint as a backend sees it: fully resolved, in clip space,
4//! and packed into the layout the shader expects. Resolving happens above,
5//! because gradient geometry has to travel through the same transform the shape
6//! did.
7
8use crate::blend::BlendMode;
9
10/// Floats in the packed representation.
11///
12/// This was 128 bytes for a long time because that is exactly what every
13/// device guarantees as push constants, and the material traveled as one.
14/// That guarantee was also a ceiling, and the material had grown to occupy it
15/// exactly -- so the mechanism was deciding what a paint could hold, which is
16/// the wrong way round. Materials travel in a uniform buffer now, and the
17/// limit that binds is `maxUniformBufferRange`, whose guaranteed minimum is
18/// sixteen kilobytes: two orders of magnitude of room rather than none.
19///
20/// The size has not changed with the mechanism, and should not change without
21/// a material that needs it. Every float here is read by a shader that
22/// branches on the kind, and floats nobody reads are bandwidth in the one
23/// place a renderer spends it per draw.
24pub const MATERIAL_FLOATS: usize = 64;
25
26/// Enforced at compile time rather than by a test, so a material that outgrew
27/// what every device guarantees could not be built at all.
28///
29/// The bound is `maxUniformBufferRange`'s guaranteed minimum. A material is
30/// nowhere near it; the assertion is here because the previous bound was
31/// reached, and the way that was noticed was this line failing to compile.
32const _: () = assert!(
33 MATERIAL_FLOATS * 4 <= 16384,
34 "a material must fit the 16 KiB of uniform buffer range every device guarantees"
35);
36
37/// The most stops a gradient carries in the material itself.
38///
39/// Four covers the overwhelming majority of real gradients, and covers them
40/// without a texture, an upload or a binding. It is not a limit on what can be
41/// drawn: beyond this the recorder tabulates the stops into a ramp and the
42/// shader samples it instead, which is what this constant used to say was
43/// waiting on the HAL learning to sample textures. It has since learned.
44pub const MAX_STOPS: usize = 4;
45
46/// Offsets into the packed layout, matching the shader's declaration.
47///
48/// Public because it is a contract between the shader and every backend, not an
49/// internal detail. Both backends copy the packed floats straight into a
50/// uniform buffer, so a member is found by its offset here rather than by a
51/// name -- and naming the offsets in one place keeps the layout from being
52/// written out again as bare indices that quietly go stale when it grows.
53pub mod layout {
54 /// Four stop colors.
55 pub const STOPS: usize = 0;
56 /// Stop positions.
57 pub const OFFSETS: usize = 16;
58 /// Endpoints, or center plus angles.
59 pub const GEOMETRY: usize = 20;
60 /// Clip space to the paint's own space: three columns of a three-by-three,
61 /// in column order, each padded to four floats.
62 ///
63 /// Twelve floats rather than nine because that is how a `mat3x3` sits in a
64 /// uniform block, and because every member here is a four-component vector
65 /// on purpose -- it is what lets both backends copy the packed material
66 /// straight in without writing padding around anything.
67 ///
68 /// The paint's origin is inside this matrix rather than beside it in
69 /// `GEOMETRY`, which is why the first two floats there are unclaimed for
70 /// every kind that carries a mapping. See `invert_to_local`.
71 pub const TO_LOCAL: usize = 24;
72 /// Stop count, material kind, and two floats whose meaning the kind
73 /// decides -- a corner radius, a stroke width, a blur's deviation, a
74 /// gradient's tile mode, a conical gradient's separation.
75 ///
76 /// A zero stop count means the colors are in a ramp texture; see
77 /// `stop_count_code`.
78 pub const PARAMS: usize = 36;
79 /// A color filter's matrix, by column.
80 pub const FILTER: usize = 40;
81 /// The constant a color filter adds.
82 pub const FILTER_OFFSET: usize = 56;
83 /// Which color filter, if any, and in which form its matrix is stated.
84 ///
85 /// The second float holds the tint blend, the third the dither, and the
86 /// last the draw's opacity; see [`DITHER`] and [`OPACITY`]. Four unrelated
87 /// things share a slot because the slot is a four-component vector whether
88 /// or not anything fills it, and a fifth vector would cost every draw
89 /// sixteen bytes to carry three unused floats.
90 pub const FILTER_PARAMS: usize = 60;
91 /// The dither amplitude, in the target's storage units, with zero meaning
92 /// no dithering.
93 ///
94 /// Written by the backend at submission rather than by the recorder,
95 /// because the target's format is what decides it and a recording is made
96 /// without one -- which is also what keeps the color policy intact. The
97 /// shader is handed a number and still knows nothing about formats.
98 ///
99 /// It once had a flag beside it, saying whether a step was one of encoded
100 /// value or of light. Upstream's rate is a single constant on encoded
101 /// values, this took it, and the flag was never written after; the float
102 /// it held is [`OPACITY`]'s.
103 pub const DITHER: usize = 62;
104 /// What the tint blend's result is scaled by, before a color filter.
105 ///
106 /// The batch's to write, as the tint blend is: a material is a paint's
107 /// color, and this is how a draw that blends a color of its own into that
108 /// one fades. One for every other draw. See `BatchDraw::opacity`.
109 pub const OPACITY: usize = 63;
110
111 /// For a runtime effect only: clip space to the draw's own space, packed as
112 /// [`TO_LOCAL`] is, in the last three vectors of the block.
113 ///
114 /// The shared vertex stage reads it, not the caller's program: it maps each
115 /// vertex's clip position back to where the draw placed it and hands that
116 /// on as the fourth varying, `local`, which is what upstream's
117 /// `FlutterFragCoord()` returns -- the geometry's own coordinates, before
118 /// the transform. A built-in material uses these floats for its color
119 /// filter, and its fragment stage ignores the varying, so one vertex stage
120 /// still serves both.
121 ///
122 /// At the end rather than the start because the caller's block begins at
123 /// offset zero, as the program declared it.
124 pub const RUNTIME_TO_LOCAL: usize = 52;
125
126 // Neither names a member of the block: the shader reads them as
127 // `filter_params.z` and `.w`, and these are where those land.
128 const _: () = assert!(DITHER == FILTER_PARAMS + 2 && OPACITY == FILTER_PARAMS + 3);
129}
130
131/// The number the shader reads for a tile mode.
132///
133/// Written once rather than at each call site: an image and a gradient must
134/// agree about what `1.0` means, and two copies of a mapping eventually do not.
135/// The stop count the shader reads, which doubles as the ramp flag.
136///
137/// Zero means the colors are in a texture rather than in this material, and
138/// the shader samples them instead of walking the stops. A sentinel rather
139/// than a flag of its own because the two are mutually exclusive by
140/// construction -- a ramp exists only when the stops outnumbered what fits, so
141/// a material with a ramp has no count worth reporting -- and because the float
142/// this frees is the one a conical gradient needs for its second center. That
143/// is the whole reason the fourth parameter slot was available to it.
144fn stop_count_code(count: usize, ramp: &Option<u32>) -> f32 {
145 match ramp {
146 Some(_) => 0.0,
147 None => count.max(1) as f32,
148 }
149}
150
151fn tile_code(tile: TileMode) -> f32 {
152 match tile {
153 TileMode::Clamp => tile::CLAMP,
154 TileMode::Repeat => tile::REPEAT,
155 TileMode::Decal => tile::DECAL,
156 TileMode::Mirror => tile::MIRROR,
157 }
158}
159
160/// Kind selector shared with the shader.
161pub mod kind {
162 pub const SOLID: f32 = 0.0;
163 pub const LINEAR: f32 = 1.0;
164 pub const RADIAL: f32 = 2.0;
165 pub const SWEEP: f32 = 3.0;
166 pub const IMAGE: f32 = 4.0;
167 pub const GLYPH: f32 = 5.0;
168 pub const BLUR: f32 = 6.0;
169 pub const ROUNDED_RECT: f32 = 7.0;
170 pub const ELLIPSE: f32 = 8.0;
171 pub const CONICAL: f32 = 9.0;
172 pub const MESH: f32 = 10.0;
173 pub const MORPHOLOGY: f32 = 11.0;
174 pub const ROUNDED_RECT_BLUR: f32 = 12.0;
175 pub const POINT_FIELD: f32 = 13.0;
176 pub const SHADOW_MESH: f32 = 14.0;
177}
178
179/// How many textures one runtime program may sample.
180///
181/// A fixed ceiling because the descriptor set layout is shared: every pipeline
182/// this renderer builds is built against one layout, so the bindings it
183/// declares are the same for a solid fill and for a caller's program. Raising
184/// this costs an image binding on every draw; removing the ceiling costs a
185/// layout per program.
186///
187/// Four covers what `dart:ui` shaders ask for in practice -- an image and a
188/// mask, an image and a gradient ramp, occasionally a third.
189pub const MAX_EFFECT_TEXTURES: usize = 4;
190
191/// How far one morphology pass reaches, in texels each way.
192///
193/// The shader's loop has to be bounded, and this is the bound. It is not a
194/// limit on the filter: a larger radius becomes more passes, since dilating
195/// twice dilates by the sum. Sixty-five samples per pixel per pass is already
196/// enough bandwidth that splitting is the cheaper answer anyway.
197pub const MORPHOLOGY_TAPS: u32 = 32;
198
199/// How many floats a runtime effect may take: 6,208 bytes, the most
200/// Flutter's shader compiler (`impellerc`) lets a fragment program declare.
201///
202/// They travel in a block of their own, the effect block, at group 1,
203/// binding 1 ([`EFFECT_BYTES`]), packed per draw at the effect's own length,
204/// so a draw that is not an effect carries none of them.
205///
206/// The first [`layout::RUNTIME_TO_LOCAL`] of them are also in the material
207/// block at binding 0, where an effect read them before the effect block
208/// existed, so an effect declaring its block there still reads what it did.
209/// The twelve floats after those are the mapping the shared vertex stage
210/// reads to hand the program its position in the draw's own space.
211pub const RUNTIME_FLOATS: usize = 1552;
212
213/// Bytes of the effect block a draw binds: [`RUNTIME_FLOATS`] of them.
214///
215/// The range every effect is bound with, whatever its own length: a program's
216/// declared block is the caller's, and a range shorter than it would leave the
217/// rest of the declaration reading outside what was bound.
218pub const EFFECT_BYTES: usize = RUNTIME_FLOATS * 4;
219
220/// The floats of an effect the material block also carries, at binding 0.
221const MATERIAL_EFFECT_FLOATS: usize = layout::RUNTIME_TO_LOCAL;
222
223const _: () = assert!(
224 MATERIAL_EFFECT_FLOATS + 12 == MATERIAL_FLOATS,
225 "an effect's floats and its mapping fill the block exactly"
226);
227
228/// How a texture is read between its texels.
229///
230/// Not two samplers. The same argument that keeps tile modes in the shader
231/// keeps this there: a sampler baked with a filter would mean one sampler per
232/// combination and a descriptor set per draw that used a different one. A
233/// linear sampler read exactly at a texel's center returns that texel and
234/// nothing else, so nearest sampling is the coordinate snapped to the nearest
235/// center before the read, which is one multiply-floor-divide and no bindings
236/// at all.
237///
238/// `dart:ui` offers four qualities. These are its first two; the other two are
239/// mipmapped and bicubic, and neither exists here to select.
240#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
241pub enum Sampling {
242 /// Blend the texels around the coordinate. The right default: an image
243 /// drawn at any size but its own is otherwise a mess of hard edges.
244 #[default]
245 Linear,
246 /// The one texel the coordinate falls in.
247 ///
248 /// What pixel art needs, and what a sprite drawn at exactly its own size
249 /// wants in order to be certain no neighbor bled in.
250 Nearest,
251 /// A bicubic reconstruction over the sixteen texels around the coordinate.
252 ///
253 /// What `dart:ui` calls `FilterQuality.high`. Sharper than linear under
254 /// magnification, because the curve through four texels along an axis has
255 /// a slope where a straight line between two has a corner, and it costs
256 /// sixteen reads per fragment to say so.
257 ///
258 /// The particular curve is Mitchell-Netravali with `B` and `C` both a
259 /// third, which is what Skia's high quality has always meant and so what a
260 /// caller porting from Flutter is expecting. It rings slightly -- the
261 /// weights go a little negative between one and two texels out -- and that
262 /// overshoot is the sharpening, not an error in it.
263 Cubic,
264 /// A linear read of the mip level that matches how far the image is being
265 /// minified, blended with the level either side of it.
266 ///
267 /// What `dart:ui` calls `FilterQuality.medium`, and the one quality that
268 /// answers minification rather than magnification. Drawn at half its size
269 /// an image read linearly skips every other texel and aliases; read from
270 /// the level built for that size, every texel of the original contributes.
271 ///
272 /// It needs a texture that was allocated with a chain, since a level that
273 /// was never made cannot be read. On a texture without one every read lands
274 /// on the image itself and this is linear -- which is a picture that is
275 /// merely worse rather than wrong, and is what a sampler does with a level
276 /// it does not have.
277 Mipmap,
278}
279
280/// The number the shader reads for a sampling mode.
281fn sampling_code(sampling: Sampling) -> f32 {
282 match sampling {
283 Sampling::Linear => sampling::LINEAR,
284 Sampling::Nearest => sampling::NEAREST,
285 Sampling::Cubic => sampling::CUBIC,
286 Sampling::Mipmap => sampling::MIPMAP,
287 }
288}
289
290/// Sampling selector shared with the shader.
291pub mod sampling {
292 pub const LINEAR: f32 = 0.0;
293 pub const NEAREST: f32 = 1.0;
294 pub const CUBIC: f32 = 2.0;
295 pub const MIPMAP: f32 = 3.0;
296}
297
298/// Tile mode selector shared with the shader.
299///
300/// emblema's own numbering, older than [`TileMode`]'s upstream discriminants
301/// and deliberately not cast from them: `DECAL` is 2 and `MIRROR` 3 here,
302/// the other way round from the enum, and only this side is visible from
303/// the shader.
304pub mod tile {
305 pub const CLAMP: f32 = 0.0;
306 pub const REPEAT: f32 = 1.0;
307 pub const DECAL: f32 = 2.0;
308 pub const MIRROR: f32 = 3.0;
309}
310
311/// What space a color filter's matrix expects its input in.
312///
313/// A `dart:ui` color matrix is defined on straight color, which is the form a
314/// person writes a saturation or a sepia matrix in. A blend against a constant
315/// color is defined on premultiplied color, which is the form the compositing
316/// rules are stated in. Both are affine, both are one matrix here, and this is
317/// which one -- because the shader works in premultiplied color and has to know
318/// whether to undo that before applying the matrix.
319#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
320pub enum ColorForm {
321 /// Premultiplied, which is what the shader already has.
322 #[default]
323 Premultiplied,
324 /// Straight, which the shader divides out first and restores after.
325 Straight,
326}
327
328/// A function applied to a material's color, after the material and before the
329/// blend.
330///
331/// Only affine functions, which is less of a restriction than it sounds: a
332/// `dart:ui` color matrix is affine by definition, and every separable
333/// Porter-Duff blend against a *constant* color is affine in the other operand.
334/// So one matrix in the shader serves both, and which blend modes are offered
335/// is decided on the processor rather than in the fragment.
336#[derive(Debug, Clone, Copy, PartialEq, Default)]
337pub enum ColorFilter {
338 #[default]
339 None,
340 /// `columns[j]` scales the input's `j`th channel, and `offset` is added.
341 ///
342 /// Stored by column rather than by row -- the transpose of how `dart:ui`
343 /// writes it -- because that is what makes the shader four multiply-adds
344 /// of vectors rather than four dot products, and because a column is a
345 /// `vec4` where a row of the five-wide form is not.
346 Matrix {
347 columns: [[f32; 4]; 4],
348 offset: [f32; 4],
349 form: ColorForm,
350 },
351 /// Blend a constant color against the material's own, in a mode a matrix
352 /// cannot state.
353 ///
354 /// `dart:ui`'s `ColorFilter.mode` takes any blend mode, and most of them
355 /// are affine in the destination once the source is fixed -- those become
356 /// a [`Self::Matrix`] and cost the shader nothing beyond the multiply it
357 /// was already doing. The advanced modes are not affine: they are
358 /// piecewise, or they exchange components between channels. This is where
359 /// they go.
360 ///
361 /// It is arithmetic against a constant rather than against the frame, so
362 /// it needs no framebuffer fetch and no extension -- unlike the same mode
363 /// set on the paint, which reaches the hardware's blending unit and is
364 /// gated on one. The shader evaluates it with the same function a mesh's
365 /// per-vertex tint uses.
366 ///
367 /// `color` is premultiplied, as [`Self::blend`] leaves it and as the
368 /// specification states its operands.
369 Blend { color: [f32; 4], mode: BlendMode },
370 /// The sRGB transfer function, one direction or the other.
371 ///
372 /// The one filter `dart:ui` offers that a matrix cannot express: the curve
373 /// is piecewise, and the piece that covers almost all of the range has an
374 /// exponent in it. Approximating it as a power of 2.2 -- which is the usual
375 /// shortcut -- is wrong by about a percent in the midtones and much more
376 /// near black, where the linear segment is doing the work, so the shader
377 /// evaluates the real thing instead.
378 ///
379 /// Applied to straight color, per channel, leaving alpha alone. Gamma on a
380 /// premultiplied channel would be encoding the alpha along with the color.
381 Gamma { direction: Gamma },
382}
383
384/// Which way through the sRGB transfer function a [`ColorFilter::Gamma`] goes.
385#[derive(Debug, Clone, Copy, PartialEq, Eq)]
386pub enum Gamma {
387 /// Linear light in, sRGB's encoding out. `ColorFilter.linearToSrgbGamma`.
388 LinearToSrgb,
389 /// sRGB's encoding in, linear light out. `ColorFilter.srgbToLinearGamma`.
390 SrgbToLinear,
391}
392
393impl ColorFilter {
394 /// A filter from a 4x5 color matrix, in `dart:ui`'s layout but not its
395 /// units.
396 ///
397 /// Row-major and five wide: four scales and a constant per output channel,
398 /// red row first, applied to straight color with each channel from zero to
399 /// one. The constants are in the same units, zero to one, as Impeller's
400 /// are. `ColorFilter.matrix` states them in 0-255, and the engine divides
401 /// that column by 255 before Impeller sees it
402 /// (`lib/ui/painting/color_filter.cc`); a caller passing `dart:ui`'s
403 /// numbers through has to do the same.
404 pub fn matrix(rows: [f32; 20]) -> Self {
405 let mut columns = [[0.0f32; 4]; 4];
406 let mut offset = [0.0f32; 4];
407 for (out, row) in rows.chunks_exact(5).enumerate() {
408 for (channel, value) in row[..4].iter().enumerate() {
409 columns[channel][out] = *value;
410 }
411 offset[out] = row[4];
412 }
413 Self::Matrix {
414 columns,
415 offset,
416 form: ColorForm::Straight,
417 }
418 }
419
420 /// Linear light encoded into sRGB, which is `ColorFilter.linearToSrgbGamma`.
421 pub fn linear_to_srgb() -> Self {
422 Self::Gamma {
423 direction: Gamma::LinearToSrgb,
424 }
425 }
426
427 /// sRGB decoded back to linear light, which is
428 /// `ColorFilter.srgbToLinearGamma`.
429 pub fn srgb_to_linear() -> Self {
430 Self::Gamma {
431 direction: Gamma::SrgbToLinear,
432 }
433 }
434
435 /// A filter that blends a constant color against the material's own.
436 ///
437 /// The material is the destination and `color` is the source, which is the
438 /// way round `dart:ui` states `ColorFilter.mode` and the way round that
439 /// makes an icon sheet tinted by `SrcIn` mean what everyone expects.
440 ///
441 /// Most modes are affine in the destination once the source is fixed, so
442 /// each becomes a matrix and the shader needs no blending arithmetic at
443 /// all. The advanced modes are not affine -- they are piecewise, or
444 /// exchange components between channels -- so those become
445 /// [`Self::Blend`] and are evaluated per fragment against the constant, by
446 /// the same function a mesh's per-vertex tint goes through.
447 ///
448 /// Every mode is therefore a filter and none of them is refused. This used
449 /// to answer a `Result` and say in its own documentation that the advanced
450 /// modes were "refused rather than approximated", which the code below has
451 /// never done. Eighteen call sites carried an `expect` that could not fire, and
452 /// several of their messages stated the opposite of what the branch they
453 /// were on does.
454 ///
455 /// `color` is straight, like every color a caller states.
456 pub fn blend(color: [f32; 4], mode: BlendMode) -> Self {
457 use BlendMode as B;
458 let alpha = color[3];
459 // Premultiplied, because the rules below are stated for premultiplied
460 // operands and the shader's own color is premultiplied too.
461 let s = [color[0] * alpha, color[1] * alpha, color[2] * alpha, alpha];
462 let zero = [[0.0f32; 4]; 4];
463 let scaled = |k: f32| {
464 let mut m = zero;
465 for (i, column) in m.iter_mut().enumerate() {
466 column[i] = k;
467 }
468 m
469 };
470 // The destination's alpha reaches every output channel through this
471 // column alone, which is what makes the modes that multiply by it --
472 // or by one minus it -- a matrix rather than a special case.
473 let with_alpha_column = |mut m: [[f32; 4]; 4], column: [f32; 4]| {
474 for (i, value) in column.iter().enumerate() {
475 m[3][i] += *value;
476 }
477 m
478 };
479 let negated = [-s[0], -s[1], -s[2], -s[3]];
480 let (columns, offset) = match mode {
481 B::Clear => (zero, [0.0; 4]),
482 B::Src => (zero, s),
483 B::Dst => (scaled(1.0), [0.0; 4]),
484 B::SrcOver => (scaled(1.0 - alpha), s),
485 B::DstOver => (with_alpha_column(scaled(1.0), negated), s),
486 B::SrcIn => (with_alpha_column(zero, s), [0.0; 4]),
487 B::DstIn => (scaled(alpha), [0.0; 4]),
488 B::SrcOut => (with_alpha_column(zero, negated), s),
489 B::DstOut => (scaled(1.0 - alpha), [0.0; 4]),
490 B::SrcATop => (with_alpha_column(scaled(1.0 - alpha), s), [0.0; 4]),
491 B::DstATop => (with_alpha_column(scaled(alpha), negated), s),
492 B::Xor => (with_alpha_column(scaled(1.0 - alpha), negated), s),
493 B::Plus => (scaled(1.0), s),
494 B::Modulate => {
495 let mut m = zero;
496 for (i, column) in m.iter_mut().enumerate() {
497 column[i] = s[i];
498 }
499 (m, [0.0; 4])
500 }
501 // Not affine, so not a matrix. Evaluated per fragment instead,
502 // against the same constant, by the same function a mesh's
503 // per-vertex tint goes through.
504 mode => return Self::Blend { color: s, mode },
505 };
506 Self::Matrix {
507 columns,
508 offset,
509 form: ColorForm::Premultiplied,
510 }
511 }
512
513 /// Whether this changes anything.
514 pub fn is_identity(&self) -> bool {
515 match self {
516 Self::None => true,
517 Self::Matrix {
518 columns,
519 offset,
520 form: _,
521 } => {
522 offset.iter().all(|v| *v == 0.0)
523 && columns.iter().enumerate().all(|(j, column)| {
524 column
525 .iter()
526 .enumerate()
527 .all(|(i, v)| *v == if i == j { 1.0 } else { 0.0 })
528 })
529 }
530 // `Dst` returns the destination untouched, which is the identity
531 // and is the only mode here that is. It cannot arrive through
532 // `blend`, which sends every affine mode to a matrix, but it can be
533 // written by hand.
534 Self::Blend { mode, .. } => *mode == BlendMode::Dst,
535 // The curve is the identity at exactly three points -- zero, one,
536 // and nowhere else on the range -- so as a function it never is.
537 Self::Gamma { .. } => false,
538 }
539 }
540
541 /// The code the shader reads to choose a path.
542 fn code(&self) -> f32 {
543 match self {
544 Self::None => filter::NONE,
545 Self::Matrix {
546 form: ColorForm::Premultiplied,
547 ..
548 } => filter::PREMULTIPLIED,
549 Self::Matrix {
550 form: ColorForm::Straight,
551 ..
552 } => filter::STRAIGHT,
553 Self::Gamma {
554 direction: Gamma::LinearToSrgb,
555 } => filter::LINEAR_TO_SRGB,
556 Self::Gamma {
557 direction: Gamma::SrgbToLinear,
558 } => filter::SRGB_TO_LINEAR,
559 Self::Blend { .. } => filter::BLEND,
560 }
561 }
562
563 pub(crate) fn pack_into(&self, out: &mut [f32; MATERIAL_FLOATS]) {
564 out[layout::FILTER_PARAMS] = self.code();
565 match self {
566 Self::Matrix {
567 columns, offset, ..
568 } => {
569 for (j, column) in columns.iter().enumerate() {
570 out[layout::FILTER + j * 4..layout::FILTER + j * 4 + 4].copy_from_slice(column);
571 }
572 out[layout::FILTER_OFFSET..layout::FILTER_OFFSET + 4].copy_from_slice(offset);
573 }
574 // The constant goes where a matrix's offset would, which is what it
575 // is: the term that does not depend on the material. The mode goes
576 // in the first float of the matrix itself, which this filter has no
577 // use for -- sixteen floats are already reserved for every draw,
578 // and spending a fifth vector to carry one number would cost every
579 // draw that does not blend.
580 Self::Blend { color, mode } => {
581 out[layout::FILTER_OFFSET..layout::FILTER_OFFSET + 4].copy_from_slice(color);
582 out[layout::FILTER] = mode.code();
583 }
584 Self::None | Self::Gamma { .. } => {}
585 }
586 }
587}
588
589/// Filter selector shared with the shader.
590pub mod filter {
591 pub const NONE: f32 = 0.0;
592 pub const PREMULTIPLIED: f32 = 1.0;
593 pub const STRAIGHT: f32 = 2.0;
594 pub const LINEAR_TO_SRGB: f32 = 3.0;
595 pub const SRGB_TO_LINEAR: f32 = 4.0;
596 /// A blend against a constant color, for the modes a matrix cannot state.
597 pub const BLEND: f32 = 5.0;
598
599 /// Whether a code names a filter that reads straight rather than
600 /// premultiplied color.
601 ///
602 /// The shader decides this by comparison rather than by equality, and gets
603 /// the same answer, so the boundary lives here where both can cite it: a
604 /// filter added above this line is straight unless it says otherwise.
605 ///
606 /// [`BLEND`] says otherwise, which is what the sentence above anticipated.
607 /// The compositing specification states every blend on premultiplied
608 /// operands and the shader's own blend function takes them that way, so
609 /// handing it straight color would be handing it the wrong numbers.
610 pub fn is_straight(code: f32) -> bool {
611 code > PREMULTIPLIED && code < BLEND
612 }
613}
614
615/// A color stop.
616#[derive(Debug, Clone, Copy, PartialEq)]
617pub struct Stop {
618 /// Linear color with straight alpha.
619 pub color: [f32; 4],
620 /// Position along the gradient, from zero to one.
621 pub offset: f32,
622}
623
624impl Stop {
625 pub fn new(color: [f32; 4], offset: f32) -> Self {
626 Self { color, offset }
627 }
628}
629
630/// Maps a clip-space offset into a gradient's own space, in column order.
631///
632/// Clip space is anisotropic whenever the target is not square, and a transform
633/// may rotate or skew as well, so a circle in user space is an ellipse there.
634/// Radial and sweep gradients measure distance and angle, both of which that
635/// distortion changes, so they map back before measuring. A linear gradient
636/// projects onto an axis, which distortion does not affect, and so does not
637/// need this.
638pub type ToLocal = [f32; 12];
639
640/// How a shape is filled.
641#[derive(Debug, Clone, PartialEq)]
642pub enum Material {
643 Solid([f32; 4]),
644 /// Color comes from the vertices, and the result is dithered.
645 ///
646 /// Shades as opaque white, so the per-vertex color under `Modulate` -- which
647 /// is the identity against white -- is the whole result. That is the
648 /// arrangement `draw_vertices` already uses for a caller's mesh; what this
649 /// adds is that it dithers, which `Solid` must not.
650 ///
651 /// It exists for a gradient the rasterizer interpolates instead of the
652 /// fragment stage evaluating. A long run of nearly equal values is what
653 /// bands on an eight-bit target whichever stage produced it, and a route
654 /// that could not say so would drop the dither silently -- which is what
655 /// §19 of `docs/non-parity.md` records killing the first attempt at it.
656 ///
657 /// Carries no data: a section's colors ride on its vertices, and the
658 /// premultiplied alpha rides with them.
659 VertexGradient,
660 /// A gradient along an axis, starting at a point **in clip space**.
661 ///
662 /// Clip space for the start, because the fragment stage locates itself from
663 /// an interpolated clip position: the alternative, the fragment coordinate
664 /// builtin, has a different origin in each graphics API and would run the
665 /// gradient in opposite directions on the two backends.
666 ///
667 /// The axis is in the gradient's own space, and `to_local` maps a clip-space
668 /// offset into it — the same pairing radial and sweep use, and for the same
669 /// reason. Clip space is anisotropic whenever the target is not square, so
670 /// projecting onto an axis *there* weights the two axes by the target's
671 /// shape: on a target twice as wide as it is tall, a diagonal gradient runs
672 /// in the wrong direction.
673 LinearGradient {
674 /// End minus start, in the gradient's own space.
675 axis: [f32; 2],
676 to_local: ToLocal,
677 stops: Vec<Stop>,
678 /// Texture slot holding this gradient's colors, when they did not fit.
679 ///
680 /// `None` is the ordinary case: the stops travel in the material and
681 /// the shader walks them. `Some` means the recorder tabulated them into
682 /// an image instead, because there were more than [`MAX_STOPS`], and
683 /// the shader reads the color at the parameter rather than computing
684 /// it. The two must agree where both are possible, which is what makes
685 /// the choice invisible to a caller.
686 ramp: Option<u32>,
687 /// What happens beyond the two endpoints.
688 ///
689 /// The parameter a gradient is sampled by runs from zero at one end to
690 /// one at the other and is defined everywhere else too, so a shape
691 /// larger than its gradient asks a question the stops do not answer.
692 /// Clamping holds the end colors, which is the usual choice; repeating
693 /// tiles the ramp, which is what a stripe pattern is; decal draws
694 /// nothing outside, the same meaning it has for an image.
695 tile: TileMode,
696 },
697 /// A gradient outward from a center, **in clip space**, where `to_local`
698 /// carries the radius: it maps the clip-space offset so that the gradient's
699 /// edge lands at unit distance.
700 RadialGradient {
701 to_local: ToLocal,
702 stops: Vec<Stop>,
703 /// Texture slot holding this gradient's colors, when they did not fit.
704 ///
705 /// `None` is the ordinary case: the stops travel in the material and
706 /// the shader walks them. `Some` means the recorder tabulated them into
707 /// an image instead, because there were more than [`MAX_STOPS`], and
708 /// the shader reads the color at the parameter rather than computing
709 /// it. The two must agree where both are possible, which is what makes
710 /// the choice invisible to a caller.
711 ramp: Option<u32>,
712 /// What happens beyond the radius. See [`Material::LinearGradient`].
713 tile: TileMode,
714 },
715 /// A gradient around a center, **in clip space**, running from `start_angle`
716 /// to `end_angle` in radians.
717 SweepGradient {
718 to_local: ToLocal,
719 start_angle: f32,
720 end_angle: f32,
721 stops: Vec<Stop>,
722 /// Texture slot holding this gradient's colors, when they did not fit.
723 ///
724 /// `None` is the ordinary case: the stops travel in the material and
725 /// the shader walks them. `Some` means the recorder tabulated them into
726 /// an image instead, because there were more than [`MAX_STOPS`], and
727 /// the shader reads the color at the parameter rather than computing
728 /// it. The two must agree where both are possible, which is what makes
729 /// the choice invisible to a caller.
730 ramp: Option<u32>,
731 /// What happens outside the swept arc.
732 ///
733 /// Unlike the other two this can be a no-op: a sweep covering the whole
734 /// turn has no outside, and every direction lands within it.
735 tile: TileMode,
736 },
737 /// A gradient between two circles, the general form the other two are
738 /// special cases of.
739 ///
740 /// `center` is the first circle's center **in clip space**, and `to_local`
741 /// maps a clip-space offset into a space where that center is the origin
742 /// and the second circle's center lies at `(separation, 0)`. Putting the
743 /// separation on an axis costs nothing -- the rotation folds into a matrix
744 /// that has to be there anyway -- and buys the second center for one float
745 /// instead of two, which is what makes this fit at all.
746 ///
747 /// The radii are in that same space and are *not* normalized, unlike the
748 /// radial gradient's, because there are two of them and a scale can only
749 /// remove one. Carrying both plainly also means the degenerate cases need
750 /// no special handling: concentric circles are `separation == 0`, and a
751 /// cone rather than a tube is `radius_delta != 0`.
752 ConicalGradient {
753 to_local: ToLocal,
754 /// Radius of the first circle.
755 start_radius: f32,
756 /// Second radius minus the first.
757 radius_delta: f32,
758 /// Distance between the two centers.
759 separation: f32,
760 stops: Vec<Stop>,
761 /// Texture slot holding this gradient's colors, when they did not fit.
762 /// See [`Material::LinearGradient`].
763 ramp: Option<u32>,
764 /// What happens where the parameter leaves the unit interval. See
765 /// [`Material::LinearGradient`].
766 tile: TileMode,
767 },
768 /// A caller's own fragment program, with the floats it reads.
769 ///
770 /// The program is named rather than carried: registering one builds a
771 /// pipeline, which is expensive and outlives any draw, so a context holds
772 /// them and a material names which. The floats travel in the effect block
773 /// at binding 1 of the material set, the first of them also in the
774 /// material block at binding 0 (see [`RUNTIME_FLOATS`]): two bindings of
775 /// one set, not a second set.
776 Runtime {
777 program: u32,
778 /// At most [`RUNTIME_FLOATS`]; any past that are dropped.
779 uniforms: Vec<f32>,
780 /// Clip space to the space the draw's geometry was placed from, as
781 /// `emblema_geometry::invert_to_local` packs it: what the vertex stage
782 /// maps each vertex by to give the program its own position. See
783 /// [`layout::RUNTIME_TO_LOCAL`].
784 to_local: ToLocal,
785 /// The textures the program may sample, in the order it declares them.
786 ///
787 /// `None` in a position means the program does not read that binding,
788 /// and the backend binds its placeholder there -- a pipeline must have
789 /// every binding it declares bound, however unreachable the branch
790 /// reading it.
791 ///
792 /// The count is fixed rather than free because the descriptor set
793 /// layout every pipeline is built against has to be one layout. Four is
794 /// what that costs: three unused image bindings on a draw that samples
795 /// nothing, against a second set and a second layout for the draws that
796 /// want more than one.
797 textures: [Option<u32>; MAX_EFFECT_TEXTURES],
798 },
799 /// A texture, sampled at coordinates the vertices carry.
800 ///
801 /// Deliberately not [`Material::Image`] with a switch on where its
802 /// coordinates come from. An image mapped from clip space needs an origin,
803 /// a matrix and a source rectangle to say which part of a sheet it draws;
804 /// a mesh needs none of them, because a caller stating a coordinate per
805 /// vertex has already answered all three. What is left is small enough to
806 /// be its own thing, and keeping it separate means neither carries a field
807 /// that means nothing for it.
808 ///
809 /// This is what makes a sprite batch one draw: a hundred quads reading a
810 /// hundred different parts of one sheet differ only in their vertices.
811 Mesh {
812 /// Index into the texture table given at submission.
813 slot: u32,
814 /// Scales the sampled color, applied to premultiplied color like
815 /// [`Material::Image`]'s.
816 alpha: f32,
817 /// Straight color the sampled texel is multiplied by; white changes
818 /// nothing.
819 tint: [f32; 4],
820 /// What happens where a vertex names a coordinate outside the texture,
821 /// across and then down. See [`Material::Image`]'s.
822 tile: [TileMode; 2],
823 /// How to read between texels.
824 sampling: Sampling,
825 },
826 /// A texture, sampled through a mapping from clip space.
827 ///
828 /// `origin` and `to_local` together are an affine: a clip-space position
829 /// maps to texture coordinates as `to_local * (clip - origin)`, which lands
830 /// the image's top-left corner at zero and its bottom-right at one. The
831 /// same pair a radial gradient uses, for the same reason — clip space is
832 /// anisotropic on a non-square target, so a mapping that ignored it would
833 /// stretch every image by the aspect ratio.
834 ///
835 /// Which texture is not named here. The material is data the recorder
836 /// produces without touching the device, so it carries a slot into the
837 /// table supplied at submission instead of a backend handle.
838 Image {
839 to_local: ToLocal,
840 /// Index into the texture table given at submission.
841 slot: u32,
842 /// Scales the sampled color, for drawing an image translucently.
843 ///
844 /// Applied to premultiplied color, so it scales the whole texel rather
845 /// than only its alpha. A texture holds premultiplied color whether it
846 /// was uploaded or rendered into, and treating a sample as straight
847 /// alpha would apply the alpha twice — invisible for an opaque image,
848 /// and plain the moment one translucent image is drawn into another.
849 alpha: f32,
850 /// What happens outside the image, across and then down.
851 ///
852 /// Two because upstream has two: an image shader takes a horizontal
853 /// and a vertical mode, and its tiled texture contents fold and decal
854 /// each axis by its own. A decal along one axis only draws a band.
855 tile: [TileMode; 2],
856 /// How to read between texels.
857 sampling: Sampling,
858 /// The part of the texture to draw, as `[u0, v0, u1, v1]` from zero to
859 /// one.
860 ///
861 /// The whole texture is `[0, 0, 1, 1]`, which is what every caller
862 /// wanted until sprite sheets. Normalized rather than in texels because
863 /// a material is built by a recorder that has never seen the texture
864 /// and cannot know how large it is; the caller who uploaded it does.
865 ///
866 /// Applied after tiling rather than before, so a repeat repeats the
867 /// selected piece rather than the whole sheet -- which is the only
868 /// reading of "tile this sprite" that means anything.
869 source: [f32; 4],
870 /// Straight color the sampled texel is multiplied by; white changes
871 /// nothing.
872 ///
873 /// What turns one monochrome icon sheet into every state a control has.
874 /// A generalization of `alpha` rather than a rival to it: a tint of
875 /// `[1, 1, 1, a]` is exactly that scaling, and both are applied because
876 /// removing the narrower one would break callers for no gain.
877 ///
878 /// Straight rather than premultiplied because that is how a caller
879 /// states a color, and the shader premultiplies it before multiplying a
880 /// texel that already is -- scaling color by the tint's alpha as well,
881 /// which is what keeps the result premultiplied rather than merely
882 /// close to it.
883 tint: [f32; 4],
884 },
885 /// A rounded rectangle evaluated per fragment rather than tessellated.
886 ///
887 /// The shape an interface is mostly made of, and the one where computing
888 /// coverage beats building triangles for it. A tessellated rounded
889 /// rectangle costs vertices proportional to how round it is and has hard
890 /// edges unless the whole pass is multisampled; this is two triangles
891 /// whatever the radius, and antialiases itself from the distance field it
892 /// already computes.
893 ///
894 /// The geometry is in the shape's own space, with `to_local` mapping a
895 /// clip-space position into it -- the same pairing the gradients use, and
896 /// for the same reason: clip space is anisotropic on a target that is not
897 /// square, and a distance measured there would round the corners by
898 /// different amounts on each axis.
899 RoundedRect {
900 color: [f32; 4],
901 /// Half the width and height, in the shape's own space.
902 half_size: [f32; 2],
903 to_local: ToLocal,
904 /// Corner radius, in the shape's own space.
905 radius: f32,
906 /// The radius the outline's *outer* edge turns through, which is not
907 /// always the radius grown by half the stroke.
908 ///
909 /// An outline is the difference of two offset shapes rather than a band
910 /// around one, and the outer offset is where a join shows. Grow a
911 /// rounded corner and you get a bigger rounded corner, so this is
912 /// `radius + stroke / 2` for anything with a radius, and for anything
913 /// with a round join. A *mitered* square corner is the exception: its
914 /// offset is still square, so this is zero and the field draws the
915 /// point the join asks for.
916 ///
917 /// Carried rather than derived because the shader cannot see the join,
918 /// and because deriving it wrongly is what made a square-cornered
919 /// stroke come out with rounded corners and be refused this route
920 /// altogether.
921 outer_radius: f32,
922 /// Trace the outline at this width rather than filling, in the shape's
923 /// own space. Zero fills.
924 ///
925 /// Costs a distance field nothing: the field already says how far every
926 /// fragment is from the edge, so an outline is the band where that is
927 /// small. Tessellating one instead means building a second shape --
928 /// offset inward and outward, with the corners resolved -- which is
929 /// where a stroked outline gets its vertex count and its joins.
930 stroke: f32,
931 },
932 /// A *blurred* rounded rectangle evaluated per fragment, with no blur pass.
933 ///
934 /// The sibling of [`Self::RoundedRect`], and the reason it is worth having
935 /// is that the general route costs three passes per shape -- one for the
936 /// content and two for a separable Gaussian -- where this costs one draw in
937 /// the pass already being recorded. On a Raspberry Pi 5 three shadows that
938 /// way are 7.8 ms of a 26.8 ms frame and nine of its fourteen passes.
939 ///
940 /// The method is Raph Levien's "Blurred rounded rectangles", which is what
941 /// upstream's `SolidRRectBlurContents` evaluates too: the exact convolution
942 /// of a Gaussian with a rounded rectangle has no closed form, and this
943 /// approximates it as a product of two error functions along an axis,
944 /// corrected for the corners by measuring distance with an exponent other
945 /// than two. Every field here is a number the CPU precomputed for that
946 /// expression rather than anything a caller stated -- see
947 /// `Canvas::rrect_blur_material`, which is the only place they are derived.
948 ///
949 /// Only where every corner shares one circular radius, which is upstream's
950 /// condition too. Anything else takes the general route.
951 RoundedRectBlur {
952 color: [f32; 4],
953 to_local: ToLocal,
954 /// Half the rectangle, less `r1`, in the shape's own space.
955 adjust: [f32; 2],
956 /// The corner radius the approximation uses, which is not the caller's:
957 /// it grows with the deviation, because a blurred corner is rounder
958 /// than a sharp one.
959 r1: f32,
960 /// The exponent the corner distance is measured with. Two is a circle;
961 /// this is larger, which is what makes the blurred corner's profile
962 /// match a Gaussian's rather than a circle's.
963 exponent: f32,
964 /// One over the deviation, which is what the error function takes.
965 s_inv: f32,
966 /// The shorter side, which bounds how far the fade can reach before the
967 /// two edges of the shape meet.
968 min_edge: f32,
969 /// Normalizes the fade so that the middle of a large shape reaches full
970 /// coverage.
971 scale: f32,
972 },
973 /// An ellipse evaluated per fragment.
974 ///
975 /// Its own variant rather than a rounded rectangle with a large radius,
976 /// which gives a stadium: past half the shorter side a rounded rectangle
977 /// stops changing, where an ellipse keeps curving along both axes.
978 ///
979 /// The same geometry a rounded rectangle carries, less the radius, which
980 /// the two axes already state.
981 Ellipse {
982 color: [f32; 4],
983 /// The two semi-axes, in the shape's own space.
984 half_size: [f32; 2],
985 to_local: ToLocal,
986 /// Trace the outline at this width rather than filling. Zero fills.
987 stroke: f32,
988 },
989 /// One axis of a separable Gaussian blur of a sampled texture.
990 ///
991 /// Separable because a two-dimensional Gaussian is the product of two
992 /// one-dimensional ones, so blurring along each axis in turn gives the
993 /// same result as a square of taps at a fraction of the cost: at a radius
994 /// of sixteen that is thirty-three taps against a thousand and eighty-nine.
995 /// Two passes are the price, which is why this names an axis rather than
996 /// describing the whole blur.
997 Blur {
998 to_local: ToLocal,
999 slot: u32,
1000 /// One tap's step, in the sampled texture's own coordinates.
1001 ///
1002 /// The axis and the texel size together: a horizontal pass over a
1003 /// target `w` wide steps `(1/w, 0)`. Stated here rather than derived in
1004 /// the shader because the shader does not know the size of what it is
1005 /// sampling.
1006 step: [f32; 2],
1007 /// Standard deviation, in taps.
1008 ///
1009 /// The tap count follows from it -- the kernel reaches
1010 /// `(sigma - 0.5) * sqrt(3)` each way, which is upstream's radius for a
1011 /// given deviation -- so a caller sets how soft the result is and
1012 /// nothing else.
1013 sigma: f32,
1014 },
1015 /// One axis of a morphological filter of a finished layer.
1016 ///
1017 /// The largest or smallest sample within a radius, per channel, which is
1018 /// what `dart:ui` calls `ImageFilter.dilate` and `ImageFilter.erode`. Like
1019 /// the blur it is separable -- a rectangular structuring element is the
1020 /// product of two intervals -- so two passes give the square of taps.
1021 ///
1022 /// Unlike the blur it is also *decomposable*: dilating by `a` and then by
1023 /// `b` is dilating by `a + b` exactly, because the structuring elements add
1024 /// under the Minkowski sum. A radius past what one pass can reach is
1025 /// therefore split across passes rather than approximated by sampling more
1026 /// sparsely. Sparse taps work for a blur, where a missed sample costs a
1027 /// little smoothness, and do not work here: the result is a maximum, so a
1028 /// missed sample is a scallop in the edge.
1029 Morphology {
1030 to_local: ToLocal,
1031 slot: u32,
1032 /// One tap's step, in the sampled texture's own coordinates. As
1033 /// [`Self::Blur::step`].
1034 step: [f32; 2],
1035 /// How many texels each way this pass reaches, at most
1036 /// [`MORPHOLOGY_TAPS`].
1037 ///
1038 /// A whole number of texels, because the structuring element is a set
1039 /// of samples rather than a weighting of them and there is no meaning
1040 /// to half of one.
1041 radius: f32,
1042 /// The largest sample in reach rather than the smallest.
1043 dilate: bool,
1044 },
1045 /// Coverage sampled from an atlas, tinting one color.
1046 ///
1047 /// Distinct from [`Self::Image`] in two ways that matter. The texture is
1048 /// read as *coverage* rather than as color — one channel scaling a solid,
1049 /// which is what antialiased text is — and the coordinates come from the
1050 /// vertices rather than from a mapping in the paint, so a run of glyphs
1051 /// reading different parts of one atlas is a single draw.
1052 Glyph {
1053 /// Linear color with straight alpha, as the text is painted.
1054 color: [f32; 4],
1055 /// Index into the texture table given at submission.
1056 slot: u32,
1057 },
1058 /// Many discs of one color, evaluated from the vertices rather than the
1059 /// paint, so that a field of them is one draw.
1060 ///
1061 /// Carries no mapping and no size, which is the whole point of it. Every
1062 /// other fragment-evaluated shape here locates itself through `to_local`,
1063 /// and `to_local` holds the shape's center -- so two of them at different
1064 /// places are two materials and cannot share a draw. This one locates
1065 /// itself from the interpolated texture coordinate, which the vertices
1066 /// carry as the unit circle's corners, so any number of discs at any
1067 /// centers are one material and one draw.
1068 ///
1069 /// The edge is the same edge. `disc_coverage` in the shader differentiates
1070 /// the implicit function across the pixel rather than forming a distance,
1071 /// and a derivative of an interpolated value is as available as that of a
1072 /// computed one.
1073 PointField {
1074 /// One color for the field, premultiplied as everything here is.
1075 color: [f32; 4],
1076 },
1077 /// A blurred convex shape's shadow, drawn as a mesh whose vertices carry
1078 /// a Gaussian coefficient in their first texture coordinate.
1079 ///
1080 /// The coefficient is interpolated across each triangle and mapped per
1081 /// fragment through the Gaussian's integral, upstream's
1082 /// `IPHalfFractionToFastGaussianCDF`: zero at the mesh's outer ring, where
1083 /// the shadow has gone, one at its umbra. Interpolating the opacity
1084 /// instead would draw the falloff as straight ramps. Upstream's
1085 /// `ShadowVerticesContents`; the mesh is `emblema_geometry::shadow`'s.
1086 ShadowMesh {
1087 /// The shadow's color, straight, as a solid fill's.
1088 color: [f32; 4],
1089 },
1090}
1091
1092/// What happens outside an image's own bounds.
1093///
1094/// Numbered as upstream numbers them: the discriminants are `dart:ui`'s
1095/// `TileMode.index`, `DlTileMode` and Impeller's `Entity::TileMode`, so
1096/// `as u8` gives an embedder the upstream number, as with
1097/// [`crate::BlendMode`]. The number a shader reads is [`tile`], kept apart.
1098#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1099#[repr(u8)]
1100pub enum TileMode {
1101 /// Hold the edge pixel. The usual choice for drawing an image once.
1102 #[default]
1103 Clamp = 0,
1104 /// Repeat the image, tiling the plane.
1105 Repeat = 1,
1106 /// Repeat, reversing every other copy.
1107 ///
1108 /// What repeating is for when the two ends do not match. A ramp tiled by
1109 /// [`TileMode::Repeat`] jumps from its last color back to its first at
1110 /// every period, and that discontinuity is a visible seam; reflecting each
1111 /// alternate copy joins end to end and leaves none. The period is twice as
1112 /// long, since a copy and its reflection make one.
1113 Mirror = 2,
1114 /// Draw nothing outside the image.
1115 ///
1116 /// Distinct from clamping in the only case that matters: a shape larger
1117 /// than the image it is filled with. Clamping smears the border across the
1118 /// remainder, which reads as a rendering fault rather than as a choice.
1119 Decal = 3,
1120}
1121
1122impl Material {
1123 pub fn solid(color: [f32; 4]) -> Self {
1124 Self::Solid(color)
1125 }
1126
1127 /// How this material reads a texture, if it reads one.
1128 ///
1129 /// `None` for a material that samples nothing, which is not the same answer
1130 /// as [`Sampling::Nearest`]: one says there is no texture and the other says
1131 /// there is and it is read at a texel's center.
1132 ///
1133 /// Here because a caller above the HAL may need to know whether a draw
1134 /// interpolates between texels, and only this type knows. The test harness
1135 /// asks it to size a cross-device tolerance: a filter that forms a weighted
1136 /// sum of texels does so with weights of implementation-defined precision,
1137 /// so two devices disagree on every interpolated pixel by more than the last
1138 /// bit of one store. Deriving that from a recording rather than from the
1139 /// scene that produced it is the point -- the scene model has four separate
1140 /// places a sampled texture can come from and a comment recording four
1141 /// occasions on which enumerating them missed one.
1142 pub fn sampling(&self) -> Option<Sampling> {
1143 match self {
1144 // Samples nothing: the color arrives on the vertices.
1145 Self::VertexGradient => None,
1146 Self::Image { sampling, .. } | Self::Mesh { sampling, .. } => Some(*sampling),
1147 // Reads a texture and states no filter: a blur and a morphology
1148 // sample their own target at offsets they compute, and a glyph reads
1149 // coverage out of the atlas. What they do between texels is the
1150 // shader's, not a field's, so there is no mode to report here.
1151 Self::Blur { .. }
1152 | Self::Morphology { .. }
1153 | Self::Glyph { .. }
1154 | Self::Runtime { .. } => None,
1155 // Reads no texture at all.
1156 Self::Solid(_)
1157 | Self::LinearGradient { .. }
1158 | Self::RadialGradient { .. }
1159 | Self::SweepGradient { .. }
1160 | Self::ConicalGradient { .. }
1161 | Self::RoundedRect { .. }
1162 | Self::RoundedRectBlur { .. }
1163 | Self::Ellipse { .. }
1164 | Self::PointField { .. }
1165 | Self::ShadowMesh { .. } => None,
1166 }
1167 }
1168
1169 /// Whether this material reads between texels rather than at one.
1170 ///
1171 /// Every mode but [`Sampling::Nearest`] forms a weighted sum: linear over
1172 /// four texels, bicubic over sixteen, mipmapped over two levels of the
1173 /// first. Measured on a Raspberry Pi 5, one scene rendered twice differing
1174 /// only in this: nearest is byte for byte identical between v3d and llvmpipe
1175 /// over the whole frame, and linear reaches a delta of three across seventy
1176 /// per cent of it.
1177 /// Whether this material reads its texture at offsets it computes, rather
1178 /// than at the coordinate it was handed.
1179 ///
1180 /// True for the two filters that walk a neighborhood: a blur steps out by a
1181 /// sigma, a morphology by a radius, and neither need land on a texel center
1182 /// whatever size the texture is. So this is the one case where a material
1183 /// can say that a read interpolates without knowing the texture -- which is
1184 /// why it is a separate question from [`Self::sampling`], and why a layer
1185 /// dilated by a morphology is one of the scenes that put two devices three
1186 /// levels apart.
1187 pub fn reads_at_computed_offsets(&self) -> bool {
1188 matches!(self, Self::Blur { .. } | Self::Morphology { .. })
1189 }
1190
1191 /// The same material at `factor` of its opacity.
1192 ///
1193 /// Applied to every color a material carries, since a gradient's stops may
1194 /// differ in alpha and scaling them together is what keeps the ramp the
1195 /// same ramp. Straight alpha, so this happens before the premultiply the
1196 /// packing does rather than after it.
1197 ///
1198 /// Two variants are left alone and it is worth saying which. A blur or a
1199 /// morphology is a filter over a finished pass rather than a paint, so
1200 /// there is no color in it to dim -- and nothing asks this of one. A
1201 /// caller's program is the other: its output is whatever it computes, and
1202 /// this renderer has no uniform it may write to. That is a real limit
1203 /// wherever the caller wanted the dimming, and it is stated at the one
1204 /// place that asks for it.
1205 #[must_use]
1206 pub fn with_opacity(mut self, factor: f32) -> Self {
1207 let scale = |color: &mut [f32; 4]| color[3] *= factor;
1208 match &mut self {
1209 Self::Solid(color)
1210 | Self::RoundedRect { color, .. }
1211 | Self::RoundedRectBlur { color, .. }
1212 | Self::Ellipse { color, .. }
1213 | Self::PointField { color }
1214 | Self::ShadowMesh { color }
1215 | Self::Glyph { color, .. } => scale(color),
1216 Self::LinearGradient { stops, .. }
1217 | Self::RadialGradient { stops, .. }
1218 | Self::SweepGradient { stops, .. }
1219 | Self::ConicalGradient { stops, .. } => {
1220 for stop in stops.iter_mut() {
1221 scale(&mut stop.color);
1222 }
1223 }
1224 Self::Mesh { alpha, .. } | Self::Image { alpha, .. } => *alpha *= factor,
1225 Self::Runtime { .. } | Self::Blur { .. } | Self::Morphology { .. } => {}
1226 // Nothing here to scale -- the alpha is premultiplied into the
1227 // vertex colors, which this cannot see. The one caller is the thin
1228 // stroke above, and a fill passes a factor of one, so the route
1229 // that uses this material never asks. A route that did would have
1230 // to bake the factor in when it builds the sections.
1231 Self::VertexGradient => {}
1232 }
1233 self
1234 }
1235
1236 /// Whether drawing with this would change anything.
1237 pub fn is_invisible(&self) -> bool {
1238 match self {
1239 Self::Solid(color) | Self::PointField { color } | Self::ShadowMesh { color } => {
1240 color[3] <= 0.0
1241 }
1242 // The colors are on the vertices, so the only honest answer is
1243 // that it might draw something.
1244 Self::VertexGradient => false,
1245 Self::LinearGradient { stops, .. }
1246 | Self::RadialGradient { stops, .. }
1247 | Self::SweepGradient { stops, .. }
1248 | Self::ConicalGradient { stops, .. } => {
1249 stops.is_empty() || stops.iter().all(|s| s.color[3] <= 0.0)
1250 }
1251 // What the texture holds is unknown here, so only a zero alpha
1252 // makes an image provably invisible.
1253 Self::Image { alpha, .. } | Self::Mesh { alpha, .. } => *alpha <= 0.0,
1254 // What a caller's program draws is unknowable from here, so the
1255 // only honest answer is that it might draw something.
1256 Self::Runtime { .. } => false,
1257 // A blur of nothing is nothing, but the pass still has to run: what
1258 // it samples is not knowable from here.
1259 Self::Blur { .. } | Self::Morphology { .. } => false,
1260 // No `half_size` to test: a blurred rectangle with no area still
1261 // draws, because the blur carries color past where the shape is.
1262 Self::RoundedRectBlur { color, .. } => color[3] <= 0.0,
1263 Self::RoundedRect {
1264 color, half_size, ..
1265 }
1266 | Self::Ellipse {
1267 color, half_size, ..
1268 } => color[3] <= 0.0 || half_size[0] <= 0.0 || half_size[1] <= 0.0,
1269 Self::Glyph { color, .. } => color[3] <= 0.0,
1270 }
1271 }
1272
1273 /// The texture slot this samples, for a backend building its bindings.
1274 ///
1275 /// Matched exhaustively rather than with a catch-all. A variant that
1276 /// samples something and is not listed here reports no slot, so the backend
1277 /// binds its placeholder and the draw comes out flat white -- a plausible
1278 /// picture rather than an error, and one nothing else would explain.
1279 /// Every texture slot this material samples, in binding order.
1280 ///
1281 /// One entry for everything but a runtime program, which may declare
1282 /// several. A backend building descriptors needs the whole tuple, since a
1283 /// set holds all of them at once; a backend asking only which slot to bind
1284 /// first has [`Self::texture_slot`].
1285 pub fn texture_slots(&self) -> [Option<u32>; MAX_EFFECT_TEXTURES] {
1286 match self {
1287 Self::Runtime { textures, .. } => *textures,
1288 other => {
1289 let mut slots = [None; MAX_EFFECT_TEXTURES];
1290 slots[0] = other.texture_slot();
1291 slots
1292 }
1293 }
1294 }
1295
1296 pub fn texture_slot(&self) -> Option<u32> {
1297 match self {
1298 Self::VertexGradient => None,
1299 Self::Image { slot, .. }
1300 | Self::Mesh { slot, .. }
1301 | Self::Glyph { slot, .. }
1302 | Self::Blur { slot, .. }
1303 | Self::Morphology { slot, .. } => Some(*slot),
1304 // A gradient names a texture only when its colors were too many to
1305 // carry, which is why this is an option rather than a slot.
1306 Self::LinearGradient { ramp, .. }
1307 | Self::RadialGradient { ramp, .. }
1308 | Self::SweepGradient { ramp, .. }
1309 | Self::ConicalGradient { ramp, .. } => *ramp,
1310 Self::Solid(_)
1311 | Self::PointField { .. }
1312 | Self::ShadowMesh { .. }
1313 | Self::RoundedRect { .. }
1314 | Self::RoundedRectBlur { .. }
1315 | Self::Ellipse { .. } => None,
1316 // Whatever a caller named, and `None` where they named nothing --
1317 // in which case the placeholder is bound and a program that
1318 // samples anyway reads opaque white.
1319 // The first of them, for the callers that still ask a material for
1320 // one slot. `texture_slots` is what a backend binding several
1321 // should ask.
1322 Self::Runtime { textures, .. } => textures[0],
1323 }
1324 }
1325
1326 /// The stops, for any material that has them.
1327 fn stops(&self) -> &[Stop] {
1328 match self {
1329 // Its stops became vertex colors when the sections were built.
1330 Self::VertexGradient => &[],
1331 Self::Solid(_)
1332 | Self::PointField { .. }
1333 | Self::ShadowMesh { .. }
1334 | Self::Image { .. }
1335 | Self::Mesh { .. }
1336 | Self::Glyph { .. }
1337 | Self::Blur { .. }
1338 | Self::Morphology { .. }
1339 | Self::RoundedRect { .. }
1340 | Self::RoundedRectBlur { .. }
1341 | Self::Ellipse { .. }
1342 | Self::Runtime { .. } => &[],
1343 Self::LinearGradient { stops, .. }
1344 | Self::RadialGradient { stops, .. }
1345 | Self::SweepGradient { stops, .. }
1346 | Self::ConicalGradient { stops, .. } => stops,
1347 }
1348 }
1349
1350 /// Pack into the layout the shader declares.
1351 ///
1352 /// Every member is a four-component vector, which is what lets this be a
1353 /// flat array of floats copied straight into a uniform buffer: the std140
1354 /// rules the shader's block is declared with place a `vec4` and an array
1355 /// of them at exactly these offsets, so no member needs padding written
1356 /// around it.
1357 ///
1358 /// Stops beyond the limit are dropped rather than resampled, and the count
1359 /// travels alongside so the shader ignores unused entries instead of
1360 /// blending toward whatever happens to be in them.
1361 /// Whether every pixel this material writes comes out fully opaque.
1362 ///
1363 /// Used to decide whether a draw may be split into several, which is only safe when
1364 /// writing a pixel twice gives what writing it once does. Under `SrcOver` that holds
1365 /// exactly when the source is opaque.
1366 ///
1367 /// **False unless shown otherwise.** A solid fill carries its alpha and a gradient's
1368 /// stops carry theirs. Everything else -- images, the analytic shapes, blurs, a
1369 /// caller's own program -- is refused outright.
1370 ///
1371 /// A tabulated gradient still answers from its stops, and that is worth saying because
1372 /// the first version of this refused one. `ramp` being `Some` means the *shader* reads
1373 /// a texture instead of walking the list, not that the list is gone: the recorder maps
1374 /// every stop into the material either way and bakes the ramp from the same list, by
1375 /// interpolating between them. Interpolating between opaque colors gives an opaque
1376 /// one, so the texels are opaque exactly when the stops are. Refusing a ramp cost the
1377 /// whole of occlusion culling's benefit on the bench's frame, whose wash is five stops
1378 /// against a `MAX_STOPS` of four.
1379 pub fn is_opaque(&self) -> bool {
1380 let stops_opaque =
1381 |stops: &[Stop]| !stops.is_empty() && stops.iter().all(|s| s.color[3] >= 1.0);
1382 match self {
1383 Material::Solid(color) => color[3] >= 1.0,
1384 Material::LinearGradient { stops, .. }
1385 | Material::RadialGradient { stops, .. }
1386 | Material::SweepGradient { stops, .. }
1387 | Material::ConicalGradient { stops, .. } => stops_opaque(stops),
1388 _ => false,
1389 }
1390 }
1391
1392 /// Whether this material's shading reads screen-space derivatives.
1393 ///
1394 /// `dpdx` and `dpdy` are computed across a two-by-two quad of fragments, using helper
1395 /// invocations outside the primitive. Whether a scissor keeps those helpers alive is
1396 /// not something either specification settles, and implementations differ: Mesa
1397 /// 26.2.3 keeps them and 25.2.8 does not. So a draw whose shading depends on them
1398 /// gives a different answer at a scissor's edge than away from it, and splitting such
1399 /// a draw by scissor changes the picture along the seam.
1400 ///
1401 /// Measured rather than reasoned about: an analytic shadow drawn once reads 217 where
1402 /// the same shadow drawn in four scissored strips reads 206, at the pixel on the
1403 /// strip boundary, on Mesa 25.2.8. See `a_scissor_does_not_change_what_a_draw_paints`.
1404 ///
1405 /// **True unless shown otherwise**, which is the only safe direction: a material
1406 /// wrongly called derivative-free leaves a seam in the frame. The two groups that are
1407 /// shown otherwise are solid fills, whose coverage comes from the rasterizer, and the
1408 /// gradients, which sample their ramp at an explicit level of zero. The rest either
1409 /// take a coverage from the gradient of a distance field -- the rounded rectangle, the
1410 /// ellipse and the rounded-rectangle blur -- or a texture level from the rate their
1411 /// coordinates change, which is every image fill, or are a caller's own program.
1412 pub fn needs_screen_derivatives(&self) -> bool {
1413 !matches!(
1414 self,
1415 Material::Solid(_)
1416 | Material::VertexGradient
1417 | Material::LinearGradient { .. }
1418 | Material::RadialGradient { .. }
1419 | Material::SweepGradient { .. }
1420 | Material::ConicalGradient { .. }
1421 )
1422 }
1423
1424 /// Whether this material asks the target for a long run of nearly equal
1425 /// values, and so wants a dither.
1426 ///
1427 /// The gradients, and nothing else -- the same set the shader used to test
1428 /// for itself. Asked here because the shader cannot be the place that knows:
1429 /// it tests the material *kind*, so a route that draws a gradient under a
1430 /// different kind silently stops dithering. §19 of `docs/non-parity.md`
1431 /// records that happening, in the reverted attempt at upstream's
1432 /// vertex-interpolated fast gradient.
1433 ///
1434 /// **False unless shown otherwise.** Dithering something with no band to
1435 /// break adds noise to a flat color.
1436 pub fn dithers(&self) -> bool {
1437 matches!(
1438 self,
1439 // The one non-gradient here, and the reason this predicate is not
1440 // simply "is a gradient": what it draws is a gradient, with the
1441 // rasterizer interpolating it instead of the fragment stage.
1442 Material::VertexGradient
1443 | Material::LinearGradient { .. }
1444 | Material::RadialGradient { .. }
1445 | Material::SweepGradient { .. }
1446 | Material::ConicalGradient { .. }
1447 )
1448 }
1449
1450 pub fn to_uniform(&self) -> [f32; MATERIAL_FLOATS] {
1451 let mut out = [0.0f32; MATERIAL_FLOATS];
1452
1453 if let Self::Solid(color) = self {
1454 out[layout::STOPS..layout::STOPS + 4].copy_from_slice(color);
1455 out[layout::PARAMS] = 1.0;
1456 out[layout::PARAMS + 1] = kind::SOLID;
1457 return out;
1458 }
1459
1460 // Opaque white under the solid kind, which is the identity for the
1461 // `Modulate` tint that carries the vertex color. Packed here rather
1462 // than falling through, because the machinery below reads `stops` and
1463 // this material has none -- a gradient with no stops packs as
1464 // transparent black, which is the opposite of an identity.
1465 if matches!(self, Self::VertexGradient) {
1466 out[layout::STOPS..layout::STOPS + 4].copy_from_slice(&[1.0, 1.0, 1.0, 1.0]);
1467 out[layout::PARAMS] = 1.0;
1468 out[layout::PARAMS + 1] = kind::SOLID;
1469 return out;
1470 }
1471
1472 // A glyph is a solid color plus a texture read; the coordinates come
1473 // from the vertices, so nothing about the mapping is packed here.
1474 if let Self::Glyph { color, .. } = self {
1475 out[layout::STOPS..layout::STOPS + 4].copy_from_slice(color);
1476 out[layout::PARAMS] = 1.0;
1477 out[layout::PARAMS + 1] = kind::GLYPH;
1478 return out;
1479 }
1480
1481 // An image carries no stops and no count, and must be packed before
1482 // the gradient path below decides it has too few to interpolate.
1483 if let Self::PointField { color } = self {
1484 out[layout::STOPS..layout::STOPS + 4].copy_from_slice(color);
1485 out[layout::PARAMS] = 1.0;
1486 out[layout::PARAMS + 1] = kind::POINT_FIELD;
1487 return out;
1488 }
1489
1490 if let Self::ShadowMesh { color } = self {
1491 out[layout::STOPS..layout::STOPS + 4].copy_from_slice(color);
1492 out[layout::PARAMS] = 1.0;
1493 out[layout::PARAMS + 1] = kind::SHADOW_MESH;
1494 return out;
1495 }
1496
1497 if let Self::Ellipse {
1498 color,
1499 half_size,
1500 to_local,
1501 stroke,
1502 } = self
1503 {
1504 out[layout::STOPS..layout::STOPS + 4].copy_from_slice(color);
1505 out[layout::GEOMETRY + 2] = half_size[0];
1506 out[layout::GEOMETRY + 3] = half_size[1];
1507 out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1508 out[layout::PARAMS] = 1.0;
1509 out[layout::PARAMS + 1] = kind::ELLIPSE;
1510 out[layout::PARAMS + 3] = *stroke;
1511 return out;
1512 }
1513
1514 if let Self::RoundedRect {
1515 color,
1516 half_size,
1517 to_local,
1518 radius,
1519 outer_radius,
1520 stroke,
1521 } = self
1522 {
1523 out[layout::STOPS..layout::STOPS + 4].copy_from_slice(color);
1524 out[layout::GEOMETRY + 1] = *outer_radius;
1525 out[layout::GEOMETRY + 2] = half_size[0];
1526 out[layout::GEOMETRY + 3] = half_size[1];
1527 out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1528 out[layout::PARAMS] = 1.0;
1529 out[layout::PARAMS + 1] = kind::ROUNDED_RECT;
1530 out[layout::PARAMS + 2] = *radius;
1531 out[layout::PARAMS + 3] = *stroke;
1532 return out;
1533 }
1534
1535 if let Self::RoundedRectBlur {
1536 color,
1537 to_local,
1538 adjust,
1539 r1,
1540 exponent,
1541 s_inv,
1542 min_edge,
1543 scale,
1544 } = self
1545 {
1546 out[layout::STOPS..layout::STOPS + 4].copy_from_slice(color);
1547 out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1548 // The first two floats of `GEOMETRY` are unclaimed for every kind
1549 // that carries a mapping, which this does, so the two that follow
1550 // are what a rounded rectangle would have used for its half size --
1551 // and it needs none, because `adjust` already has the shape in it.
1552 out[layout::GEOMETRY] = adjust[0];
1553 out[layout::GEOMETRY + 1] = adjust[1];
1554 out[layout::GEOMETRY + 2] = *s_inv;
1555 out[layout::GEOMETRY + 3] = *min_edge;
1556 // `OFFSETS` holds stop positions for a gradient and nothing for
1557 // anything else, which is what makes it the seventh float this
1558 // needs and the only kind here that borrows it.
1559 out[layout::OFFSETS] = *scale;
1560 out[layout::PARAMS] = 1.0;
1561 out[layout::PARAMS + 1] = kind::ROUNDED_RECT_BLUR;
1562 out[layout::PARAMS + 2] = *r1;
1563 out[layout::PARAMS + 3] = *exponent;
1564 return out;
1565 }
1566
1567 if let Self::Blur {
1568 to_local,
1569 step,
1570 sigma,
1571 ..
1572 } = self
1573 {
1574 out[layout::GEOMETRY + 2] = step[0];
1575 out[layout::GEOMETRY + 3] = step[1];
1576 out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1577 out[layout::PARAMS] = 1.0;
1578 out[layout::PARAMS + 1] = kind::BLUR;
1579 out[layout::PARAMS + 2] = *sigma;
1580 return out;
1581 }
1582
1583 if let Self::Morphology {
1584 to_local,
1585 step,
1586 radius,
1587 dilate,
1588 ..
1589 } = self
1590 {
1591 out[layout::GEOMETRY + 2] = step[0];
1592 out[layout::GEOMETRY + 3] = step[1];
1593 out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1594 out[layout::PARAMS] = 1.0;
1595 out[layout::PARAMS + 1] = kind::MORPHOLOGY;
1596 out[layout::PARAMS + 2] = radius.clamp(0.0, MORPHOLOGY_TAPS as f32);
1597 out[layout::PARAMS + 3] = if *dilate { 1.0 } else { 0.0 };
1598 return out;
1599 }
1600
1601 if let Self::Runtime {
1602 uniforms, to_local, ..
1603 } = self
1604 {
1605 // Straight into the block, in the order the caller wrote them. No
1606 // kind is set: nothing in the shared fragment stage will read this,
1607 // and a caller's program does not branch on one.
1608 let count = uniforms.len().min(MATERIAL_EFFECT_FLOATS);
1609 out[..count].copy_from_slice(&uniforms[..count]);
1610 out[layout::RUNTIME_TO_LOCAL..].copy_from_slice(to_local);
1611 return out;
1612 }
1613
1614 if let Self::Mesh {
1615 alpha,
1616 tint,
1617 tile,
1618 sampling,
1619 ..
1620 } = self
1621 {
1622 out[layout::STOPS..layout::STOPS + 4].copy_from_slice(tint);
1623 out[layout::GEOMETRY] = *alpha;
1624 out[layout::GEOMETRY + 1] = tile_code(tile[0]);
1625 out[layout::GEOMETRY + 2] = tile_code(tile[1]);
1626 out[layout::PARAMS] = 1.0;
1627 out[layout::PARAMS + 1] = kind::MESH;
1628 out[layout::PARAMS + 2] = sampling_code(*sampling);
1629 return out;
1630 }
1631
1632 if let Self::Image {
1633 to_local,
1634 alpha,
1635 tile,
1636 sampling,
1637 source,
1638 tint,
1639 ..
1640 } = self
1641 {
1642 // Into the stop colors, which an image has none of. Eight floats
1643 // that would otherwise travel as zeros on every image draw.
1644 out[layout::STOPS..layout::STOPS + 4].copy_from_slice(source);
1645 out[layout::STOPS + 4..layout::STOPS + 8].copy_from_slice(tint);
1646 // The vertical mode in the slot a mapped kind leaves free. Not the
1647 // first: that is the flag a batch sets for a paint read at texture
1648 // coordinates, and it is the batch's to write.
1649 out[layout::GEOMETRY + 1] = tile_code(tile[1]);
1650 out[layout::GEOMETRY + 2] = *alpha;
1651 out[layout::GEOMETRY + 3] = tile_code(tile[0]);
1652 out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1653 out[layout::PARAMS] = 1.0;
1654 out[layout::PARAMS + 1] = kind::IMAGE;
1655 out[layout::PARAMS + 2] = sampling_code(*sampling);
1656 return out;
1657 }
1658
1659 let stops = self.stops();
1660 let count = stops.len().min(MAX_STOPS);
1661 for (i, stop) in stops.iter().take(count).enumerate() {
1662 out[layout::STOPS + i * 4..layout::STOPS + i * 4 + 4].copy_from_slice(&stop.color);
1663 out[layout::OFFSETS + i] = stop.offset;
1664 }
1665 out[layout::PARAMS] = count.max(1) as f32;
1666
1667 // A gradient with fewer than two stops has nothing to interpolate
1668 // between, so it renders as its first color rather than sending the
1669 // shader down a path that would read an entry nothing wrote.
1670 if count < 2 {
1671 out[layout::PARAMS + 1] = kind::SOLID;
1672 return out;
1673 }
1674
1675 match self {
1676 Self::Solid(_)
1677 | Self::VertexGradient
1678 | Self::PointField { .. }
1679 | Self::ShadowMesh { .. }
1680 | Self::Image { .. }
1681 | Self::Mesh { .. }
1682 | Self::Glyph { .. }
1683 | Self::Blur { .. }
1684 | Self::Morphology { .. }
1685 | Self::RoundedRect { .. }
1686 | Self::RoundedRectBlur { .. }
1687 | Self::Ellipse { .. }
1688 | Self::Runtime { .. } => {
1689 unreachable!("handled above")
1690 }
1691 Self::LinearGradient {
1692 ramp,
1693 axis,
1694 to_local,
1695 tile,
1696 ..
1697 } => {
1698 out[layout::PARAMS] = stop_count_code(count, ramp);
1699 out[layout::PARAMS + 2] = tile_code(*tile);
1700 out[layout::GEOMETRY + 2] = axis[0];
1701 out[layout::GEOMETRY + 3] = axis[1];
1702 out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1703 out[layout::PARAMS + 1] = kind::LINEAR;
1704 }
1705 Self::RadialGradient {
1706 ramp,
1707 to_local,
1708 tile,
1709 ..
1710 } => {
1711 out[layout::PARAMS] = stop_count_code(count, ramp);
1712 out[layout::PARAMS + 2] = tile_code(*tile);
1713 out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1714 out[layout::PARAMS + 1] = kind::RADIAL;
1715 }
1716 Self::SweepGradient {
1717 ramp,
1718 to_local,
1719 start_angle,
1720 end_angle,
1721 tile,
1722 ..
1723 } => {
1724 out[layout::PARAMS] = stop_count_code(count, ramp);
1725 out[layout::PARAMS + 2] = tile_code(*tile);
1726 out[layout::GEOMETRY + 2] = *start_angle;
1727 out[layout::GEOMETRY + 3] = *end_angle;
1728 out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1729 out[layout::PARAMS + 1] = kind::SWEEP;
1730 }
1731 Self::ConicalGradient {
1732 ramp,
1733 to_local,
1734 start_radius,
1735 radius_delta,
1736 separation,
1737 tile,
1738 ..
1739 } => {
1740 out[layout::PARAMS] = stop_count_code(count, ramp);
1741 out[layout::PARAMS + 2] = tile_code(*tile);
1742 out[layout::GEOMETRY + 2] = *start_radius;
1743 out[layout::GEOMETRY + 3] = *radius_delta;
1744 out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1745 out[layout::PARAMS + 1] = kind::CONICAL;
1746 out[layout::PARAMS + 3] = *separation;
1747 }
1748 }
1749 out
1750 }
1751
1752 /// The caller's program this draws with, where it uses one.
1753 ///
1754 /// `None` is every material the built-in shader draws, which is all of
1755 /// them but one.
1756 /// A runtime effect's floats, as the caller gave them.
1757 pub fn effect_uniforms(&self) -> Option<&[f32]> {
1758 match self {
1759 Self::Runtime { uniforms, .. } => Some(uniforms),
1760 _ => None,
1761 }
1762 }
1763
1764 pub fn program(&self) -> Option<u32> {
1765 match self {
1766 Self::Runtime { program, .. } => Some(*program),
1767 _ => None,
1768 }
1769 }
1770
1771 /// Which of the built-in shader's material arms this draws with.
1772 ///
1773 /// A pipeline is built with the arm its draws need and no other, so a
1774 /// driver compiles a fraction of the shader for each; see
1775 /// [`ShaderVariant`]. Exhaustive on purpose: a new material has to say
1776 /// where it is drawn, and the shader has to guard its arm by the same part.
1777 pub fn variant(&self) -> MaterialVariant {
1778 match self {
1779 Self::Solid(_)
1780 | Self::VertexGradient
1781 | Self::LinearGradient { .. }
1782 | Self::RadialGradient { .. }
1783 | Self::SweepGradient { .. }
1784 | Self::ConicalGradient { .. }
1785 | Self::Glyph { .. } => MaterialVariant::Core,
1786 Self::Image { .. } => MaterialVariant::Image,
1787 Self::Mesh { .. } => MaterialVariant::Mesh,
1788 Self::RoundedRect { .. }
1789 | Self::RoundedRectBlur { .. }
1790 | Self::Ellipse { .. }
1791 | Self::PointField { .. }
1792 | Self::ShadowMesh { .. } => MaterialVariant::Shape,
1793 Self::Blur { .. } | Self::Morphology { .. } => MaterialVariant::Pass,
1794 Self::Runtime { .. } => MaterialVariant::Runtime,
1795 }
1796 }
1797}
1798
1799/// Which arm of the built-in shader a material is drawn by.
1800#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1801pub enum MaterialVariant {
1802 /// A solid color, a gradient or a glyph: what every variant carries.
1803 Core,
1804 Image,
1805 Mesh,
1806 /// Rounded rectangles, ellipses, a rounded rectangle's blur, point fields
1807 /// and shadow meshes.
1808 Shape,
1809 /// A blur or a morphology pass.
1810 Pass,
1811 /// A caller's program, which replaces the built-in fragment stage.
1812 Runtime,
1813}
1814
1815/// The parts of the built-in shader one draw needs: its material's arm, and
1816/// whether it filters its color and blends its tint by a mode other than
1817/// `Modulate`.
1818///
1819/// A backend builds a pipeline per variant. The shader holding every part cost
1820/// seconds to compile on some drivers with their caches empty -- 1.8 on a
1821/// Raspberry Pi 5's V3D, about 5 on an RK3566's Mali-G52 -- and a frame of
1822/// solid colors, gradients and text needs a variant that compiles in tens of
1823/// milliseconds.
1824#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1825pub struct ShaderVariant {
1826 pub material: MaterialVariant,
1827 pub filters: bool,
1828 pub tint_blends: bool,
1829 /// Blends with what is under the draw in the shader, read from a texture
1830 /// (`BatchDraw::destination`), for an advanced mode the device's blend
1831 /// unit cannot do.
1832 pub reads_destination: bool,
1833}
1834
1835impl ShaderVariant {
1836 /// A solid color, a gradient or a glyph, unfiltered and tinted by
1837 /// `Modulate`: what most of a frame draws with, and what a backend
1838 /// prepares ahead of the first frame.
1839 pub const CORE: ShaderVariant = ShaderVariant {
1840 material: MaterialVariant::Core,
1841 filters: false,
1842 tint_blends: false,
1843 reads_destination: false,
1844 };
1845}
1846
1847#[cfg(test)]
1848mod tests {
1849
1850 /// Each axis's mode where the shader reads it: an image's across in the
1851 /// last geometry float and down in the second, a mesh's in the second and
1852 /// third. The first is the batch's flag, and neither writes it.
1853 #[test]
1854 fn an_image_and_a_mesh_pack_a_tile_mode_per_axis() {
1855 let image = Material::Image {
1856 to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
1857 slot: 0,
1858 alpha: 0.5,
1859 tile: [TileMode::Repeat, TileMode::Decal],
1860 sampling: Sampling::Linear,
1861 source: [0.0, 0.0, 1.0, 1.0],
1862 tint: [1.0; 4],
1863 }
1864 .to_uniform();
1865 assert_eq!(
1866 &image[layout::GEOMETRY..layout::GEOMETRY + 4],
1867 &[0.0, tile::DECAL, 0.5, tile::REPEAT]
1868 );
1869
1870 let mesh = Material::Mesh {
1871 slot: 0,
1872 alpha: 0.5,
1873 tint: [1.0; 4],
1874 tile: [TileMode::Mirror, TileMode::Repeat],
1875 sampling: Sampling::Linear,
1876 }
1877 .to_uniform();
1878 assert_eq!(
1879 &mesh[layout::GEOMETRY..layout::GEOMETRY + 3],
1880 &[0.5, tile::MIRROR, tile::REPEAT]
1881 );
1882 }
1883
1884 /// The enum carries upstream's numbers; the shader keeps its own, and
1885 /// reordering the enum to the first left the second alone.
1886 #[test]
1887 fn tile_modes_are_upstreams_numbers_and_the_shader_keeps_its_own() {
1888 assert_eq!(
1889 [
1890 TileMode::Clamp,
1891 TileMode::Repeat,
1892 TileMode::Mirror,
1893 TileMode::Decal
1894 ]
1895 .map(|t| t as u8),
1896 [0, 1, 2, 3],
1897 "dart:ui TileMode.index and Impeller's Entity::TileMode"
1898 );
1899 assert_eq!(tile_code(TileMode::Clamp), tile::CLAMP);
1900 assert_eq!(tile_code(TileMode::Repeat), tile::REPEAT);
1901 assert_eq!(tile_code(TileMode::Mirror), 3.0);
1902 assert_eq!(tile_code(TileMode::Decal), 2.0);
1903 }
1904
1905 /// `VertexGradient` packs as the identity for the tint that colors it, and
1906 /// asks for a dither where `Solid` does not.
1907 #[test]
1908 fn a_vertex_gradient_packs_as_white_and_dithers() {
1909 let packed = Material::VertexGradient.to_uniform();
1910 assert_eq!(
1911 &packed[layout::STOPS..layout::STOPS + 4],
1912 &[1.0, 1.0, 1.0, 1.0],
1913 "opaque white is the identity for a `Modulate` tint"
1914 );
1915 assert_eq!(packed[layout::PARAMS + 1], kind::SOLID);
1916 assert_eq!(packed[layout::PARAMS], 1.0);
1917
1918 assert!(Material::VertexGradient.dithers());
1919 assert!(!Material::solid([1.0; 4]).dithers());
1920 }
1921
1922 /// And answers the rest of the predicates the way its shading does: no
1923 /// texture, no derivatives, and nothing knowable about its coverage.
1924 #[test]
1925 fn a_vertex_gradient_answers_the_other_predicates() {
1926 let m = Material::VertexGradient;
1927 assert!(!m.needs_screen_derivatives(), "a vertex color reads none");
1928 assert_eq!(m.sampling(), None);
1929 assert_eq!(m.texture_slot(), None);
1930 assert!(!m.is_invisible(), "the colors are on the vertices");
1931 assert!(
1932 !m.is_opaque(),
1933 "the vertex alphas are not visible from here"
1934 );
1935 }
1936 use super::*;
1937
1938 /// What a material can say about a texture read, and what it cannot.
1939 ///
1940 /// The second half is the point. A material has never seen the texture it
1941 /// names -- `Image::source` says so in as many words -- so it can report the
1942 /// filter that is bound and never whether that filter interpolates, which
1943 /// depends on the texture's size against the size it is drawn at. Only the
1944 /// two neighborhood filters escape that, because they step out by a sigma or
1945 /// a radius whatever the size is.
1946 #[test]
1947 fn a_material_reports_its_filter_and_not_what_the_filter_does() {
1948 let image = |sampling| Material::Image {
1949 to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
1950 slot: 3,
1951 alpha: 1.0,
1952 tile: [TileMode::Clamp; 2],
1953 sampling,
1954 source: [0.0, 0.0, 1.0, 1.0],
1955 tint: [1.0; 4],
1956 };
1957
1958 for sampling in [
1959 Sampling::Nearest,
1960 Sampling::Linear,
1961 Sampling::Cubic,
1962 Sampling::Mipmap,
1963 ] {
1964 assert_eq!(image(sampling).sampling(), Some(sampling));
1965 assert_eq!(image(sampling).texture_slot(), Some(3));
1966 // Even a linear one: whether it lands between texels is the
1967 // caller's geometry against a size this type does not hold.
1968 assert!(
1969 !image(sampling).reads_at_computed_offsets(),
1970 "an image is read where it is drawn, not at an offset of its own"
1971 );
1972 }
1973
1974 // The one case a material can settle by itself.
1975 let morphology = Material::Morphology {
1976 to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
1977 slot: 0,
1978 step: [1.0, 0.0],
1979 radius: 2.0,
1980 dilate: true,
1981 };
1982 assert_eq!(
1983 morphology.sampling(),
1984 None,
1985 "it carries no filter to report"
1986 );
1987 assert!(morphology.reads_at_computed_offsets());
1988
1989 // Reads a texture, states no filter, and walks nothing: the pair of
1990 // answers is why `sampling` returning `None` cannot be read as "no
1991 // texture".
1992 let glyph = Material::Glyph {
1993 color: [1.0; 4],
1994 slot: 1,
1995 };
1996 assert_eq!(glyph.sampling(), None);
1997 assert_eq!(glyph.texture_slot(), Some(1));
1998 assert!(!glyph.reads_at_computed_offsets());
1999
2000 // Reads nothing at all.
2001 let solid = Material::solid([1.0; 4]);
2002 assert_eq!(solid.sampling(), None);
2003 assert_eq!(solid.texture_slot(), None);
2004 assert!(!solid.reads_at_computed_offsets());
2005 }
2006
2007 /// A mapping with the given two-by-two linear part and no translation.
2008 ///
2009 /// Most of these tests care that the mapping survives packing, not what it
2010 /// is, and said so in four floats before the paint's origin moved inside
2011 /// it. This keeps them saying that.
2012 fn linear_to_local(m: [f32; 4]) -> ToLocal {
2013 [
2014 m[0], m[1], 0.0, 0.0, //
2015 m[2], m[3], 0.0, 0.0, //
2016 0.0, 0.0, 1.0, 0.0,
2017 ]
2018 }
2019
2020 fn two_stops() -> Vec<Stop> {
2021 vec![
2022 Stop::new([1.0, 0.0, 0.0, 1.0], 0.0),
2023 Stop::new([0.0, 0.0, 1.0, 1.0], 1.0),
2024 ]
2025 }
2026
2027 #[test]
2028 fn a_solid_color_lands_in_the_first_stop_and_selects_the_solid_path() {
2029 let packed = Material::solid([0.25, 0.5, 0.75, 1.0]).to_uniform();
2030 assert_eq!(&packed[0..4], &[0.25, 0.5, 0.75, 1.0]);
2031 assert_eq!(packed[layout::PARAMS], 1.0, "stop count");
2032 assert_eq!(packed[layout::PARAMS + 1], kind::SOLID);
2033 }
2034
2035 #[test]
2036 fn a_linear_gradient_packs_its_stops_axis_and_count() {
2037 let packed = Material::LinearGradient {
2038 axis: [2.0, 0.0],
2039 to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
2040 stops: two_stops(),
2041 tile: TileMode::Clamp,
2042 ramp: None,
2043 }
2044 .to_uniform();
2045
2046 assert_eq!(&packed[0..4], &[1.0, 0.0, 0.0, 1.0], "first stop");
2047 assert_eq!(&packed[4..8], &[0.0, 0.0, 1.0, 1.0], "second stop");
2048 assert_eq!(packed[layout::OFFSETS], 0.0);
2049 assert_eq!(packed[layout::OFFSETS + 1], 1.0);
2050 assert_eq!(
2051 &packed[layout::GEOMETRY..layout::GEOMETRY + 4],
2052 &[0.0, 0.0, 2.0, 0.0],
2053 "the axis rather than the end point, and nothing in the half the \
2054 start used to occupy before it moved inside the mapping"
2055 );
2056 assert_eq!(
2057 &packed[layout::TO_LOCAL..layout::TO_LOCAL + 12],
2058 &linear_to_local([1.0, 0.0, 0.0, 1.0])
2059 );
2060 assert_eq!(packed[layout::PARAMS + 1], kind::LINEAR);
2061 }
2062
2063 #[test]
2064 fn a_radial_gradient_packs_its_mapping() {
2065 let packed = Material::RadialGradient {
2066 to_local: linear_to_local([2.0, 0.0, 0.0, 4.0]),
2067 stops: two_stops(),
2068 tile: TileMode::Clamp,
2069 ramp: None,
2070 }
2071 .to_uniform();
2072
2073 // A radial gradient states nothing in the geometry slot at all now: its
2074 // center rode there, and rides inside the mapping instead.
2075 assert_eq!(&packed[layout::GEOMETRY..layout::GEOMETRY + 2], &[0.0, 0.0]);
2076 // The mapping is what makes a circle circular on a non-square target,
2077 // so it has to survive packing intact.
2078 assert_eq!(
2079 &packed[layout::TO_LOCAL..layout::TO_LOCAL + 12],
2080 &linear_to_local([2.0, 0.0, 0.0, 4.0])
2081 );
2082 assert_eq!(packed[layout::PARAMS + 1], kind::RADIAL);
2083 }
2084
2085 #[test]
2086 fn a_sweep_gradient_packs_its_angles_alongside_its_center() {
2087 let packed = Material::SweepGradient {
2088 to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
2089 start_angle: 0.5,
2090 end_angle: 2.5,
2091 stops: two_stops(),
2092 tile: TileMode::Clamp,
2093 ramp: None,
2094 }
2095 .to_uniform();
2096
2097 // Angles share the geometry slot with the center, which is why a linear
2098 // gradient's endpoints and a sweep's angles cannot both be present.
2099 assert_eq!(
2100 &packed[layout::GEOMETRY..layout::GEOMETRY + 4],
2101 &[0.0, 0.0, 0.5, 2.5]
2102 );
2103 assert_eq!(packed[layout::PARAMS + 1], kind::SWEEP);
2104 }
2105
2106 #[test]
2107 fn every_gradient_kind_falls_back_to_solid_with_one_stop() {
2108 // Interpolating needs two points. Selecting a gradient path with one
2109 // would have the shader read an entry nothing wrote.
2110 let one = vec![Stop::new([1.0, 1.0, 1.0, 1.0], 0.0)];
2111 let materials = [
2112 Material::LinearGradient {
2113 axis: [1.0 - 0.0, 0.0 - 0.0],
2114 to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
2115 stops: one.clone(),
2116 tile: TileMode::Clamp,
2117 ramp: None,
2118 },
2119 Material::RadialGradient {
2120 to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
2121 stops: one.clone(),
2122 tile: TileMode::Clamp,
2123 ramp: None,
2124 },
2125 Material::SweepGradient {
2126 to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
2127 start_angle: 0.0,
2128 end_angle: 1.0,
2129 stops: one,
2130 tile: TileMode::Clamp,
2131 ramp: None,
2132 },
2133 ];
2134 for material in materials {
2135 let packed = material.to_uniform();
2136 assert_eq!(packed[layout::PARAMS + 1], kind::SOLID, "{material:?}");
2137 assert_eq!(&packed[0..4], &[1.0, 1.0, 1.0, 1.0]);
2138 }
2139 }
2140
2141 #[test]
2142 fn stops_beyond_the_limit_are_dropped_rather_than_overflowing() {
2143 let stops: Vec<Stop> = (0..8)
2144 .map(|i| Stop::new([i as f32 / 8.0, 0.0, 0.0, 1.0], i as f32 / 7.0))
2145 .collect();
2146 let packed = Material::LinearGradient {
2147 axis: [1.0 - 0.0, 0.0 - 0.0],
2148 to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
2149 stops,
2150 tile: TileMode::Clamp,
2151 ramp: None,
2152 }
2153 .to_uniform();
2154 // The count is what stops the shader reading past what was written.
2155 assert_eq!(packed[layout::PARAMS], MAX_STOPS as f32);
2156 }
2157
2158 #[test]
2159 fn visibility_accounts_for_every_stop_of_every_kind() {
2160 assert!(Material::solid([1.0, 1.0, 1.0, 0.0]).is_invisible());
2161 assert!(!Material::solid([0.0, 0.0, 0.0, 1.0]).is_invisible());
2162
2163 let clear = vec![
2164 Stop::new([1.0, 0.0, 0.0, 0.0], 0.0),
2165 Stop::new([0.0, 0.0, 1.0, 0.0], 1.0),
2166 ];
2167 assert!(Material::RadialGradient {
2168 to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
2169 stops: clear,
2170 tile: TileMode::Clamp,
2171 ramp: None,
2172 }
2173 .is_invisible());
2174
2175 let partly = vec![
2176 Stop::new([1.0, 0.0, 0.0, 0.0], 0.0),
2177 Stop::new([0.0, 0.0, 1.0, 1.0], 1.0),
2178 ];
2179 assert!(
2180 !Material::SweepGradient {
2181 to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
2182 start_angle: 0.0,
2183 end_angle: 1.0,
2184 stops: partly,
2185 tile: TileMode::Clamp,
2186 ramp: None,
2187 }
2188 .is_invisible(),
2189 "one visible stop is enough"
2190 );
2191 }
2192
2193 #[test]
2194 fn a_solid_color_and_every_gradient_report_the_core_variant() {
2195 // They share the core of the shader, selected by a uniform, so keying
2196 // a pipeline on the kind would create identical pipelines.
2197 assert_eq!(Material::solid([0.0; 4]).variant(), MaterialVariant::Core);
2198 for material in [
2199 Material::LinearGradient {
2200 axis: [1.0, 0.0],
2201 to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
2202 stops: two_stops(),
2203 tile: TileMode::Clamp,
2204 ramp: None,
2205 },
2206 Material::RadialGradient {
2207 to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
2208 stops: two_stops(),
2209 tile: TileMode::Clamp,
2210 ramp: None,
2211 },
2212 ] {
2213 assert_eq!(material.variant(), MaterialVariant::Core);
2214 }
2215 }
2216}