cranpose-render-wgpu 0.24.0

GPU renderer for Cranpose scenes through wgpu
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
use std::borrow::Cow;
#[cfg(not(target_arch = "wasm32"))]
use std::sync::{Arc, OnceLock};

use crate::lazy_resource::LazyGpuResource;

#[cfg(not(target_arch = "wasm32"))]
static STAGES_FOLDED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

#[cfg(not(target_arch = "wasm32"))]
static STAGES_FLATTENED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// The pipeline stages this process built specialized and folded, each
/// carrying only the code its override constants keep.
pub fn shader_stages_folded() -> u64 {
    #[cfg(not(target_arch = "wasm32"))]
    {
        STAGES_FOLDED.load(std::sync::atomic::Ordering::Relaxed)
    }
    #[cfg(target_arch = "wasm32")]
    {
        0
    }
}

/// The folded stages this process also flattened: every call inlined and
/// every struct variable split into its members.
pub fn shader_stages_flattened() -> u64 {
    #[cfg(not(target_arch = "wasm32"))]
    {
        STAGES_FLATTENED.load(std::sync::atomic::Ordering::Relaxed)
    }
    #[cfg(target_arch = "wasm32")]
    {
        0
    }
}

/// A pipeline's two stages and the override constants it is built with.
pub(crate) struct Stages<'c> {
    pub(crate) vertex: wgpu::ShaderModule,
    pub(crate) fragment: wgpu::ShaderModule,
    pub(crate) constants: &'c [(&'c str, f64)],
}

impl Stages<'_> {
    // These stages at their `entries`, the vertex entry first.
    pub(crate) fn strip(
        &self,
        (vertex, fragment): (&'static str, &'static str),
    ) -> StripStages<'_> {
        StripStages {
            vertex: (&self.vertex, vertex),
            fragment: (&self.fragment, fragment),
            constants: self.constants,
        }
    }
}

// A strip pipeline's two stages, each a module and its entry point, and the
// override constants both read.
#[derive(Clone, Copy)]
pub(crate) struct StripStages<'a> {
    pub(crate) vertex: (&'a wgpu::ShaderModule, &'static str),
    pub(crate) fragment: (&'a wgpu::ShaderModule, &'static str),
    pub(crate) constants: &'a [(&'a str, f64)],
}

/// A shader's naga module and what validating it found, which each stage
/// is specialized from.
#[cfg(not(target_arch = "wasm32"))]
type Parsed = Option<(naga::Module, naga::valid::ModuleInfo)>;

/// A shader module's code: its WGSL, and on the web the GLSL templates of
/// its entry points, which a WebGL device builds its pipelines from without
/// running naga on the page.
#[derive(Clone, Copy)]
pub(crate) struct ShaderCode {
    wgsl: fn() -> Cow<'static, str>,
    #[cfg(all(target_arch = "wasm32", feature = "gl-templates"))]
    built_in: Option<BuiltIn>,
}

// A built-in module's name among the framework shaders, and the templates
// the build script wrote of it (`crate::gl_templates`).
#[cfg(all(target_arch = "wasm32", feature = "gl-templates"))]
#[derive(Clone, Copy)]
pub(crate) struct BuiltIn {
    pub(crate) name: &'static str,
    pub(crate) glsl: &'static [wgpu::hal::GlslTemplate],
}

impl ShaderCode {
    /// WGSL alone: written at run time, so no template covers it.
    pub(crate) const fn wgsl(wgsl: fn() -> Cow<'static, str>) -> Self {
        Self {
            wgsl,
            #[cfg(all(target_arch = "wasm32", feature = "gl-templates"))]
            built_in: None,
        }
    }

    /// A built-in module: its WGSL, its name and its templates.
    #[cfg(all(target_arch = "wasm32", feature = "gl-templates"))]
    pub(crate) const fn built_in(wgsl: fn() -> Cow<'static, str>, built_in: BuiltIn) -> Self {
        Self {
            wgsl,
            built_in: Some(built_in),
        }
    }

    /// The module of the templates, on a WebGL device.
    #[cfg(all(target_arch = "wasm32", feature = "gl-templates"))]
    fn template_module(
        &self,
        device: &wgpu::Device,
        backend: wgpu::Backend,
        label: &str,
    ) -> Option<wgpu::ShaderModule> {
        let built_in = self.built_in.filter(|_| backend == wgpu::Backend::Gl)?;
        device.create_shader_module_glsl_templates(Some(label), built_in.glsl)
    }

    fn wgsl_module(&self, device: &wgpu::Device, label: &str) -> wgpu::ShaderModule {
        device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some(label),
            source: wgpu::ShaderSource::Wgsl((self.wgsl)()),
        })
    }
}

