viewport-lib 0.19.0

3D viewport rendering library
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! GPU compute path for IBL precomputation.
//!
//! Three compute shaders replace the CPU reference port for the heavy parts of
//! `upload_environment_map`:
//!
//! - `ibl_irradiance.wgsl`: cosine-weighted hemisphere convolution
//! - `ibl_prefilter.wgsl` : GGX importance-sampled roughness convolution (per mip)
//! - `ibl_brdf_lut.wgsl`  : Hsplit-sum BRDF integration
//!
//! Selected at runtime via [`compute_supported`]. When unavailable, callers must
//! fall back to the CPU path in `environment.rs`.

use wgpu::util::DeviceExt;

const PREFILTER_PARAMS_SIZE: u64 = 16; // 4 floats (1 used, 3 pad) = 16 bytes

/// Return whether the device supports the storage-texture features the compute
/// path requires.
///
/// Currently gated on [`wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES`],
/// which is the WebGPU mechanism that exposes Rgba16Float storage-write access
/// on adapters that allow it. Consumers that want the fast IBL path should
/// include this feature in their `request_device` call.
pub(crate) fn compute_supported(device: &wgpu::Device) -> bool {
    device
        .features()
        .contains(wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES)
}

/// Upload the source HDR equirect as a sampleable Rgba16Float texture
/// (the input to the irradiance and prefilter compute dispatches).
fn upload_source(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    pixels: &[f32],
    width: u32,
    height: u32,
) -> wgpu::Texture {
    use rayon::prelude::*;
    let half: Vec<u16> = pixels
        .par_iter()
        .map(|&f| half::f16::from_f32(f).to_bits())
        .collect();
    let tex = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("ibl_skybox"),
        size: wgpu::Extent3d {
            width,
            height,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::Rgba16Float,
        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
        view_formats: &[],
    });
    queue.write_texture(
        wgpu::TexelCopyTextureInfo {
            texture: &tex,
            mip_level: 0,
            origin: wgpu::Origin3d::ZERO,
            aspect: wgpu::TextureAspect::All,
        },
        bytemuck::cast_slice(&half),
        wgpu::TexelCopyBufferLayout {
            offset: 0,
            bytes_per_row: Some(width * 8),
            rows_per_image: Some(height),
        },
        wgpu::Extent3d {
            width,
            height,
            depth_or_array_layers: 1,
        },
    );
    tex
}

/// Sampler shared by all compute dispatches that read the source equirect.
fn make_sampler(device: &wgpu::Device) -> wgpu::Sampler {
    crate::resources::builders::env_sampler(device, "ibl_compute_sampler")
}

/// BGL shared by irradiance + prefilter (params buffer is optional via
/// distinct BGLs in practice; we use two BGLs).
struct ConvolutionBgls {
    irradiance_bgl: wgpu::BindGroupLayout,
    prefilter_bgl: wgpu::BindGroupLayout,
    brdf_bgl: wgpu::BindGroupLayout,
}

fn make_bgls(device: &wgpu::Device) -> ConvolutionBgls {
    let irradiance_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        label: Some("ibl_irradiance_bgl"),
        entries: &[
            wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Texture {
                    sample_type: wgpu::TextureSampleType::Float { filterable: true },
                    view_dimension: wgpu::TextureViewDimension::D2,
                    multisampled: false,
                },
                count: None,
            },
            wgpu::BindGroupLayoutEntry {
                binding: 1,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                count: None,
            },
            wgpu::BindGroupLayoutEntry {
                binding: 2,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::StorageTexture {
                    access: wgpu::StorageTextureAccess::WriteOnly,
                    format: wgpu::TextureFormat::Rgba16Float,
                    view_dimension: wgpu::TextureViewDimension::D2,
                },
                count: None,
            },
        ],
    });

    let prefilter_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        label: Some("ibl_prefilter_bgl"),
        entries: &[
            wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Texture {
                    sample_type: wgpu::TextureSampleType::Float { filterable: true },
                    view_dimension: wgpu::TextureViewDimension::D2,
                    multisampled: false,
                },
                count: None,
            },
            wgpu::BindGroupLayoutEntry {
                binding: 1,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                count: None,
            },
            wgpu::BindGroupLayoutEntry {
                binding: 2,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::StorageTexture {
                    access: wgpu::StorageTextureAccess::WriteOnly,
                    format: wgpu::TextureFormat::Rgba16Float,
                    view_dimension: wgpu::TextureViewDimension::D2,
                },
                count: None,
            },
            wgpu::BindGroupLayoutEntry {
                binding: 3,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            },
        ],
    });

    let brdf_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        label: Some("ibl_brdf_bgl"),
        entries: &[wgpu::BindGroupLayoutEntry {
            binding: 0,
            visibility: wgpu::ShaderStages::COMPUTE,
            ty: wgpu::BindingType::StorageTexture {
                access: wgpu::StorageTextureAccess::WriteOnly,
                format: wgpu::TextureFormat::Rgba16Float,
                view_dimension: wgpu::TextureViewDimension::D2,
            },
            count: None,
        }],
    });

    ConvolutionBgls {
        irradiance_bgl,
        prefilter_bgl,
        brdf_bgl,
    }
}

