Skip to main content

waft_embedder/
fragment_shader.rs

1//! Flutter counterpart: dart:ui `FragmentShader`, its uniform slots and `UniformArray`, and the
2//! engine's `lib/ui/painting/fragment_shader.cc` (`ReusableFragmentShader`) that holds a shader's
3//! floats and images.
4//!
5//! A shader keeps Flutter's tightly packed floats; a slot is a `Copy` handle on one float index,
6//! looked up by name once and kept beside the shader, whose `set` takes the shader it writes. The
7//! invariant a later editor must keep: a [`Shader`] or a filter made from a shader copies its
8//! floats and images at that moment, as the engine copies its uniform data into the display list,
9//! so the shader can change for the next frame without changing what was drawn.
10
11use std::ops::Index;
12use std::sync::Arc;
13
14use crate::fragment_program::{FragmentProgram, UniformError};
15use crate::painting::{FilterQuality, Image, Shader, valo};
16
17/// A binding to a uniform of type float. Calling [`set`](Self::set) on this object updates a
18/// float uniform's value.
19///
20/// ```ignore
21/// shader.get_uniform_float("uColor", Some(0))?.set(&mut shader, 1.0);
22/// ```
23///
24/// See also: [`FragmentShader::get_uniform_float`], how [`UniformFloatSlot`] instances are
25/// acquired.
26#[derive(Clone, Copy, Debug)]
27pub struct UniformFloatSlot {
28    /// The effect of the program the slot was looked up in, which a shader it writes is of.
29    program: u64,
30    shader_index: usize,
31    index: usize,
32}
33
34impl UniformFloatSlot {
35    /// Set the float value of the bound uniform in `shader`, one of the program's.
36    pub fn set(self, shader: &mut FragmentShader, val: f64) {
37        debug_assert_eq!(
38            self.program,
39            shader.program.effect().id(),
40            "a slot sets a shader of the program it was looked up in"
41        );
42        shader.set_float_at(self.shader_index, val);
43    }
44
45    /// VisibleForTesting: This is the index of this uniform in the shader's float uniform buffer.
46    pub fn shader_index(self) -> usize {
47        self.shader_index
48    }
49
50    /// The offset into the bound uniform. For example, 1 for `.y` or 2 for `.b`.
51    pub fn index(self) -> usize {
52        self.index
53    }
54}
55
56/// A binding to a uniform of type vec2. Calling [`set`](Self::set) on this object updates the
57/// uniform's value.
58///
59/// See also: [`FragmentShader::get_uniform_vec2`].
60#[derive(Clone, Copy, Debug)]
61pub struct UniformVec2Slot {
62    x_slot: UniformFloatSlot,
63    y_slot: UniformFloatSlot,
64}
65
66impl UniformVec2Slot {
67    /// Set the float value of the bound uniform.
68    pub fn set(self, shader: &mut FragmentShader, x: f64, y: f64) {
69        self.x_slot.set(shader, x);
70        self.y_slot.set(shader, y);
71    }
72}
73
74/// A binding to a uniform of type vec3. Calling [`set`](Self::set) on this object updates the
75/// uniform's value.
76///
77/// See also: [`FragmentShader::get_uniform_vec3`].
78#[derive(Clone, Copy, Debug)]
79pub struct UniformVec3Slot {
80    x_slot: UniformFloatSlot,
81    y_slot: UniformFloatSlot,
82    z_slot: UniformFloatSlot,
83}
84
85impl UniformVec3Slot {
86    /// Set the float value of the bound uniform.
87    pub fn set(self, shader: &mut FragmentShader, x: f64, y: f64, z: f64) {
88        self.x_slot.set(shader, x);
89        self.y_slot.set(shader, y);
90        self.z_slot.set(shader, z);
91    }
92}
93
94/// A binding to a uniform of type vec4. Calling [`set`](Self::set) on this object updates the
95/// uniform's value.
96///
97/// See also: [`FragmentShader::get_uniform_vec4`].
98#[derive(Clone, Copy, Debug)]
99pub struct UniformVec4Slot {
100    x_slot: UniformFloatSlot,
101    y_slot: UniformFloatSlot,
102    z_slot: UniformFloatSlot,
103    w_slot: UniformFloatSlot,
104}
105
106impl UniformVec4Slot {
107    /// Set the float value of the bound uniform.
108    pub fn set(self, shader: &mut FragmentShader, x: f64, y: f64, z: f64, w: f64) {
109        self.x_slot.set(shader, x);
110        self.y_slot.set(shader, y);
111        self.z_slot.set(shader, z);
112        self.w_slot.set(shader, w);
113    }
114}
115
116/// A binding to a uniform of type mat2. Calling [`set`](Self::set) on this object updates the
117/// uniform's value.
118///
119/// See also: [`FragmentShader::get_uniform_mat2`].
120#[derive(Clone, Copy, Debug)]
121pub struct UniformMat2Slot {
122    /// `_m00`, `_m01`, `_m10`, `_m11`.
123    slots: [UniformFloatSlot; 4],
124}
125
126impl UniformMat2Slot {
127    /// Set the float value of the matrix in row-major order.
128    pub fn set(self, shader: &mut FragmentShader, m00: f64, m01: f64, m10: f64, m11: f64) {
129        set_all(&self.slots, shader, [m00, m01, m10, m11]);
130    }
131}
132
133/// A binding to a uniform of type mat3. Calling [`set`](Self::set) on this object updates the
134/// uniform's value.
135///
136/// See also: [`FragmentShader::get_uniform_mat3`].
137#[derive(Clone, Copy, Debug)]
138pub struct UniformMat3Slot {
139    /// `_m00` to `_m22`, row after row.
140    slots: [UniformFloatSlot; 9],
141}
142
143impl UniformMat3Slot {
144    /// Set the float value of the matrix in row-major order.
145    #[expect(
146        clippy::too_many_arguments,
147        reason = "Dart's nine entries, one argument each"
148    )]
149    pub fn set(
150        self,
151        shader: &mut FragmentShader,
152        m00: f64,
153        m01: f64,
154        m02: f64,
155        m10: f64,
156        m11: f64,
157        m12: f64,
158        m20: f64,
159        m21: f64,
160        m22: f64,
161    ) {
162        set_all(
163            &self.slots,
164            shader,
165            [m00, m01, m02, m10, m11, m12, m20, m21, m22],
166        );
167    }
168}
169
170/// A binding to a uniform of type mat4. Calling [`set`](Self::set) on this object updates the
171/// uniform's value.
172///
173/// See also: [`FragmentShader::get_uniform_mat4`].
174#[derive(Clone, Copy, Debug)]
175pub struct UniformMat4Slot {
176    /// `_m00` to `_m33`, row after row.
177    slots: [UniformFloatSlot; 16],
178}
179
180impl UniformMat4Slot {
181    /// Set the float value of the matrix in row-major order.
182    #[expect(
183        clippy::too_many_arguments,
184        reason = "Dart's sixteen entries, one argument each"
185    )]
186    pub fn set(
187        self,
188        shader: &mut FragmentShader,
189        m00: f64,
190        m01: f64,
191        m02: f64,
192        m03: f64,
193        m10: f64,
194        m11: f64,
195        m12: f64,
196        m13: f64,
197        m20: f64,
198        m21: f64,
199        m22: f64,
200        m23: f64,
201        m30: f64,
202        m31: f64,
203        m32: f64,
204        m33: f64,
205    ) {
206        set_all(
207            &self.slots,
208            shader,
209            [
210                m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33,
211            ],
212        );
213    }
214}
215
216/// Sets each of `slots` to the value beside it, in order.
217fn set_all<const N: usize>(
218    slots: &[UniformFloatSlot; N],
219    shader: &mut FragmentShader,
220    values: [f64; N],
221) {
222    for (slot, value) in slots.iter().zip(values) {
223        slot.set(shader, value);
224    }
225}
226
227/// An array of bindings to uniforms of the same type `T`. Access elements via `[]` and set them
228/// individually.
229///
230/// ```ignore
231/// let colors = shader.get_uniform_vec4_array("uColorArray")?;
232/// colors[0].set(&mut shader, 1.0, 0.0, 1.0, 0.3);
233/// ```
234///
235/// See also: [`FragmentShader::get_uniform_float_array`], how `UniformArray`s are acquired.
236#[derive(Clone, Debug)]
237pub struct UniformArray<T> {
238    elements: Vec<T>,
239}
240
241impl<T> UniformArray<T> {
242    /// The number of Uniforms in the UniformArray.
243    pub fn len(&self) -> usize {
244        self.elements.len()
245    }
246
247    /// Whether the array has no elements.
248    pub fn is_empty(&self) -> bool {
249        self.elements.is_empty()
250    }
251}
252
253/// Access an element of the UniformArray.
254impl<T> Index<usize> for UniformArray<T> {
255    type Output = T;
256
257    fn index(&self, index: usize) -> &T {
258        &self.elements[index]
259    }
260}
261
262/// A binding to a shader's image sampler. Calling [`set`](Self::set) on this object updates a
263/// sampler's bound image.
264#[derive(Clone, Copy, Debug)]
265pub struct ImageSamplerSlot {
266    /// The effect of the program the slot was looked up in.
267    program: u64,
268    shader_index: usize,
269}
270
271impl ImageSamplerSlot {
272    /// Set the [`Image`] value for the bound sampler associated with this slot, sampled at
273    /// [`FilterQuality::None`].
274    pub fn set(self, shader: &mut FragmentShader, val: &Image) {
275        debug_assert_eq!(
276            self.program,
277            shader.program.effect().id(),
278            "a slot sets a shader of the program it was looked up in"
279        );
280        shader.set_image_sampler(self.shader_index, val, FilterQuality::None);
281    }
282
283    /// VisibleForTesting: This is the index one would use with
284    /// [`FragmentShader::set_image_sampler`] for this sampler.
285    pub fn shader_index(self) -> usize {
286        self.shader_index
287    }
288}
289
290/// A [`Shader`] generated from a [`FragmentProgram`].
291///
292/// Instances of this class can be obtained from the [`FragmentProgram::fragment_shader`] method.
293/// The float uniforms list is initialized to the size expected by the shader and is zero-filled.
294/// Uniforms of float type can then be set by name with
295/// [`get_uniform_float`](Self::get_uniform_float), [`get_uniform_vec2`](Self::get_uniform_vec2),
296/// [`get_uniform_vec3`](Self::get_uniform_vec3), [`get_uniform_vec4`](Self::get_uniform_vec4),
297/// and related methods. Sampler uniforms are set by calling
298/// [`set_image_sampler`](Self::set_image_sampler).
299///
300/// A [`FragmentShader`] can be re-used, and this is an efficient way to avoid allocating and
301/// re-initializing the uniform buffer and samplers. However, if two [`FragmentShader`] objects
302/// with different float uniforms or samplers are required to exist simultaneously, they must be
303/// obtained from two different calls to [`FragmentProgram::fragment_shader`].
304///
305/// A paint draws with the shader as it is when the paint is made, `Shader::from(&shader)`.
306#[derive(Debug)]
307pub struct FragmentShader {
308    program: Arc<FragmentProgram>,
309    floats: Vec<f32>,
310    /// Each image sampler's image and how it is sampled; `None` until it is set.
311    samplers: Vec<Option<valo::EffectImage>>,
312}
313
314impl FragmentShader {
315    pub(crate) fn new(program: Arc<FragmentProgram>) -> FragmentShader {
316        FragmentShader {
317            floats: vec![0.0; program.uniform_float_count()],
318            samplers: vec![None; program.sampler_count()],
319            program,
320        }
321    }
322
323    /// Sets the float uniform at `index` to `value`.
324    ///
325    /// Deprecated: Prefer setting uniforms by name with
326    /// [`get_uniform_float`](Self::get_uniform_float),
327    /// [`get_uniform_vec2`](Self::get_uniform_vec2),
328    /// [`get_uniform_vec3`](Self::get_uniform_vec3),
329    /// [`get_uniform_vec4`](Self::get_uniform_vec4),
330    /// [`get_uniform_mat2`](Self::get_uniform_mat2),
331    /// [`get_uniform_mat3`](Self::get_uniform_mat3),
332    /// [`get_uniform_mat4`](Self::get_uniform_mat4), or their array counterparts such as
333    /// [`get_uniform_float_array`](Self::get_uniform_float_array). Those methods don't require
334    /// manually computing the index of each uniform and are robust to changes in the order or
335    /// layout of uniforms in the fragment program.
336    ///
337    /// The index for each uniform is determined by the order of the uniforms as defined in the
338    /// fragment program's uniform struct, ignoring any images, each counted by its floats packed
339    /// tightly. For data types that are composed of multiple floats such as a `vec4`, more than
340    /// one call to [`set_float`](Self::set_float) is required.
341    ///
342    /// For example, given the following uniforms in a fragment program:
343    ///
344    /// ```wgsl
345    /// struct Uniforms { uScale: f32, uMagnitude: vec2<f32>, uColor: vec4<f32> }
346    /// ```
347    ///
348    /// `uScale` is at index 0, `uMagnitude` occupies indices 1 and 2, and `uColor` occupies
349    /// indices 3 through 6, wherever WGSL places them in the struct's bytes.
350    ///
351    /// Any float uniforms that are left uninitialized will default to `0`.
352    ///
353    /// # Panics
354    ///
355    /// Where `index` is past the program's floats.
356    #[deprecated(
357        note = "Use get_uniform_float, get_uniform_vec2, get_uniform_vec3, get_uniform_vec4, or \
358                a related method to set uniforms by name instead. This feature was deprecated \
359                after v3.51.0-0.1.pre."
360    )]
361    pub fn set_float(&mut self, index: usize, value: f64) {
362        self.set_float_at(index, value);
363    }
364
365    /// Dart's `_setFloat`.
366    fn set_float_at(&mut self, index: usize, value: f64) {
367        self.floats[index] = value as f32;
368    }
369
370    /// Dart's `_getSlotsForUniform`.
371    fn get_slots_for_uniform(
372        &self,
373        name: &str,
374        size: usize,
375    ) -> Result<Vec<UniformFloatSlot>, UniformError> {
376        let (index, info_size) = self.program.get_uniform_float_info(name)?;
377        if info_size != size {
378            return Err(UniformError::WrongSize {
379                name: name.to_owned(),
380                size: info_size,
381                expected: size,
382            });
383        }
384        Ok((0..size).map(|i| self.slot(i, index + i)).collect())
385    }
386
387    /// The float slot of component `index` at `shader_index`.
388    fn slot(&self, index: usize, shader_index: usize) -> UniformFloatSlot {
389        UniformFloatSlot {
390            program: self.program.effect().id(),
391            shader_index,
392            index,
393        }
394    }
395
396    /// Access the float binding for uniform named `name` with optional offset `index`, 0 when
397    /// `None`. Example `index` values: 1 for `foo.y`, 2 for `foo.b`.
398    pub fn get_uniform_float(
399        &self,
400        name: &str,
401        index: Option<usize>,
402    ) -> Result<UniformFloatSlot, UniformError> {
403        let index = index.unwrap_or(0);
404        let (shader_index, size) = self.program.get_uniform_float_info(name)?;
405        if index >= size {
406            return Err(UniformError::IndexOutOfBounds {
407                name: name.to_owned(),
408                index,
409            });
410        }
411        Ok(self.slot(index, shader_index + index))
412    }
413
414    /// Access the float binding for a vec2 uniform named `name`.
415    pub fn get_uniform_vec2(&self, name: &str) -> Result<UniformVec2Slot, UniformError> {
416        let slots = self.get_slots_for_uniform(name, 2)?;
417        Ok(UniformVec2Slot {
418            x_slot: slots[0],
419            y_slot: slots[1],
420        })
421    }
422
423    /// Access the float binding for a vec3 uniform named `name`.
424    pub fn get_uniform_vec3(&self, name: &str) -> Result<UniformVec3Slot, UniformError> {
425        let slots = self.get_slots_for_uniform(name, 3)?;
426        Ok(UniformVec3Slot {
427            x_slot: slots[0],
428            y_slot: slots[1],
429            z_slot: slots[2],
430        })
431    }
432
433    /// Access the float binding for a vec4 uniform named `name`.
434    pub fn get_uniform_vec4(&self, name: &str) -> Result<UniformVec4Slot, UniformError> {
435        let slots = self.get_slots_for_uniform(name, 4)?;
436        Ok(UniformVec4Slot {
437            x_slot: slots[0],
438            y_slot: slots[1],
439            z_slot: slots[2],
440            w_slot: slots[3],
441        })
442    }
443
444    /// Access the float binding for a mat2 uniform named `name`.
445    pub fn get_uniform_mat2(&self, name: &str) -> Result<UniformMat2Slot, UniformError> {
446        let slots = self.get_slots_for_uniform(name, 4)?;
447        Ok(UniformMat2Slot {
448            slots: to_array(&slots),
449        })
450    }
451
452    /// Access the float binding for a mat3 uniform named `name`.
453    pub fn get_uniform_mat3(&self, name: &str) -> Result<UniformMat3Slot, UniformError> {
454        let slots = self.get_slots_for_uniform(name, 9)?;
455        Ok(UniformMat3Slot {
456            slots: to_array(&slots),
457        })
458    }
459
460    /// Access the float binding for a mat4 uniform named `name`.
461    pub fn get_uniform_mat4(&self, name: &str) -> Result<UniformMat4Slot, UniformError> {
462        let slots = self.get_slots_for_uniform(name, 16)?;
463        Ok(UniformMat4Slot {
464            slots: to_array(&slots),
465        })
466    }
467
468    /// Dart's `_getUniformArray`.
469    fn get_uniform_array<T>(
470        &self,
471        name: &str,
472        element_size: usize,
473        element_factory: impl Fn(&[UniformFloatSlot]) -> T,
474    ) -> Result<UniformArray<T>, UniformError> {
475        let (index, size) = self.program.get_uniform_float_info(name)?;
476        if size % element_size != 0 {
477            return Err(UniformError::NotAMultiple {
478                name: name.to_owned(),
479                size,
480                element_size,
481            });
482        }
483        let num_elements = size / element_size;
484        let elements = (0..num_elements)
485            .map(|i| {
486                let slots: Vec<UniformFloatSlot> = (0..element_size)
487                    .map(|j| self.slot(j, index + i * element_size + j))
488                    .collect();
489                element_factory(&slots)
490            })
491            .collect();
492        Ok(UniformArray { elements })
493    }
494
495    /// Access the binding for a float array uniform named `name`.
496    ///
497    /// WGSL keeps no float array in a uniform struct, so a GLSL `float uValues[8]` is an
498    /// `array<vec4<f32>, 2>`, whose eight floats this reads as eight elements.
499    pub fn get_uniform_float_array(
500        &self,
501        name: &str,
502    ) -> Result<UniformArray<UniformFloatSlot>, UniformError> {
503        self.get_uniform_array(name, 1, |components| components[0])
504    }
505
506    /// Access the binding for a vec2 array uniform named `name`.
507    pub fn get_uniform_vec2_array(
508        &self,
509        name: &str,
510    ) -> Result<UniformArray<UniformVec2Slot>, UniformError> {
511        self.get_uniform_array(name, 2, |components| UniformVec2Slot {
512            x_slot: components[0],
513            y_slot: components[1],
514        })
515    }
516
517    /// Access the binding for a vec3 array uniform named `name`.
518    pub fn get_uniform_vec3_array(
519        &self,
520        name: &str,
521    ) -> Result<UniformArray<UniformVec3Slot>, UniformError> {
522        self.get_uniform_array(name, 3, |components| UniformVec3Slot {
523            x_slot: components[0],
524            y_slot: components[1],
525            z_slot: components[2],
526        })
527    }
528
529    /// Access the binding for a vec4 array uniform named `name`.
530    pub fn get_uniform_vec4_array(
531        &self,
532        name: &str,
533    ) -> Result<UniformArray<UniformVec4Slot>, UniformError> {
534        self.get_uniform_array(name, 4, |components| UniformVec4Slot {
535            x_slot: components[0],
536            y_slot: components[1],
537            z_slot: components[2],
538            w_slot: components[3],
539        })
540    }
541
542    /// Access the binding for a mat2 array uniform named `name`.
543    pub fn get_uniform_mat2_array(
544        &self,
545        name: &str,
546    ) -> Result<UniformArray<UniformMat2Slot>, UniformError> {
547        self.get_uniform_array(name, 4, |components| UniformMat2Slot {
548            slots: to_array(components),
549        })
550    }
551
552    /// Access the binding for a mat3 array uniform named `name`.
553    pub fn get_uniform_mat3_array(
554        &self,
555        name: &str,
556    ) -> Result<UniformArray<UniformMat3Slot>, UniformError> {
557        self.get_uniform_array(name, 9, |components| UniformMat3Slot {
558            slots: to_array(components),
559        })
560    }
561
562    /// Access the binding for a mat4 array uniform named `name`.
563    pub fn get_uniform_mat4_array(
564        &self,
565        name: &str,
566    ) -> Result<UniformArray<UniformMat4Slot>, UniformError> {
567        self.get_uniform_array(name, 16, |components| UniformMat4Slot {
568            slots: to_array(components),
569        })
570    }
571
572    /// Access the [`ImageSamplerSlot`] binding associated with the sampler named `name`: the
573    /// texture's name in the WGSL, as its pair's sampler is named after it.
574    ///
575    /// The index provided to [`set_image_sampler`](Self::set_image_sampler) is the index of the
576    /// image defined in the fragment program, excluding all non-image uniforms.
577    pub fn get_image_sampler(&self, name: &str) -> Result<ImageSamplerSlot, UniformError> {
578        let index = self.program.get_image_sampler_index(name)?;
579        Ok(ImageSamplerSlot {
580            program: self.program.effect().id(),
581            shader_index: index,
582        })
583    }
584
585    /// Sets the sampler uniform at `index` to `image`.
586    ///
587    /// The index provided to [`set_image_sampler`](Self::set_image_sampler) is the index of the
588    /// image defined in the fragment program, excluding all non-image uniforms.
589    ///
590    /// The `filter_quality` argument sets the quality level used to sample the image; Flutter's
591    /// default is [`FilterQuality::None`].
592    ///
593    /// All the sampler uniforms that a shader expects must be provided before a paint is made
594    /// from it.
595    ///
596    /// # Panics
597    ///
598    /// Where `index` is past the program's images: "Sampler index out of bounds".
599    pub fn set_image_sampler(
600        &mut self,
601        index: usize,
602        image: &Image,
603        filter_quality: FilterQuality,
604    ) {
605        let Some(sampler) = self.samplers.get_mut(index) else {
606            panic!("Sampler index out of bounds");
607        };
608        *sampler = Some(valo::EffectImage {
609            image: Some(image.clone()),
610            sampling: filter_quality.to_valo(),
611        });
612    }
613
614    /// Dart's `_floats.length`.
615    pub(crate) fn float_count(&self) -> usize {
616        self.floats.len()
617    }
618
619    /// Dart's `_validateSamplers`: whether every image is set.
620    fn validate_samplers(&self) -> bool {
621        self.samplers.iter().all(Option::is_some)
622    }
623
624    /// Dart's `_validateImageFilter`: whether there is a first image, left for the filter's
625    /// input, and every other is set.
626    pub(crate) fn validate_image_filter(&self) -> bool {
627        match self.samplers.split_first() {
628            Some((_, others)) => others.iter().all(Option::is_some),
629            None => false,
630        }
631    }
632
633    /// The shader as a filter's: its floats and images now, its first image left for the
634    /// filter's input, sampled with `input_sampling`. `ReusableFragmentShader::as_image_filter`.
635    pub(crate) fn as_image_filter(&self, input_sampling: valo::Sampling) -> valo::RuntimeShader {
636        let mut images = self.effect_images();
637        if let Some(input) = images.first_mut() {
638            *input = valo::EffectImage {
639                image: None,
640                sampling: input_sampling,
641            };
642        }
643        self.runtime_shader(images)
644    }
645
646    /// The images, an unset one left empty.
647    fn effect_images(&self) -> Vec<valo::EffectImage> {
648        self.samplers
649            .iter()
650            .map(|sampler| {
651                sampler.clone().unwrap_or(valo::EffectImage {
652                    image: None,
653                    sampling: FilterQuality::None.to_valo(),
654                })
655            })
656            .collect()
657    }
658
659    /// The program's effect with the floats as they are now and `images`.
660    fn runtime_shader(&self, images: Vec<valo::EffectImage>) -> valo::RuntimeShader {
661        let uniforms = self.program.uniform_bytes(&self.floats);
662        valo::RuntimeShader::new(Arc::clone(self.program.effect()), uniforms, images)
663            .expect("a shader's floats and images are its program's")
664    }
665}
666
667/// The shader as a paint draws it, its floats and images copied now:
668/// `ReusableFragmentShader::shader`, as `Paint.shader` takes a `FragmentShader`.
669///
670/// # Panics
671///
672/// Where an image is not set, as Dart's `Paint.shader` setter throws in a debug build.
673impl From<&FragmentShader> for Shader {
674    fn from(shader: &FragmentShader) -> Shader {
675        assert!(
676            shader.validate_samplers(),
677            "Invalid FragmentShader: missing sampler"
678        );
679        Shader::runtime(shader.runtime_shader(shader.effect_images()))
680            .expect("a shader with every image set is a paint shader")
681    }
682}
683
684/// `slots` as an array of `N`, as the matrix slots hold them.
685fn to_array<const N: usize>(slots: &[UniformFloatSlot]) -> [UniformFloatSlot; N] {
686    slots
687        .try_into()
688        .expect("as many slots as the matrix has entries")
689}
690
691#[cfg(test)]
692mod tests {
693    //! Ported from the engine's `testing/dart/fragment_shader_test.dart`, its GLSL fixtures
694    //! (`lib/ui/fixtures/shaders`) written again in WGSL. WGSL keeps no `float` or `vec2` array in
695    //! a uniform struct, so those fixtures' arrays are arrays of `vec4`, the same floats.
696
697    use super::*;
698    use crate::painting::ImageFilter;
699
700    fn program(wgsl: &str) -> Arc<FragmentProgram> {
701        FragmentProgram::from_wgsl(wgsl).expect("a valid program")
702    }
703
704    const FLOAT_UNIFORM: &str = "
705struct U { color_r: f32 }
706@group(2) @binding(0) var<uniform> u: U;
707fn shade(position: vec2<f32>) -> vec4<f32> { return vec4<f32>(u.color_r, 0.0, 0.0, 1.0); }
708";
709
710    const VEC2_UNIFORM: &str = "
711struct U { color_rg: vec2<f32> }
712@group(2) @binding(0) var<uniform> u: U;
713fn shade(position: vec2<f32>) -> vec4<f32> { return vec4<f32>(u.color_rg, 0.0, 1.0); }
714";
715
716    const VEC3_UNIFORM: &str = "
717struct U { color_rgb: vec3<f32> }
718@group(2) @binding(0) var<uniform> u: U;
719fn shade(position: vec2<f32>) -> vec4<f32> { return vec4<f32>(u.color_rgb, 1.0); }
720";
721
722    const VEC4_UNIFORM: &str = "
723struct U { color_rgba: vec4<f32> }
724@group(2) @binding(0) var<uniform> u: U;
725fn shade(position: vec2<f32>) -> vec4<f32> { return u.color_rgba; }
726";
727
728    /// `uniforms.frag`: a uniform of each kind, the arrays after the ones it draws with.
729    const UNIFORMS: &str = "
730struct U {
731    iFloatUniform: f32,
732    iVec2Uniform: vec2<f32>,
733    iMat2Uniform: mat2x2<f32>,
734    iVec3Uniform: vec3<f32>,
735    iVec4Uniform: vec4<f32>,
736    iFloatArrayUniform: array<vec4<f32>, 3>,
737    iVec3ArrayUniform: array<vec3<f32>, 3>,
738}
739@group(2) @binding(0) var<uniform> u: U;
740fn shade(position: vec2<f32>) -> vec4<f32> {
741    return vec4<f32>(u.iFloatUniform, u.iVec2Uniform, u.iMat2Uniform[1][1]);
742}
743";
744
745    /// `uniform_ordering.frag`: floats around an image, which counts apart from them.
746    const UNIFORM_ORDERING: &str = "
747struct U { a: f32, b: f32, c: f32 }
748@group(2) @binding(0) var<uniform> u: U;
749@group(1) @binding(0) var u_texture: texture_2d<f32>;
750@group(1) @binding(1) var u_texture_sampler: sampler;
751fn shade(position: vec2<f32>) -> vec4<f32> {
752    let sampled = textureSampleLevel(u_texture, u_texture_sampler, vec2<f32>(0.5), 0.0);
753    if u.a == 1.0 && u.b == 2.0 && u.c == 3.0 {
754        return vec4<f32>(0.0, 1.0, 0.0, 1.0) + sampled * 0.0;
755    }
756    return vec4<f32>(1.0, 0.0, 0.0, 1.0);
757}
758";
759
760    /// `blue_green_sampler.frag`: the right edge of a half blue, half green image.
761    const BLUE_GREEN_SAMPLER: &str = "
762@group(1) @binding(0) var iChild: texture_2d<f32>;
763@group(1) @binding(1) var iChild_sampler: sampler;
764fn shade(position: vec2<f32>) -> vec4<f32> {
765    let color = textureSampleLevel(iChild, iChild_sampler, vec2<f32>(1.0, 0.0), 0.0);
766    return vec4<f32>(color.rgb, 1.0);
767}
768";
769
770    const NO_UNIFORMS: &str =
771        "fn shade(position: vec2<f32>) -> vec4<f32> { return vec4<f32>(0.0, 1.0, 0.0, 1.0); }";
772
773    /// `missing_size.frag`: an image, but no size first.
774    const MISSING_SIZE: &str = "
775@group(1) @binding(0) var u_texture: texture_2d<f32>;
776@group(1) @binding(1) var u_texture_sampler: sampler;
777fn shade(position: vec2<f32>) -> vec4<f32> {
778    return textureSampleLevel(u_texture, u_texture_sampler, position / vec2<f32>(100.0), 0.0).bgra;
779}
780";
781
782    /// `missing_texture.frag`: a size, but no image.
783    const MISSING_TEXTURE: &str = "
784struct U { u_size: vec2<f32> }
785@group(2) @binding(0) var<uniform> u: U;
786fn shade(position: vec2<f32>) -> vec4<f32> { return vec4<f32>(u.u_size.x, u.u_size.y, 0.0, 1.0); }
787";
788
789    /// `filter_shader.frag`: the input with its red and blue swapped.
790    const FILTER_SHADER: &str = "
791struct U { u_size: vec2<f32> }
792@group(2) @binding(0) var<uniform> u: U;
793@group(1) @binding(0) var u_texture: texture_2d<f32>;
794@group(1) @binding(1) var u_texture_sampler: sampler;
795fn shade(position: vec2<f32>) -> vec4<f32> {
796    return textureSampleLevel(u_texture, u_texture_sampler, position / u.u_size, 0.0).bgra;
797}
798";
799
800    /// Dart's `FragmentProgram uniform info`.
801    #[test]
802    fn a_slot_indexes_the_floats_packed_tightly() {
803        let shader = program(UNIFORMS).fragment_shader();
804        let slots = [
805            shader.get_uniform_float("iFloatUniform", None),
806            shader.get_uniform_float("iVec2Uniform", Some(0)),
807            shader.get_uniform_float("iVec2Uniform", Some(1)),
808            shader.get_uniform_float("iMat2Uniform", Some(0)),
809            shader.get_uniform_float("iMat2Uniform", Some(1)),
810            shader.get_uniform_float("iMat2Uniform", Some(2)),
811            shader.get_uniform_float("iMat2Uniform", Some(3)),
812        ];
813        for (i, slot) in slots.into_iter().enumerate() {
814            assert_eq!(slot.expect("a float slot").shader_index(), i);
815        }
816    }
817
818    /// Dart's `getUniformFloat offset overflow`; an underflow is not a `usize`.
819    #[test]
820    fn a_float_slot_past_the_uniform_is_out_of_bounds() {
821        let shader = program(FLOAT_UNIFORM).fragment_shader();
822        let error = shader
823            .get_uniform_float("color_r", Some(2))
824            .expect_err("past the uniform");
825        assert_eq!(error.to_string(), "Index `2` out of bounds for `color_r`.");
826    }
827
828    /// Dart's `wrong datatype` cases, each asking a slot of another size than the uniform's.
829    #[test]
830    fn a_slot_of_another_size_is_refused() {
831        let vec2 = program(VEC2_UNIFORM).fragment_shader();
832        let vec3 = program(VEC3_UNIFORM).fragment_shader();
833        let vec4 = program(VEC4_UNIFORM).fragment_shader();
834        let message = |error: UniformError| error.to_string();
835        assert!(
836            message(vec3.get_uniform_vec2("color_rgb").unwrap_err())
837                .contains("`color_rgb` has size 3, not size 2.")
838        );
839        assert!(
840            message(vec2.get_uniform_vec3("color_rg").unwrap_err())
841                .contains("`color_rg` has size 2, not size 3.")
842        );
843        assert!(
844            message(vec3.get_uniform_vec4("color_rgb").unwrap_err())
845                .contains("`color_rgb` has size 3, not size 4.")
846        );
847        assert!(
848            message(vec3.get_uniform_mat2("color_rgb").unwrap_err())
849                .contains("`color_rgb` has size 3, not size 4.")
850        );
851        assert!(
852            message(vec3.get_uniform_mat3("color_rgb").unwrap_err())
853                .contains("Uniform `color_rgb` has size 3, not size 9.")
854        );
855        assert!(
856            message(vec3.get_uniform_mat4("color_rgb").unwrap_err())
857                .contains("Uniform `color_rgb` has size 3, not size 16.")
858        );
859        assert!(
860            message(vec3.get_uniform_vec2_array("color_rgb").unwrap_err())
861                .contains("Uniform size (3) for \"color_rgb\" is not a multiple of 2.")
862        );
863        assert!(
864            message(vec4.get_uniform_vec3_array("color_rgba").unwrap_err())
865                .contains("Uniform size (4) for \"color_rgba\" is not a multiple of 3.")
866        );
867        for (array, size) in [
868            (vec3.get_uniform_vec4_array("color_rgb").map(|_| ()), 4),
869            (vec3.get_uniform_mat2_array("color_rgb").map(|_| ()), 4),
870            (vec3.get_uniform_mat3_array("color_rgb").map(|_| ()), 9),
871            (vec3.get_uniform_mat4_array("color_rgb").map(|_| ()), 16),
872        ] {
873            assert!(message(array.unwrap_err()).contains(&format!(
874                "Uniform size (3) for \"color_rgb\" is not a multiple of {size}."
875            )));
876        }
877    }
878
879    /// Dart's `FragmentProgram getImageSampler`, `… unknown` and `… wrong type`.
880    #[test]
881    fn an_image_sampler_is_looked_up_by_its_textures_name() {
882        let shader = program(UNIFORM_ORDERING).fragment_shader();
883        let slot = shader.get_image_sampler("u_texture").expect("the image");
884        assert_eq!(slot.shader_index(), 0);
885        assert!(
886            shader
887                .get_image_sampler("unknown")
888                .unwrap_err()
889                .to_string()
890                .contains("No uniform named \"unknown\".")
891        );
892        assert!(
893            shader
894                .get_image_sampler("b")
895                .unwrap_err()
896                .to_string()
897                .contains("Uniform \"b\" is not an image sampler.")
898        );
899    }
900
901    /// Dart's `FragmentShader with sampler asserts if sampler is missing when assigned to paint`.
902    #[test]
903    #[should_panic(expected = "Invalid FragmentShader")]
904    fn a_paint_needs_every_image_set() {
905        let shader = program(BLUE_GREEN_SAMPLER).fragment_shader();
906        let _paint = Shader::from(&shader);
907    }
908
909    /// Dart's `ImageFilter.shader errors if shader does not have correct uniform layout`.
910    #[test]
911    fn a_shader_filter_needs_a_size_first_and_an_image() {
912        let cases = [
913            (NO_UNIFORMS, true, true),
914            (MISSING_SIZE, true, false),
915            (MISSING_TEXTURE, false, true),
916        ];
917        for (wgsl, float_error, sampler_error) in cases {
918            let shader = program(wgsl).fragment_shader();
919            let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
920                ImageFilter::shader(&shader, FilterQuality::None);
921            }))
922            .expect_err("the filter is refused");
923            let message = panicked
924                .downcast_ref::<String>()
925                .cloned()
926                .unwrap_or_default();
927            assert_eq!(
928                message.contains("shader has fewer than two float"),
929                float_error,
930                "{message}"
931            );
932            assert_eq!(
933                message.contains("shader is missing a sampler uniform"),
934                sampler_error,
935                "{message}"
936            );
937        }
938    }
939
940    /// Dart's `ImageFilter.shader equality checks consider uniform values`.
941    #[test]
942    #[expect(deprecated, reason = "Dart's test sets the float by index")]
943    fn a_shader_filter_equals_another_of_the_same_uniforms_and_quality() {
944        let mut shader = program(FILTER_SHADER).fragment_shader();
945        let filter = ImageFilter::shader(&shader, FilterQuality::None);
946        assert_eq!(filter, filter.clone());
947        assert_eq!(filter, ImageFilter::shader(&shader, FilterQuality::None));
948        let low_quality = ImageFilter::shader(&shader, FilterQuality::Low);
949        assert_ne!(filter, low_quality);
950        assert_eq!(
951            low_quality,
952            ImageFilter::shader(&shader, FilterQuality::Low)
953        );
954        shader.set_float(0, 1.0);
955        assert_ne!(filter, ImageFilter::shader(&shader, FilterQuality::None));
956    }
957
958    /// A slot keeps nothing of the shader it was looked up on, so the next frame's shader of the
959    /// same program takes the same slot.
960    #[test]
961    fn a_slot_sets_any_shader_of_its_program() {
962        let program = program(VEC4_UNIFORM);
963        let first = program.fragment_shader();
964        let color = first.get_uniform_vec4("color_rgba").expect("a vec4");
965        let mut next = program.fragment_shader();
966        color.set(&mut next, 0.1, 0.2, 0.3, 0.4);
967        assert_eq!(next.floats, [0.1, 0.2, 0.3, 0.4]);
968        assert_eq!(first.floats, [0.0; 4]);
969    }
970
971    #[cfg(feature = "test-support")]
972    mod drawn {
973        //! The engine's tests that draw: each through `drawPaint` into a small image, here a
974        //! rectangle of the shader over black, so an output that is not opaque reads back as its
975        //! premultiplied colour.
976
977        use super::*;
978        use crate::painting::{Canvas, Paint};
979        use crate::test_support::{drawn_pixels, image_from_pixels, picture_to_image};
980
981        /// The program's shader drawn over black into `width` by `height` pixels, its first row.
982        fn rendered(shader: &FragmentShader, width: u32, height: u32) -> Vec<[u8; 4]> {
983            let whole = valo::Rect::new(0.0, 0.0, width as f32, height as f32);
984            let mut canvas = Canvas::new();
985            canvas.draw_rect(whole, &Paint::from_color(valo::Color::BLACK));
986            canvas.draw_rect(whole, &Paint::from_shader(Shader::from(shader)));
987            let pixels = drawn_pixels(canvas.build(), [width, height]);
988            pixels.as_chunks::<4>().0[..width as usize].to_vec()
989        }
990
991        /// Dart's `_expectShaderRendersColor`, at its image dimension of 4.
992        fn expect_renders(shader: &FragmentShader, color: [u8; 4]) {
993            for pixel in rendered(shader, 4, 4) {
994                assert_eq!(pixel, color);
995            }
996        }
997
998        /// Dart's `_expectShaderRendersBarcode`, one colour a pixel, compared by red, green and
999        /// blue within 0.06.
1000        fn expect_barcode(shader: &FragmentShader, colors: &[[u8; 4]]) {
1001            let width = colors.len() as u32;
1002            for (i, (pixel, expected)) in rendered(shader, width, width)
1003                .iter()
1004                .zip(colors)
1005                .enumerate()
1006            {
1007                for channel in 0..3 {
1008                    let difference =
1009                        (f64::from(pixel[channel]) - f64::from(expected[channel])).abs() / 255.0;
1010                    assert!(
1011                        difference <= 0.06,
1012                        "colour {i}: {pixel:?}, expected {expected:?}"
1013                    );
1014                }
1015            }
1016        }
1017
1018        /// Dart's `Color.fromARGB` as red, green, blue and alpha bytes.
1019        const fn argb(a: u8, r: u8, g: u8, b: u8) -> [u8; 4] {
1020            [r, g, b, a]
1021        }
1022
1023        /// A channel as Dart's `Color.r` answers it.
1024        fn channel(value: u8) -> f64 {
1025            f64::from(value) / 255.0
1026        }
1027
1028        /// The channels of `colors` in order, red, green, blue and, with `alpha`, alpha.
1029        fn channels(colors: &[[u8; 4]], alpha: bool) -> Vec<f64> {
1030            let take = if alpha { 4 } else { 3 };
1031            colors
1032                .iter()
1033                .flat_map(|color| color[..take].iter().map(|&value| channel(value)))
1034                .collect()
1035        }
1036
1037        #[expect(deprecated, reason = "Dart's tests set the floats by index")]
1038        fn set_floats(shader: &mut FragmentShader, from: usize, values: &[f64]) {
1039            for (i, value) in values.iter().enumerate() {
1040                shader.set_float(from + i, *value);
1041            }
1042        }
1043
1044        const GREEN: [u8; 4] = [0, 255, 0, 255];
1045        const BLACK: [u8; 4] = [0, 0, 0, 255];
1046
1047        #[test]
1048        fn a_float_is_set_by_index_and_by_name() {
1049            let mut shader = program(FLOAT_UNIFORM).fragment_shader();
1050            set_floats(&mut shader, 0, &[1.0]);
1051            expect_renders(&shader, argb(255, 255, 0, 0));
1052            let color = argb(255, 50, 0, 0);
1053            shader
1054                .get_uniform_float("color_r", None)
1055                .unwrap()
1056                .set(&mut shader, channel(color[0]));
1057            expect_renders(&shader, color);
1058        }
1059
1060        #[test]
1061        fn a_vec2_is_set_by_index_and_by_name() {
1062            let mut shader = program(VEC2_UNIFORM).fragment_shader();
1063            set_floats(&mut shader, 0, &[1.0, 1.0]);
1064            expect_renders(&shader, argb(255, 255, 255, 0));
1065            let color = argb(255, 50, 50, 0);
1066            shader.get_uniform_vec2("color_rg").unwrap().set(
1067                &mut shader,
1068                channel(color[0]),
1069                channel(color[1]),
1070            );
1071            expect_renders(&shader, color);
1072        }
1073
1074        #[test]
1075        fn a_vec3_is_set_by_index_and_by_name() {
1076            let mut shader = program(VEC3_UNIFORM).fragment_shader();
1077            let color = argb(255, 67, 42, 12);
1078            set_floats(&mut shader, 0, &channels(&[color], false));
1079            expect_renders(&shader, color);
1080            let color = argb(255, 42, 67, 12);
1081            shader.get_uniform_vec3("color_rgb").unwrap().set(
1082                &mut shader,
1083                channel(color[0]),
1084                channel(color[1]),
1085                channel(color[2]),
1086            );
1087            expect_renders(&shader, color);
1088        }
1089
1090        #[test]
1091        fn a_vec4_is_set_by_index_and_by_name() {
1092            let mut shader = program(VEC4_UNIFORM).fragment_shader();
1093            let color = argb(255, 67, 42, 12);
1094            set_floats(&mut shader, 0, &channels(&[color], true));
1095            expect_renders(&shader, color);
1096            let color = argb(255, 12, 37, 27);
1097            shader.get_uniform_vec4("color_rgba").unwrap().set(
1098                &mut shader,
1099                channel(color[0]),
1100                channel(color[1]),
1101                channel(color[2]),
1102                channel(color[3]),
1103            );
1104            expect_renders(&shader, color);
1105        }
1106
1107        #[test]
1108        fn a_mat2_is_set_by_index_and_by_name() {
1109            let mut shader = program(
1110                "struct U { color_rgba: mat2x2<f32> }
1111                 @group(2) @binding(0) var<uniform> u: U;
1112                 fn shade(position: vec2<f32>) -> vec4<f32> {
1113                     return vec4<f32>(u.color_rgba[0], u.color_rgba[1]);
1114                 }",
1115            )
1116            .fragment_shader();
1117            let color = argb(255, 67, 42, 12);
1118            set_floats(&mut shader, 0, &channels(&[color], true));
1119            expect_renders(&shader, color);
1120            let color = argb(255, 12, 37, 27);
1121            shader.get_uniform_mat2("color_rgba").unwrap().set(
1122                &mut shader,
1123                channel(color[0]),
1124                channel(color[1]),
1125                channel(color[2]),
1126                channel(color[3]),
1127            );
1128            expect_renders(&shader, color);
1129        }
1130
1131        const MAT3_UNIFORM: &str = "
1132struct U { colors: mat3x3<f32> }
1133@group(2) @binding(0) var<uniform> u: U;
1134fn shade(position: vec2<f32>) -> vec4<f32> {
1135    let uv = position / 3.0;
1136    if uv.x < 0.3 { return vec4<f32>(u.colors[0], 1.0); }
1137    if uv.x < 0.6 { return vec4<f32>(u.colors[1], 1.0); }
1138    return vec4<f32>(u.colors[2], 1.0);
1139}
1140";
1141
1142        #[test]
1143        fn a_mat3_is_set_by_index_and_by_name() {
1144            let mut shader = program(MAT3_UNIFORM).fragment_shader();
1145            let colors = [
1146                argb(255, 67, 42, 12),
1147                argb(255, 11, 22, 96),
1148                argb(255, 8, 16, 67),
1149            ];
1150            set_floats(&mut shader, 0, &channels(&colors, false));
1151            expect_barcode(&shader, &colors);
1152            let colors = [colors[1], colors[2], colors[0]];
1153            let c = channels(&colors, false);
1154            shader.get_uniform_mat3("colors").unwrap().set(
1155                &mut shader,
1156                c[0],
1157                c[1],
1158                c[2],
1159                c[3],
1160                c[4],
1161                c[5],
1162                c[6],
1163                c[7],
1164                c[8],
1165            );
1166            expect_barcode(&shader, &colors);
1167        }
1168
1169        const MAT4_UNIFORM: &str = "
1170struct U { colors: mat4x4<f32> }
1171@group(2) @binding(0) var<uniform> u: U;
1172fn shade(position: vec2<f32>) -> vec4<f32> {
1173    let uv = position / 4.0;
1174    if uv.x < 0.25 { return u.colors[0]; }
1175    if uv.x < 0.5 { return u.colors[1]; }
1176    if uv.x < 0.75 { return u.colors[2]; }
1177    return u.colors[3];
1178}
1179";
1180
1181        #[test]
1182        fn a_mat4_is_set_by_index_and_by_name() {
1183            let mut shader = program(MAT4_UNIFORM).fragment_shader();
1184            let colors = [
1185                argb(6, 67, 42, 12),
1186                argb(33, 11, 22, 96),
1187                argb(99, 8, 16, 67),
1188                argb(120, 11, 22, 96),
1189            ];
1190            set_floats(&mut shader, 0, &channels(&colors, true));
1191            expect_barcode(&shader, &colors);
1192            let colors = [
1193                argb(78, 11, 22, 96),
1194                argb(255, 8, 16, 67),
1195                argb(99, 11, 22, 96),
1196                argb(46, 67, 42, 12),
1197            ];
1198            let c = channels(&colors, true);
1199            shader.get_uniform_mat4("colors").unwrap().set(
1200                &mut shader,
1201                c[0],
1202                c[1],
1203                c[2],
1204                c[3],
1205                c[4],
1206                c[5],
1207                c[6],
1208                c[7],
1209                c[8],
1210                c[9],
1211                c[10],
1212                c[11],
1213                c[12],
1214                c[13],
1215                c[14],
1216                c[15],
1217            );
1218            expect_barcode(&shader, &colors);
1219        }
1220
1221        #[test]
1222        fn a_float_array_is_set_by_index_and_by_name() {
1223            let mut shader = program(
1224                "struct U { color_array: array<vec4<f32>, 1> }
1225                 @group(2) @binding(0) var<uniform> u: U;
1226                 fn shade(position: vec2<f32>) -> vec4<f32> { return u.color_array[0]; }",
1227            )
1228            .fragment_shader();
1229            let color = argb(255, 11, 22, 96);
1230            set_floats(&mut shader, 0, &channels(&[color], true));
1231            expect_renders(&shader, color);
1232            let color = argb(255, 96, 11, 22);
1233            let color_rgba = shader.get_uniform_float_array("color_array").unwrap();
1234            assert_eq!(color_rgba.len(), 4);
1235            for (i, value) in channels(&[color], true).into_iter().enumerate() {
1236                color_rgba[i].set(&mut shader, value);
1237            }
1238            expect_renders(&shader, color);
1239        }
1240
1241        #[test]
1242        fn a_vec2_array_is_set_by_index_and_by_name() {
1243            let mut shader = program(
1244                "struct U { color_array: array<vec4<f32>, 1> }
1245                 @group(2) @binding(0) var<uniform> u: U;
1246                 fn shade(position: vec2<f32>) -> vec4<f32> {
1247                     return vec4<f32>(u.color_array[0].xy, u.color_array[0].zw);
1248                 }",
1249            )
1250            .fragment_shader();
1251            let color = argb(255, 67, 42, 12);
1252            set_floats(&mut shader, 0, &channels(&[color], true));
1253            expect_renders(&shader, color);
1254            let color = argb(255, 1, 73, 26);
1255            let c = channels(&[color], true);
1256            let color_rgba = shader.get_uniform_vec2_array("color_array").unwrap();
1257            color_rgba[0].set(&mut shader, c[0], c[1]);
1258            color_rgba[1].set(&mut shader, c[2], c[3]);
1259            expect_renders(&shader, color);
1260        }
1261
1262        #[test]
1263        fn a_vec3_array_is_set_by_index_and_by_name() {
1264            let mut shader = program(
1265                "struct U { u_size: vec2<f32>, color_array: array<vec3<f32>, 2> }
1266                 @group(2) @binding(0) var<uniform> u: U;
1267                 fn shade(position: vec2<f32>) -> vec4<f32> {
1268                     let uv = position / u.u_size;
1269                     if uv.x < 0.5 { return vec4<f32>(u.color_array[0], 1.0); }
1270                     return vec4<f32>(u.color_array[1], 1.0);
1271                 }",
1272            )
1273            .fragment_shader();
1274            let colors = [argb(255, 67, 42, 12), argb(255, 11, 22, 96)];
1275            set_floats(&mut shader, 0, &[2.0, 2.0]);
1276            set_floats(&mut shader, 2, &channels(&colors, false));
1277            expect_barcode(&shader, &colors);
1278            let colors = [colors[1], colors[0]];
1279            let c = channels(&colors, false);
1280            shader
1281                .get_uniform_vec2("u_size")
1282                .unwrap()
1283                .set(&mut shader, 2.0, 2.0);
1284            let gpu_colors = shader.get_uniform_vec3_array("color_array").unwrap();
1285            gpu_colors[0].set(&mut shader, c[0], c[1], c[2]);
1286            gpu_colors[1].set(&mut shader, c[3], c[4], c[5]);
1287            expect_barcode(&shader, &colors);
1288        }
1289
1290        #[test]
1291        fn a_vec4_array_is_set_by_index_and_by_name() {
1292            let mut shader = program(
1293                "struct U { u_size: vec2<f32>, color_array: array<vec4<f32>, 2> }
1294                 @group(2) @binding(0) var<uniform> u: U;
1295                 fn shade(position: vec2<f32>) -> vec4<f32> {
1296                     let uv = position / u.u_size;
1297                     if uv.x < 0.5 { return u.color_array[0]; }
1298                     return u.color_array[1];
1299                 }",
1300            )
1301            .fragment_shader();
1302            let colors = [argb(77, 67, 42, 12), argb(51, 11, 22, 96)];
1303            set_floats(&mut shader, 0, &[2.0, 2.0]);
1304            set_floats(&mut shader, 2, &channels(&colors, true));
1305            expect_barcode(&shader, &colors);
1306            let colors = [argb(51, 11, 22, 96), argb(77, 67, 42, 12)];
1307            let c = channels(&colors, true);
1308            shader
1309                .get_uniform_vec2("u_size")
1310                .unwrap()
1311                .set(&mut shader, 2.0, 2.0);
1312            let gpu_colors = shader.get_uniform_vec4_array("color_array").unwrap();
1313            gpu_colors[0].set(&mut shader, c[0], c[1], c[2], c[3]);
1314            gpu_colors[1].set(&mut shader, c[4], c[5], c[6], c[7]);
1315            expect_barcode(&shader, &colors);
1316        }
1317
1318        #[test]
1319        fn a_mat2_array_is_set_by_index_and_by_name() {
1320            let mut shader = program(
1321                "struct U { colors: array<mat2x2<f32>, 2> }
1322                 @group(2) @binding(0) var<uniform> u: U;
1323                 fn shade(position: vec2<f32>) -> vec4<f32> {
1324                     if position.x < 1.0 { return vec4<f32>(u.colors[0][0], u.colors[0][1]); }
1325                     return vec4<f32>(u.colors[1][0], u.colors[1][1]);
1326                 }",
1327            )
1328            .fragment_shader();
1329            let colors = [argb(77, 67, 42, 12), argb(51, 11, 22, 96)];
1330            set_floats(&mut shader, 0, &channels(&colors, true));
1331            expect_barcode(&shader, &colors);
1332            let colors = [argb(51, 11, 22, 96), argb(77, 67, 42, 12)];
1333            let c = channels(&colors, true);
1334            let gpu_colors = shader.get_uniform_mat2_array("colors").unwrap();
1335            gpu_colors[0].set(&mut shader, c[0], c[1], c[2], c[3]);
1336            gpu_colors[1].set(&mut shader, c[4], c[5], c[6], c[7]);
1337            expect_barcode(&shader, &colors);
1338        }
1339
1340        #[test]
1341        fn a_mat3_array_is_set_by_index_and_by_name() {
1342            let mut shader = program(
1343                "struct U { colors: array<mat3x3<f32>, 2> }
1344                 @group(2) @binding(0) var<uniform> u: U;
1345                 fn shade(position: vec2<f32>) -> vec4<f32> {
1346                     let column = u32(position.x);
1347                     return vec4<f32>(u.colors[column / 3u][column % 3u], 1.0);
1348                 }",
1349            )
1350            .fragment_shader();
1351            let colors = [
1352                argb(255, 67, 42, 12),
1353                argb(255, 11, 22, 96),
1354                argb(255, 2, 4, 6),
1355                argb(255, 8, 10, 12),
1356                argb(255, 14, 16, 18),
1357                argb(255, 20, 22, 24),
1358            ];
1359            set_floats(&mut shader, 0, &channels(&colors, false));
1360            expect_barcode(&shader, &colors);
1361            let colors = [
1362                colors[3], colors[4], colors[5], colors[0], colors[1], colors[2],
1363            ];
1364            let c = channels(&colors, false);
1365            let gpu_colors = shader.get_uniform_mat3_array("colors").unwrap();
1366            gpu_colors[0].set(
1367                &mut shader,
1368                c[0],
1369                c[1],
1370                c[2],
1371                c[3],
1372                c[4],
1373                c[5],
1374                c[6],
1375                c[7],
1376                c[8],
1377            );
1378            gpu_colors[1].set(
1379                &mut shader,
1380                c[9],
1381                c[10],
1382                c[11],
1383                c[12],
1384                c[13],
1385                c[14],
1386                c[15],
1387                c[16],
1388                c[17],
1389            );
1390            expect_barcode(&shader, &colors);
1391        }
1392
1393        #[test]
1394        fn a_mat4_array_is_set_by_index_and_by_name() {
1395            let mut shader = program(
1396                "struct U { colors: array<mat4x4<f32>, 2> }
1397                 @group(2) @binding(0) var<uniform> u: U;
1398                 fn shade(position: vec2<f32>) -> vec4<f32> {
1399                     let column = u32(position.x);
1400                     return u.colors[column / 4u][column % 4u];
1401                 }",
1402            )
1403            .fragment_shader();
1404            let colors = [
1405                argb(31, 8, 16, 67),
1406                argb(29, 11, 22, 96),
1407                argb(43, 32, 34, 36),
1408                argb(41, 26, 28, 30),
1409                argb(39, 20, 22, 24),
1410                argb(37, 14, 16, 18),
1411                argb(35, 8, 10, 12),
1412                argb(33, 2, 4, 6),
1413            ];
1414            set_floats(&mut shader, 0, &channels(&colors, true));
1415            expect_barcode(&shader, &colors);
1416            let colors = [
1417                colors[1], colors[0], colors[7], colors[6], colors[5], colors[4], colors[3],
1418                colors[2],
1419            ];
1420            let c = channels(&colors, true);
1421            let gpu_colors = shader.get_uniform_mat4_array("colors").unwrap();
1422            for (element, values) in c.as_chunks::<16>().0.iter().enumerate() {
1423                gpu_colors[element].set(
1424                    &mut shader,
1425                    values[0],
1426                    values[1],
1427                    values[2],
1428                    values[3],
1429                    values[4],
1430                    values[5],
1431                    values[6],
1432                    values[7],
1433                    values[8],
1434                    values[9],
1435                    values[10],
1436                    values[11],
1437                    values[12],
1438                    values[13],
1439                    values[14],
1440                    values[15],
1441                );
1442            }
1443            expect_barcode(&shader, &colors);
1444        }
1445
1446        /// A 10x10 image whose left half is blue and right half green, from pixels: Dart's
1447        /// `_createBlueGreenImage`.
1448        fn blue_green_image() -> Image {
1449            let mut pixels = Vec::new();
1450            for _y in 0..10 {
1451                for x in 0..10 {
1452                    let blue_or_green: [u8; 4] = if x < 5 {
1453                        [0, 0, 255, 255]
1454                    } else {
1455                        [0, 255, 0, 255]
1456                    };
1457                    pixels.extend(blue_or_green);
1458                }
1459            }
1460            image_from_pixels([10, 10], &pixels)
1461        }
1462
1463        /// The same image drawn from a picture: Dart's `_createBlueGreenImageSync`.
1464        fn blue_green_image_sync() -> Image {
1465            let mut canvas = Canvas::new();
1466            canvas.draw_rect(
1467                valo::Rect::new(0.0, 0.0, 5.0, 10.0),
1468                &Paint::from_color(valo::Color::rgb(0.0, 0.0, 1.0)),
1469            );
1470            canvas.draw_rect(
1471                valo::Rect::new(5.0, 0.0, 5.0, 10.0),
1472                &Paint::from_color(valo::Color::rgb(0.0, 1.0, 0.0)),
1473            );
1474            picture_to_image(&canvas.build(), [10, 10])
1475        }
1476
1477        /// Dart's `FragmentShader setSampler throws with out-of-bounds index`.
1478        #[test]
1479        #[should_panic(expected = "Sampler index out of bounds")]
1480        fn an_image_past_the_programs_is_refused() {
1481            let mut shader = program(BLUE_GREEN_SAMPLER).fragment_shader();
1482            shader.set_image_sampler(1, &blue_green_image(), FilterQuality::None);
1483        }
1484
1485        /// Dart's `FragmentShader blue-green image renders green`, and its `GPU image` case.
1486        #[test]
1487        fn an_image_is_sampled_whether_uploaded_or_drawn() {
1488            for image in [blue_green_image(), blue_green_image_sync()] {
1489                let mut shader = program(BLUE_GREEN_SAMPLER).fragment_shader();
1490                shader.set_image_sampler(0, &image, FilterQuality::None);
1491                expect_renders(&shader, GREEN);
1492            }
1493        }
1494
1495        /// Dart's `Reused FragmentShader simple shader renders correctly`, over `functions.frag`.
1496        #[test]
1497        fn a_shader_draws_again_with_its_new_floats() {
1498            let mut shader = program(
1499                "struct U { a: f32 }
1500                 @group(2) @binding(0) var<uniform> u: U;
1501                 fn add_a(x: f32) -> f32 { return x + u.a; }
1502                 fn pair_with_a(x: f32) -> vec2<f32> { return vec2<f32>(x, u.a); }
1503                 fn composed_function(x: f32) -> vec3<f32> { return vec3<f32>(add_a(x), pair_with_a(x)); }
1504                 fn multi_param(x: f32, y: f32, z: f32) -> f32 { return x * y * z * u.a; }
1505                 fn shade(position: vec2<f32>) -> vec4<f32> {
1506                     var x = add_a(0.0);
1507                     let v3 = composed_function(x);
1508                     x = multi_param(v3.x, v3.y, v3.z);
1509                     return vec4<f32>(0.0, x / 2.0, 0.0, 1.0);
1510                 }",
1511            )
1512            .fragment_shader();
1513            set_floats(&mut shader, 0, &[1.0]);
1514            expect_renders(&shader, GREEN);
1515            set_floats(&mut shader, 0, &[0.0]);
1516            expect_renders(&shader, BLACK);
1517        }
1518
1519        /// Dart's `FragmentShader Uniforms are sorted correctly`, over `uniforms_sorted.frag`'s
1520        /// uniforms: floats and vectors mixed, so WGSL pads between them.
1521        #[test]
1522        fn floats_set_in_order_reach_the_uniforms_in_order() {
1523            let mut shader = program(
1524                "struct U {
1525                     u_color: vec4<f32>,
1526                     u_alpha: f32,
1527                     u_sparkle_color: vec4<f32>,
1528                     u_sparkle_alpha: f32,
1529                     u_blur: f32,
1530                     u_center: vec2<f32>,
1531                     u_radius_scale: f32,
1532                     u_max_radius: f32,
1533                     u_resolution_scale: vec2<f32>,
1534                     u_noise_scale: vec2<f32>,
1535                     u_noise_phase: f32,
1536                     u_circle1: vec2<f32>,
1537                     u_circle2: vec2<f32>,
1538                     u_circle3: vec2<f32>,
1539                     u_rotation1: vec2<f32>,
1540                     u_rotation2: vec2<f32>,
1541                     u_rotation3: vec2<f32>,
1542                 }
1543                 @group(2) @binding(0) var<uniform> u: U;
1544                 fn shade(position: vec2<f32>) -> vec4<f32> {
1545                     if u.u_color.x > u.u_alpha || u.u_alpha > u.u_sparkle_color.x
1546                         || u.u_sparkle_color.x > u.u_sparkle_alpha || u.u_sparkle_alpha > u.u_blur
1547                         || u.u_blur > u.u_center.x || u.u_center.x > u.u_radius_scale
1548                         || u.u_radius_scale > u.u_max_radius
1549                         || u.u_max_radius > u.u_resolution_scale.x
1550                         || u.u_resolution_scale.x > u.u_noise_scale.x
1551                         || u.u_noise_scale.x > u.u_noise_phase || u.u_noise_phase > u.u_circle1.x
1552                         || u.u_circle1.x > u.u_circle2.x || u.u_circle2.x > u.u_circle3.x
1553                         || u.u_circle3.x > u.u_rotation1.x || u.u_rotation1.x > u.u_rotation2.x
1554                         || u.u_rotation2.x > u.u_rotation3.x {
1555                         return vec4<f32>(1.0, 0.0, 0.0, 1.0);
1556                     }
1557                     return vec4<f32>(0.0, 1.0, 0.0, 1.0);
1558                 }",
1559            )
1560            .fragment_shader();
1561            let ordered: Vec<f64> = (0..32).map(f64::from).collect();
1562            set_floats(&mut shader, 0, &ordered);
1563            expect_renders(&shader, GREEN);
1564        }
1565
1566        /// Dart's `FragmentShader Uniforms with interleaved textures are sorted`.
1567        #[test]
1568        fn floats_count_apart_from_the_images_between_them() {
1569            let mut shader = program(UNIFORM_ORDERING).fragment_shader();
1570            set_floats(&mut shader, 0, &[1.0, 2.0, 3.0]);
1571            shader.set_image_sampler(0, &blue_green_image_sync(), FilterQuality::None);
1572            expect_renders(&shader, GREEN);
1573        }
1574
1575        /// Dart's `FragmentShader fromAsset accepts a shader with no uniforms`.
1576        #[test]
1577        fn a_program_with_no_uniforms_draws() {
1578            expect_renders(&program(NO_UNIFORMS).fragment_shader(), GREEN);
1579        }
1580
1581        /// Dart's `FragmentShader with uniforms renders correctly`.
1582        #[test]
1583        fn the_floats_set_are_the_colour_drawn() {
1584            let mut shader = program(UNIFORMS).fragment_shader();
1585            set_floats(&mut shader, 0, &[0.0, 0.25, 0.75, 0.0, 0.0, 0.0, 1.0]);
1586            let pixel = rendered(&shader, 1, 1)[0];
1587            let epsilon = 0.5 / 255.0 + 1e-6;
1588            for (value, expected) in pixel.iter().zip([0.0, 0.25, 0.75, 1.0]) {
1589                assert!((channel(*value) - expected).abs() <= epsilon, "{pixel:?}");
1590            }
1591        }
1592
1593        /// Dart's `FragmentShader shader with mat2 uniform renders correctly`.
1594        #[test]
1595        fn a_mat2_set_by_index_is_read_column_by_column() {
1596            let mut shader = program(
1597                "struct U { uMat: mat2x2<f32> }
1598                 @group(2) @binding(0) var<uniform> u: U;
1599                 fn shade(position: vec2<f32>) -> vec4<f32> {
1600                     let m = u.uMat;
1601                     if abs(m[0][0] - 4.0) < 0.01 && abs(m[0][1] - 8.0) < 0.01
1602                         && abs(m[1][0] - 16.0) < 0.01 && abs(m[1][1] - 32.0) < 0.01 {
1603                         return vec4<f32>(0.0, 1.0, 0.0, 1.0);
1604                     }
1605                     return vec4<f32>(1.0, 0.0, 0.0, 1.0);
1606                 }",
1607            )
1608            .fragment_shader();
1609            set_floats(&mut shader, 0, &[4.0, 8.0, 16.0, 32.0]);
1610            expect_renders(&shader, GREEN);
1611        }
1612
1613        /// Dart's `ImageFilter.shader can be applied to canvas operations`: red through a filter
1614        /// that swaps red and blue is blue.
1615        #[test]
1616        fn a_shader_filter_filters_a_layer() {
1617            let shader = program(FILTER_SHADER).fragment_shader();
1618            let filter = ImageFilter::shader(&shader, FilterQuality::None);
1619            let mut canvas = Canvas::new();
1620            canvas.save_layer(
1621                None,
1622                &Paint {
1623                    image_filter: Some(filter.to_valo()),
1624                    ..Paint::default()
1625                },
1626            );
1627            canvas.draw_rect(
1628                valo::Rect::new(0.0, 0.0, 1.0, 1.0),
1629                &Paint::from_color(valo::Color::rgb(1.0, 0.0, 0.0)),
1630            );
1631            canvas.restore();
1632            let pixels = drawn_pixels(canvas.build(), [1, 1]);
1633            assert_eq!(pixels, [0, 0, 255, 255]);
1634        }
1635    }
1636}