/// One WGSL shader and the pipeline layout of every pipeline built from it.
/// The module is parsed once, by the first build that needs it, on whichever
/// thread: each pipeline keeps its module alive, and a module with override
/// constants keeps its parsed shader, so a module per pipeline would hold a
/// parse per variant. On a native device a pipeline with constants instead
/// takes its two stages specialized and folded from one naga parse (see
/// [`Self::stages`]): each holds only the code its constants keep.
#[derive(Clone)]
pub(crate) struct SharedShader {
    device: wgpu::Device,
    backend: wgpu::Backend,
    label: &'static str,
    code: ShaderCode,
    module: LazyGpuResource<wgpu::ShaderModule>,
    #[cfg(not(target_arch = "wasm32"))]
    parsed: Arc<OnceLock<Parsed>>,
    layout: wgpu::PipelineLayout,
}

impl SharedShader {
    pub(crate) fn new(
        device: &wgpu::Device,
        backend: wgpu::Backend,
        label: &'static str,
        code: ShaderCode,
        bind_group_layouts: &[Option<&wgpu::BindGroupLayout>],
    ) -> Self {
        Self {
            device: device.clone(),
            backend,
            label,
            code,
            module: LazyGpuResource::new(label),
            #[cfg(not(target_arch = "wasm32"))]
            parsed: Arc::default(),
            layout: device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some(label),
                bind_group_layouts,
                immediate_size: 0,
            }),
        }
    }

    /// The shader's module, made on the first call.
    pub(crate) fn module(&self) -> &wgpu::ShaderModule {
        self.module.get_or_init(self.backend, || {
            #[cfg(all(target_arch = "wasm32", feature = "gl-templates"))]
            if let Some(module) = self
                .code
                .template_module(&self.device, self.backend, self.label)
            {
                return module;
            }
            self.code.wgsl_module(&self.device, self.label)
        })
    }

    pub(crate) fn layout(&self) -> &wgpu::PipelineLayout {
        &self.layout
    }

    /// The two stages of a pipeline with `constants`, whose entry points are
    /// `vertex` and `fragment`. On a native device each is specialized by
    /// the constants and folded on its own (see [`cranpose_shader_passes::fold`]), so
    /// the driver compiles only the code they keep; on WebGL a program of the
    /// page's first-screen GLSL holds both alike (`crate::first_screen_glsl`).
    /// Elsewhere, or where naga refuses the shader, both share the module,
    /// which the device specializes.
    #[cfg_attr(
        all(target_arch = "wasm32", not(feature = "gl-templates")),
        expect(unused_variables, reason = "the web specializes the shared module")
    )]
    pub(crate) fn stages<'c>(
        &self,
        (vertex, fragment): (&str, &str),
        constants: &'c [(&'c str, f64)],
    ) -> Stages<'c> {
        #[cfg(all(target_arch = "wasm32", feature = "gl-templates"))]
        if let Some(built_in) = self.code.built_in
            && self.backend == wgpu::Backend::Gl
        {
            if let Some(list) = crate::first_screen_glsl::listing() {
                list(built_in.name, (vertex, fragment), constants);
            }
            if let Some(module) =
                crate::first_screen_glsl::program(built_in.name, (vertex, fragment), constants)
                    .and_then(|program| {
                        self.device
                            .create_shader_module_glsl_templates(Some(self.label), program)
                    })
            {
                return Stages {
                    vertex: module.clone(),
                    fragment: module,
                    constants: &[],
                };
            }
        }
        #[cfg(not(target_arch = "wasm32"))]
        if !constants.is_empty()
            && !cranpose_core::DIAGNOSTICS.no_shader_fold.equals("1")
            && let Some((vertex, fragment)) = self
                .folded(naga::ShaderStage::Vertex, vertex, constants)
                .zip(self.folded(naga::ShaderStage::Fragment, fragment, constants))
        {
            return Stages {
                vertex,
                fragment,
                constants: &[],
            };
        }
        let module = self.module().clone();
        Stages {
            vertex: module.clone(),
            fragment: module,
            constants,
        }
    }

    /// The shader parsed by naga once, by the first build that needs it.
    #[cfg(not(target_arch = "wasm32"))]
    fn parsed(&self) -> Option<&(naga::Module, naga::valid::ModuleInfo)> {
        self.parsed
            .get_or_init(|| {
                let source = (self.code.wgsl)();
                let module = naga::front::wgsl::parse_str(&source)
                    .inspect_err(|error| {
                        log::error!("[shader-fold] {} does not parse: {error}", self.label);
                    })
                    .ok()?;
                let info = naga::valid::Validator::new(
                    naga::valid::ValidationFlags::all(),
                    naga::valid::Capabilities::all(),
                )
                .validate(&module)
                .inspect_err(|error| {
                    log::error!("[shader-fold] {} does not validate: {error:?}", self.label);
                })
                .ok()?;
                Some((module, info))
            })
            .as_ref()
    }

    /// The `stage` of entry point `entry` with `constants`, specialized and
    /// folded into a module of its own, and flattened where wgpu takes the
    /// flattened module.
    #[cfg(not(target_arch = "wasm32"))]
    fn folded(
        &self,
        stage: naga::ShaderStage,
        entry: &str,
        constants: &[(&str, f64)],
    ) -> Option<wgpu::ShaderModule> {
        let mut module = self.specialized(stage, entry, constants)?;
        if !cranpose_core::DIAGNOSTICS.no_shader_flatten.equals("1") {
            match cranpose_shader_passes::flatten(&mut module) {
                Ok(()) => {
                    naga::compact::compact(&mut module, naga::compact::KeepUnused::No);
                    if let Some(shader) = self.created(module) {
                        STAGES_FOLDED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                        STAGES_FLATTENED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                        return Some(shader);
                    }
                    log::error!(
                        "[shader-flatten] {} {entry}: wgpu refused the flattened stage",
                        self.label
                    );
                }
                Err(error) => {
                    log::debug!(
                        "[shader-flatten] {} {entry} stays folded: {}",
                        self.label,
                        error.0
                    );
                }
            }
            // The passes left the module part flattened.
            module = self.specialized(stage, entry, constants)?;
        }
        naga::compact::compact(&mut module, naga::compact::KeepUnused::No);
        STAGES_FOLDED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        Some(
            self.device
                .create_shader_module(wgpu::ShaderModuleDescriptor {
                    label: Some(self.label),
                    source: wgpu::ShaderSource::Naga(Cow::Owned(module)),
                }),
        )
    }

    /// The `stage` of entry point `entry` specialized by `constants` and
    /// folded (see [`cranpose_shader_passes::fold`]).
    #[cfg(not(target_arch = "wasm32"))]
    fn specialized(
        &self,
        stage: naga::ShaderStage,
        entry: &str,
        constants: &[(&str, f64)],
    ) -> Option<naga::Module> {
        let (module, info) = self.parsed()?;
        let constants: naga::back::PipelineConstants = constants
            .iter()
            .map(|&(name, value)| (name.to_string(), value))
            .collect();
        let (specialized, _) = naga::back::pipeline_constants::process_overrides(
            module,
            info,
            Some((stage, entry)),
            &constants,
        )
        .inspect_err(|error| {
            log::error!(
                "[shader-fold] {} {entry} does not specialize: {error:?}",
                self.label
            );
        })
        .ok()?;
        let mut folded = specialized.into_owned();
        cranpose_shader_passes::fold(&mut folded);
        Some(folded)
    }

    /// The shader module of `module`, or `None` where wgpu's validation
    /// refuses it: wgpu validates a naga module as it creates it, and an
    /// error scope keeps that error from the device.
    #[cfg(not(target_arch = "wasm32"))]
    fn created(&self, module: naga::Module) -> Option<wgpu::ShaderModule> {
        let scope = self.device.push_error_scope(wgpu::ErrorFilter::Validation);
        let shader = self
            .device
            .create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some(self.label),
                source: wgpu::ShaderSource::Naga(Cow::Owned(module)),
            });
        // A native device reports the error as it creates the module, so
        // the scope's result is ready when popped.
        let mut popped = std::pin::pin!(scope.pop());
        let mut context = std::task::Context::from_waker(std::task::Waker::noop());
        match popped.as_mut().poll(&mut context) {
            std::task::Poll::Ready(None) => Some(shader),
            std::task::Poll::Ready(Some(error)) => {
                log::error!("[shader-flatten] {}: {error}", self.label);
                None
            }
            std::task::Poll::Pending => None,
        }
    }
}