/// Build the irradiance compute pipeline.
fn build_irradiance_pipeline(
    device: &wgpu::Device,
    bgl: &wgpu::BindGroupLayout,
) -> wgpu::ComputePipeline {
    let shader = crate::resources::builders::wgsl_module(
        device,
        "ibl_irradiance_shader",
        crate::resources::builders::wgsl_source!("ibl_irradiance"),
    );
    let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some("ibl_irradiance_layout"),
        bind_group_layouts: &[bgl],
        push_constant_ranges: &[],
    });
    crate::resources::builders::compute_pipeline(
        device,
        "ibl_irradiance_pipeline",
        &layout,
        &shader,
        "cs_main",
    )
}

fn build_prefilter_pipeline(
    device: &wgpu::Device,
    bgl: &wgpu::BindGroupLayout,
) -> wgpu::ComputePipeline {
    let shader = crate::resources::builders::wgsl_module(
        device,
        "ibl_prefilter_shader",
        crate::resources::builders::wgsl_source!("ibl_prefilter"),
    );
    let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some("ibl_prefilter_layout"),
        bind_group_layouts: &[bgl],
        push_constant_ranges: &[],
    });
    crate::resources::builders::compute_pipeline(
        device,
        "ibl_prefilter_pipeline",
        &layout,
        &shader,
        "cs_main",
    )
}

fn build_brdf_pipeline(
    device: &wgpu::Device,
    bgl: &wgpu::BindGroupLayout,
) -> wgpu::ComputePipeline {
    let shader = crate::resources::builders::wgsl_module(
        device,
        "ibl_brdf_lut_shader",
        crate::resources::builders::wgsl_source!("ibl_brdf_lut"),
    );
    let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some("ibl_brdf_lut_layout"),
        bind_group_layouts: &[bgl],
        push_constant_ranges: &[],
    });
    crate::resources::builders::compute_pipeline(
        device,
        "ibl_brdf_lut_pipeline",
        &layout,
        &shader,
        "cs_main",
    )
}

/// Result of a GPU IBL precomputation.
pub(crate) struct IblComputeResult {
    pub skybox_texture: wgpu::Texture,
    pub skybox_view: wgpu::TextureView,
    pub irradiance_texture: wgpu::Texture,
    pub irradiance_view: wgpu::TextureView,
    pub prefilter_texture: wgpu::Texture,
    pub prefilter_view: wgpu::TextureView,
    /// Generated only if requested (skipped when a cached LUT already exists).
    pub brdf_texture: Option<wgpu::Texture>,
    pub brdf_view: Option<wgpu::TextureView>,
    /// Submission index for the queue submit that ran the compute passes.
    /// Callers gate downstream work on this submission completing.
    pub submission: wgpu::SubmissionIndex,
}

