Skip to main content

waft_embedder/
fragment_program.rs

1//! Flutter counterpart: dart:ui `FragmentProgram`, and the engine's
2//! `lib/ui/painting/fragment_program.cc` that reflects its uniforms.
3//!
4//! A program is WGSL in valo's form (`valo::RuntimeEffect`): one `shade` function, its uniforms
5//! one struct, its images texture and sampler pairs. Flutter's API counts a program's floats
6//! packed tightly in field order, as its GLSL declares them, while WGSL places each field at the
7//! alignment its type asks: in a struct of a `vec4`, a `vec4`, a `vec2`, an `f32` and a `vec2`,
8//! float 11 is at byte 48, not 44. The invariant a later editor must keep: a float index means
9//! what it means in Flutter, and [`FragmentProgram::uniform_bytes`] is the one place that maps
10//! it to WGSL's bytes, as Impeller's `padding_layout` does for its own backends.
11//!
12//! Every program made is listed for the hosts, which prepare each on their renderers before
13//! their next draw ([`PreparedPrograms`]), as the engine posts `CacheRuntimeStage` to its raster
14//! thread when a program loads.
15
16use std::fmt;
17use std::sync::{Arc, Mutex, Weak};
18
19use crate::FragmentShader;
20use crate::painting::valo;
21
22/// An instance of [`FragmentProgram`] creates [`Shader`](crate::Shader) objects (as used by
23/// [`Paint::shader`](crate::Paint)), through the [`FragmentShader`]s it hands out.
24#[derive(Debug)]
25pub struct FragmentProgram {
26    effect: Arc<valo::RuntimeEffect>,
27    /// The float uniforms in field order, each with its first index and its size in floats:
28    /// Dart's `_uniformInfo` as `_getUniformFloatInfo` reads it.
29    uniform_info: Vec<UniformFloatInfo>,
30    /// The byte in the uniform struct of each float index: what Impeller's `padding_layout`
31    /// spells out.
32    float_offsets: Vec<u32>,
33}
34
35/// One float uniform's place among the tightly packed floats: Dart's `_UniformFloatInfo`, with
36/// the name it is looked up by.
37#[derive(Debug)]
38struct UniformFloatInfo {
39    name: String,
40    index: usize,
41    size: usize,
42}
43
44impl FragmentProgram {
45    /// Creates a fragment program from WGSL in valo's form, a paint shader's: Flutter's
46    /// `FragmentProgram.fromAsset`, for a shader built into the code that uses it, typically
47    /// with `include_str!`.
48    ///
49    /// The constructed object should then be reused via the
50    /// [`fragment_shader`](Self::fragment_shader) method to create shader objects that can be
51    /// used by [`Paint::shader`](crate::Paint).
52    ///
53    /// # Errors
54    ///
55    /// Where naga rejects the WGSL, where it breaks valo's contract, or where a uniform is not
56    /// one Flutter's API sets: a float, a float vector or a square float matrix, or a
57    /// fixed-size array of one of those.
58    pub fn from_wgsl(wgsl: &str) -> Result<Arc<FragmentProgram>, valo::EffectError> {
59        let effect = valo::RuntimeEffect::shader(wgsl)?;
60        let (uniform_info, float_offsets) = float_layout(effect.uniforms())?;
61        list_for_the_hosts(&effect);
62        Ok(Arc::new(FragmentProgram {
63            effect,
64            uniform_info,
65            float_offsets,
66        }))
67    }
68
69    /// Returns a fresh instance of [`FragmentShader`].
70    pub fn fragment_shader(self: &Arc<Self>) -> FragmentShader {
71        FragmentShader::new(Arc::clone(self))
72    }
73
74    pub(crate) fn effect(&self) -> &Arc<valo::RuntimeEffect> {
75        &self.effect
76    }
77
78    /// Dart's `_uniformFloatCount`.
79    pub(crate) fn uniform_float_count(&self) -> usize {
80        self.float_offsets.len()
81    }
82
83    /// Dart's `_samplerCount`.
84    pub(crate) fn sampler_count(&self) -> usize {
85        self.effect.image_names().len()
86    }
87
88    /// Dart's `_hasUniform`.
89    fn has_uniform(&self, name: &str) -> bool {
90        self.uniform_info.iter().any(|entry| entry.name == name)
91            || self.effect.image_names().iter().any(|entry| entry == name)
92    }
93
94    /// Dart's `_getImageSamplerIndex`.
95    pub(crate) fn get_image_sampler_index(&self, name: &str) -> Result<usize, UniformError> {
96        match self
97            .effect
98            .image_names()
99            .iter()
100            .position(|entry| entry == name)
101        {
102            Some(index) => Ok(index),
103            None if self.has_uniform(name) => Err(UniformError::NotAnImageSampler {
104                name: name.to_owned(),
105            }),
106            None => Err(UniformError::NoUniform {
107                name: name.to_owned(),
108            }),
109        }
110    }
111
112    /// Dart's `_getUniformFloatInfo`: the first index of the uniform named `name` and its size,
113    /// both in floats.
114    pub(crate) fn get_uniform_float_info(
115        &self,
116        name: &str,
117    ) -> Result<(usize, usize), UniformError> {
118        self.uniform_info
119            .iter()
120            .find(|entry| entry.name == name)
121            .map(|entry| (entry.index, entry.size))
122            .ok_or_else(|| UniformError::NoUniform {
123                name: name.to_owned(),
124            })
125    }
126
127    /// `floats`, the program's tightly packed floats, laid out as WGSL lays out its uniform
128    /// struct, the padding zero: Impeller's `RuntimeEffectContents::EmplaceUniform`.
129    pub(crate) fn uniform_bytes(&self, floats: &[f32]) -> Vec<u8> {
130        let mut bytes = vec![0; self.effect.uniforms().size as usize];
131        for (value, &offset) in floats.iter().zip(&self.float_offsets) {
132            let at = offset as usize;
133            bytes[at..at + 4].copy_from_slice(&value.to_le_bytes());
134        }
135        bytes
136    }
137}
138
139/// Each float uniform of `uniforms` with its place among the tightly packed floats, and the byte
140/// of each of those floats in the struct.
141fn float_layout(
142    uniforms: &valo::UniformLayout,
143) -> Result<(Vec<UniformFloatInfo>, Vec<u32>), valo::EffectError> {
144    let mut uniform_info = Vec::new();
145    let mut float_offsets = Vec::new();
146    for field in &uniforms.fields {
147        let offsets = float_offsets_of(field)?;
148        uniform_info.push(UniformFloatInfo {
149            name: field.name.clone(),
150            index: float_offsets.len(),
151            size: offsets.len(),
152        });
153        float_offsets.extend(offsets);
154    }
155    Ok((uniform_info, float_offsets))
156}
157
158/// The byte of each of `field`'s floats in the uniform struct, in the order Flutter's tightly
159/// packed indices count them: an array's elements one after the other, a matrix's columns.
160fn float_offsets_of(field: &valo::UniformField) -> Result<Vec<u32>, valo::EffectError> {
161    let element = element_float_offsets(field.ty).ok_or_else(|| {
162        valo::EffectError::Contract(format!(
163            "`{}` is not a uniform a fragment program sets: those are floats, float vectors, \
164             square float matrices and fixed-size arrays of them",
165            field.name
166        ))
167    })?;
168    let (count, stride) = field
169        .array
170        .map_or((1, 0), |array| (array.count, array.stride));
171    Ok((0..count)
172        .flat_map(|item| {
173            element
174                .iter()
175                .map(move |offset| field.offset + item * stride + offset)
176        })
177        .collect())
178}
179
180/// Where each float of one value of `ty` lies from the value's start, as WGSL lays the type out
181/// in a uniform struct: a matrix column by column, each column a vector aligned as one.
182fn element_float_offsets(ty: valo::UniformType) -> Option<&'static [u32]> {
183    use valo::UniformType;
184    match ty {
185        UniformType::F32 => Some(&[0]),
186        UniformType::Vec2F => Some(&[0, 4]),
187        UniformType::Vec3F => Some(&[0, 4, 8]),
188        UniformType::Vec4F => Some(&[0, 4, 8, 12]),
189        UniformType::Mat2x2F => Some(&[0, 4, 8, 12]),
190        UniformType::Mat3x3F => Some(&[0, 4, 8, 16, 20, 24, 32, 36, 40]),
191        UniformType::Mat4x4F => {
192            Some(&[0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60])
193        }
194        UniformType::I32
195        | UniformType::U32
196        | UniformType::Vec2I
197        | UniformType::Vec2U
198        | UniformType::Other { .. } => None,
199    }
200}
201
202/// Why a uniform could not be looked up: the `ArgumentError`s and `IndexError`s Dart throws, each
203/// displayed with Dart's message.
204#[derive(Clone, Debug, PartialEq, Eq)]
205pub enum UniformError {
206    /// The program has no uniform of that name.
207    NoUniform { name: String },
208    /// The uniform has another number of floats than the slot asked for.
209    WrongSize {
210        name: String,
211        size: usize,
212        expected: usize,
213    },
214    /// A float slot past the uniform's floats.
215    IndexOutOfBounds { name: String, index: usize },
216    /// An array asked of a uniform whose floats do not divide into its elements.
217    NotAMultiple {
218        name: String,
219        size: usize,
220        element_size: usize,
221    },
222    /// An image sampler asked of a float uniform.
223    NotAnImageSampler { name: String },
224}
225
226impl fmt::Display for UniformError {
227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228        match self {
229            UniformError::NoUniform { name } => write!(f, "No uniform named \"{name}\"."),
230            UniformError::WrongSize {
231                name,
232                size,
233                expected,
234            } => write!(f, "Uniform `{name}` has size {size}, not size {expected}."),
235            UniformError::IndexOutOfBounds { name, index } => {
236                write!(f, "Index `{index}` out of bounds for `{name}`.")
237            }
238            UniformError::NotAMultiple {
239                name,
240                size,
241                element_size,
242            } => write!(
243                f,
244                "Uniform size ({size}) for \"{name}\" is not a multiple of {element_size}."
245            ),
246            UniformError::NotAnImageSampler { name } => {
247                write!(f, "Uniform \"{name}\" is not an image sampler.")
248            }
249        }
250    }
251}
252
253impl std::error::Error for UniformError {}
254
255/// The effects of every program made in this process, the first made first.
256static PROGRAMS_MADE: Mutex<Vec<Weak<valo::RuntimeEffect>>> = Mutex::new(Vec::new());
257
258/// Lists `effect` among the programs made, for each host's renderers to prepare.
259fn list_for_the_hosts(effect: &Arc<valo::RuntimeEffect>) {
260    PROGRAMS_MADE
261        .lock()
262        .expect("the list of programs made")
263        .push(Arc::downgrade(effect));
264}
265
266/// Which of the process's fragment programs one renderer has prepared: what a host keeps beside
267/// each renderer it draws with, to prepare every program made on it before its next draw, as the
268/// engine runs `CacheRuntimeStage` on its raster thread when a program loads.
269#[derive(Debug, Default)]
270pub struct PreparedPrograms {
271    /// How many of the programs made the renderer has been handed.
272    handed: usize,
273}
274
275impl PreparedPrograms {
276    /// A renderer that has prepared none.
277    pub fn new() -> PreparedPrograms {
278        PreparedPrograms::default()
279    }
280
281    /// Hands `prepare` the effect of each program made since the last call, the first made
282    /// first, leaving out those no one holds any longer: a host prepares each with
283    /// `valo::Context::prepare_runtime_effect` for the format it draws into.
284    pub fn prepare_new(&mut self, mut prepare: impl FnMut(&Arc<valo::RuntimeEffect>)) {
285        let made: Vec<Arc<valo::RuntimeEffect>> = {
286            let programs = PROGRAMS_MADE.lock().expect("the list of programs made");
287            let new = programs.get(self.handed..).unwrap_or_default();
288            self.handed = programs.len();
289            new.iter().filter_map(Weak::upgrade).collect()
290        };
291        for effect in &made {
292            prepare(effect);
293        }
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300
301    /// Material's ink sparkle's uniforms, in its GLSL file's order.
302    const INK_SPARKLE_UNIFORMS: &str = "
303struct Uniforms {
304    u_color: vec4<f32>,
305    u_composite_1: vec4<f32>,
306    u_center: vec2<f32>,
307    u_max_radius: f32,
308    u_resolution_scale: vec2<f32>,
309    u_noise_scale: vec2<f32>,
310    u_noise_phase: f32,
311    u_circle1: vec2<f32>,
312    u_circle2: vec2<f32>,
313    u_circle3: vec2<f32>,
314    u_rotation1: vec2<f32>,
315    u_rotation2: vec2<f32>,
316    u_rotation3: vec2<f32>,
317}
318@group(2) @binding(0) var<uniform> u: Uniforms;
319
320fn shade(position: vec2<f32>) -> vec4<f32> {
321    return u.u_color * u.u_composite_1.x + vec4<f32>(u.u_resolution_scale, u.u_rotation3);
322}
323";
324
325    /// Flutter's float 11, the first of `u_resolution_scale`, follows `u_max_radius` at float
326    /// 10, but WGSL aligns a `vec2` to eight bytes: it is at byte 48, not 44.
327    #[test]
328    fn a_float_index_lands_where_wgsl_lays_the_uniform_out() {
329        let program = FragmentProgram::from_wgsl(INK_SPARKLE_UNIFORMS).expect("valid program");
330        assert_eq!(program.uniform_float_count(), 28);
331        assert_eq!(
332            program.get_uniform_float_info("u_resolution_scale"),
333            Ok((11, 2))
334        );
335        let floats: Vec<f32> = (0..28).map(|index| index as f32).collect();
336        let bytes = program.uniform_bytes(&floats);
337        let float_at = |byte: usize| f32::from_le_bytes(bytes[byte..byte + 4].try_into().unwrap());
338        assert_eq!(float_at(40), 10.0, "u_max_radius");
339        assert_eq!(float_at(44), 0.0, "padding");
340        assert_eq!(float_at(48), 11.0, "u_resolution_scale.x");
341        assert_eq!(float_at(64), 15.0, "u_noise_phase");
342        assert_eq!(float_at(72), 16.0, "u_circle1.x");
343        assert_eq!(float_at(116), 27.0, "u_rotation3.y");
344        assert_eq!(bytes.len(), 128);
345    }
346
347    /// A `mat3x3` keeps each column in sixteen bytes, and an array its stride: Impeller's
348    /// padding layout of a GLSL `vec3` array.
349    #[test]
350    fn a_matrix_and_an_array_skip_their_padding() {
351        let program = FragmentProgram::from_wgsl(
352            "struct U { m: mat3x3<f32>, colors: array<vec3<f32>, 2>, last: f32 }
353             @group(2) @binding(0) var<uniform> u: U;
354             fn shade(position: vec2<f32>) -> vec4<f32> {
355                 return vec4<f32>(u.m[0] + u.colors[1], u.last);
356             }",
357        )
358        .expect("valid program");
359        assert_eq!(program.get_uniform_float_info("m"), Ok((0, 9)));
360        assert_eq!(program.get_uniform_float_info("colors"), Ok((9, 6)));
361        assert_eq!(program.get_uniform_float_info("last"), Ok((15, 1)));
362        assert_eq!(
363            program.float_offsets,
364            [0, 4, 8, 16, 20, 24, 32, 36, 40, 48, 52, 56, 64, 68, 72, 80]
365        );
366    }
367
368    #[test]
369    fn an_integer_uniform_is_not_one_a_program_sets() {
370        let error = FragmentProgram::from_wgsl(
371            "struct U { count: i32 }
372             @group(2) @binding(0) var<uniform> u: U;
373             fn shade(position: vec2<f32>) -> vec4<f32> { return vec4<f32>(f32(u.count)); }",
374        )
375        .expect_err("an integer uniform");
376        assert!(
377            matches!(&error, valo::EffectError::Contract(message) if message.contains("`count`")),
378            "{error}"
379        );
380    }
381
382    /// Dart's `fromAsset throws an exception on invalid data`.
383    #[test]
384    fn invalid_wgsl_is_refused_with_valos_message() {
385        assert!(matches!(
386            FragmentProgram::from_wgsl("fn shade(position: vec2<f32>) -> vec4<f32> { oops }"),
387            Err(valo::EffectError::Parse(_))
388        ));
389    }
390
391    #[test]
392    fn a_renderer_is_handed_each_program_once() {
393        let mut prepared = PreparedPrograms::new();
394        prepared.prepare_new(|_| {});
395        let program = FragmentProgram::from_wgsl(
396            "fn shade(position: vec2<f32>) -> vec4<f32> { return vec4<f32>(1.0); }",
397        )
398        .expect("valid program");
399        let mut handed = Vec::new();
400        prepared.prepare_new(|effect| handed.push(effect.id()));
401        assert!(handed.contains(&program.effect().id()));
402        let mut again = Vec::new();
403        prepared.prepare_new(|effect| again.push(effect.id()));
404        assert!(!again.contains(&program.effect().id()));
405    }
406}