#[cfg(test)]
#[path = "tests/shared_shader_tests.rs"]
mod tests;

/// A pipeline that draws one full-screen triangle strip from `fullscreen_vs`
/// into a single color target, the shape every effect and composite pass
/// shares; the stages' constants fix the shader's override constants.
pub(crate) fn create_fullscreen_strip_pipeline(
    device: &wgpu::Device,
    cache: Option<&wgpu::PipelineCache>,
    log_label: &str,
    label: &'static str,
    layout: &wgpu::PipelineLayout,
    stages: StripStages<'_>,
    (target, depth_stencil): (wgpu::ColorTargetState, Option<wgpu::DepthStencilState>),
) -> wgpu::RenderPipeline {
    let StripStages {
        vertex: (vertex_module, vertex_entry),
        fragment: (fragment_module, fragment_entry),
        constants,
    } = stages;
    crate::render::create_render_pipeline_logged(
        device,
        cache,
        log_label,
        wgpu::RenderPipelineDescriptor {
            label: Some(label),
            layout: Some(layout),
            vertex: wgpu::VertexState {
                module: vertex_module,
                entry_point: Some(vertex_entry),
                buffers: &[],
                compilation_options: wgpu::PipelineCompilationOptions {
                    constants,
                    ..wgpu::PipelineCompilationOptions::default()
                },
            },
            fragment: Some(wgpu::FragmentState {
                module: fragment_module,
                entry_point: Some(fragment_entry),
                targets: &[Some(target)],
                compilation_options: wgpu::PipelineCompilationOptions {
                    constants,
                    ..wgpu::PipelineCompilationOptions::default()
                },
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleStrip,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: None,
                ..Default::default()
            },
            depth_stencil,
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        },
    )
}