/// Run the full IBL precomputation on the GPU.
///
/// If `compute_brdf` is `false`, the BRDF LUT step is skipped (caller is reusing
/// a previously-cached LUT).
pub(crate) fn compute_ibl(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    pixels: &[f32],
    width: u32,
    height: u32,
    compute_brdf: bool,
) -> IblComputeResult {
    let irr_w = 64u32;
    let irr_h = 32u32;
    let prefilter_w = 128u32;
    let prefilter_h = 64u32;
    let prefilter_mips = 5u32;
    let brdf_size = 128u32;

    // ----- Source skybox -----
    let skybox_texture = upload_source(device, queue, pixels, width, height);
    let skybox_view = skybox_texture.create_view(&wgpu::TextureViewDescriptor::default());

    // ----- Destination textures (Rgba16Float, STORAGE + TEXTURE binding) -----
    let irradiance_texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("ibl_irradiance"),
        size: wgpu::Extent3d {
            width: irr_w,
            height: irr_h,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::Rgba16Float,
        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::STORAGE_BINDING,
        view_formats: &[],
    });
    let irradiance_view = irradiance_texture.create_view(&wgpu::TextureViewDescriptor::default());

    let prefilter_texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("ibl_prefiltered"),
        size: wgpu::Extent3d {
            width: prefilter_w,
            height: prefilter_h,
            depth_or_array_layers: 1,
        },
        mip_level_count: prefilter_mips,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::Rgba16Float,
        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::STORAGE_BINDING,
        view_formats: &[],
    });
    let prefilter_view = prefilter_texture.create_view(&wgpu::TextureViewDescriptor::default());

    let sampler = make_sampler(device);
    let bgls = make_bgls(device);
    let irradiance_pipeline = build_irradiance_pipeline(device, &bgls.irradiance_bgl);
    let prefilter_pipeline = build_prefilter_pipeline(device, &bgls.prefilter_bgl);

    let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
        label: Some("ibl_compute_encoder"),
    });

    // ----- Irradiance dispatch -----
    {
        let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("ibl_irradiance_bg"),
            layout: &bgls.irradiance_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&skybox_view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::TextureView(&irradiance_view),
                },
            ],
        });
        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
            label: Some("ibl_irradiance_pass"),
            timestamp_writes: None,
        });
        pass.set_pipeline(&irradiance_pipeline);
        pass.set_bind_group(0, &bg, &[]);
        pass.dispatch_workgroups(irr_w.div_ceil(8), irr_h.div_ceil(8), 1);
    }

    // ----- Prefilter dispatches (one per mip) -----
    for mip in 0..prefilter_mips {
        let mip_w = (prefilter_w >> mip).max(1);
        let mip_h = (prefilter_h >> mip).max(1);
        let roughness = mip as f32 / (prefilter_mips - 1).max(1) as f32;

        let params = [roughness, 0.0f32, 0.0, 0.0];
        let params_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("ibl_prefilter_params"),
            contents: bytemuck::cast_slice(&params),
            usage: wgpu::BufferUsages::UNIFORM,
        });
        debug_assert_eq!(std::mem::size_of_val(&params) as u64, PREFILTER_PARAMS_SIZE);

        let mip_view = prefilter_texture.create_view(&wgpu::TextureViewDescriptor {
            label: Some("ibl_prefilter_mip_view"),
            base_mip_level: mip,
            mip_level_count: Some(1),
            ..Default::default()
        });

        let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("ibl_prefilter_bg"),
            layout: &bgls.prefilter_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&skybox_view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::TextureView(&mip_view),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: params_buf.as_entire_binding(),
                },
            ],
        });

        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
            label: Some("ibl_prefilter_pass"),
            timestamp_writes: None,
        });
        pass.set_pipeline(&prefilter_pipeline);
        pass.set_bind_group(0, &bg, &[]);
        pass.dispatch_workgroups(mip_w.div_ceil(8), mip_h.div_ceil(8), 1);
    }

    // ----- BRDF LUT (one-time) -----
    let (brdf_texture, brdf_view) = if compute_brdf {
        let brdf_pipeline = build_brdf_pipeline(device, &bgls.brdf_bgl);
        let brdf_tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ibl_brdf_lut"),
            size: wgpu::Extent3d {
                width: brdf_size,
                height: brdf_size,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba16Float,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::STORAGE_BINDING,
            view_formats: &[],
        });
        let brdf_v = brdf_tex.create_view(&wgpu::TextureViewDescriptor::default());

        let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("ibl_brdf_bg"),
            layout: &bgls.brdf_bgl,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: wgpu::BindingResource::TextureView(&brdf_v),
            }],
        });

        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
            label: Some("ibl_brdf_pass"),
            timestamp_writes: None,
        });
        pass.set_pipeline(&brdf_pipeline);
        pass.set_bind_group(0, &bg, &[]);
        pass.dispatch_workgroups(brdf_size.div_ceil(8), brdf_size.div_ceil(8), 1);
        drop(pass);

        (Some(brdf_tex), Some(brdf_v))
    } else {
        (None, None)
    };

    let submission = queue.submit(std::iter::once(encoder.finish()));

    // Callers gate on the returned submission index instead of blocking
    // here. The synchronous `upload_environment_map` wrapper drains the
    // upload-job runner until the matching job reports Ready.

    IblComputeResult {
        skybox_texture,
        skybox_view,
        irradiance_texture,
        irradiance_view,
        prefilter_texture,
        prefilter_view,
        brdf_texture,
        brdf_view,
        submission,
    }
}