viewport-lib 0.17.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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Plugin-facing accessors and pipeline builders on [`ViewportGpuResources`].
//!
//! See [`crate::plugin_api`] for the published types these methods return.

use crate::plugin_api::{
    MaskTargetDesc, OitTargetDesc, OpaqueTargetDesc, PickTargetDesc, ShadowTargetDesc,
    SharedBindings,
    target_desc::{OIT_ACCUM_BLEND, OIT_REVEAL_BLEND},
};
use crate::resources::ViewportGpuResources;

/// HDR colour format used by the scene buffer. Plugins targeting the HDR
/// path build pipelines against this format.
pub const HDR_COLOR_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;

/// Depth-stencil format shared by every scene render pass.
pub const SCENE_DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth24PlusStencil8;

/// Shadow atlas depth format.
pub const SHADOW_DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;

/// Outline-mask colour format.
pub const MASK_COLOR_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::R8Unorm;

/// Pick-id colour format.
pub const PICK_COLOR_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::R32Uint;

impl ViewportGpuResources {
    // ------------------------------------------------------------------
    // Target descriptors and SharedBindings accessor
    // ------------------------------------------------------------------

    /// Group-0 bind layout shared by every scene pipeline. Use as group 0
    /// when building a plugin pipeline layout.
    pub fn shared_bindings(&self) -> SharedBindings<'_> {
        SharedBindings {
            group0_layout: &self.camera_bind_group_layout,
        }
    }

    /// Render-target descriptor for the HDR opaque scene pass.
    pub fn opaque_target_desc(&self) -> OpaqueTargetDesc {
        OpaqueTargetDesc {
            color_format: HDR_COLOR_FORMAT,
            depth_format: SCENE_DEPTH_FORMAT,
            sample_count: self.sample_count,
        }
    }

    /// Render-target descriptor for the OIT pass (MRT: accum + reveal).
    pub fn oit_target_desc(&self) -> OitTargetDesc {
        OitTargetDesc {
            accum_format: HDR_COLOR_FORMAT,
            reveal_format: MASK_COLOR_FORMAT,
            depth_format: SCENE_DEPTH_FORMAT,
            accum_blend: OIT_ACCUM_BLEND,
            reveal_blend: OIT_REVEAL_BLEND,
            sample_count: self.sample_count,
        }
    }

    /// Render-target descriptor for the outline-mask pass.
    pub fn mask_target_desc(&self) -> MaskTargetDesc {
        MaskTargetDesc {
            color_format: MASK_COLOR_FORMAT,
            depth_format: SCENE_DEPTH_FORMAT,
            sample_count: 1,
        }
    }

    /// Render-target descriptor for the pick-id pass.
    pub fn pick_target_desc(&self) -> PickTargetDesc {
        PickTargetDesc {
            color_format: PICK_COLOR_FORMAT,
            depth_format: SCENE_DEPTH_FORMAT,
            sample_count: 1,
        }
    }

    /// Render-target descriptor for the shadow-atlas pass.
    pub fn shadow_target_desc(&self) -> ShadowTargetDesc {
        ShadowTargetDesc {
            depth_format: SHADOW_DEPTH_FORMAT,
            sample_count: 1,
        }
    }

    // ------------------------------------------------------------------
    // Texture-id namespace accessors
    // ------------------------------------------------------------------

    /// Borrow the `TextureView` for a texture previously uploaded via
    /// [`upload_texture`](Self::upload_texture) or
    /// [`upload_normal_map`](Self::upload_normal_map).
    ///
    /// Returns `None` if `id` does not refer to a live texture (out of
    /// range, or the texture was unloaded).
    ///
    /// Lifetime contract: the returned view is valid until the texture
    /// is removed (currently no public removal API exists, so views are
    /// effectively stable for the lifetime of `self`). Plugins that build a
    /// bind group from this view must rebuild it after any operation that
    /// could invalidate the texture (texture-store compaction, device
    /// recreation). A safer pattern is to fetch the view each frame just
    /// before building / rebuilding the bind group.
    pub fn texture_view(&self, id: u64) -> Option<&wgpu::TextureView> {
        self.textures.get(id as usize).map(|t| &t.view)
    }

    /// Borrow the sampler the texture was uploaded with.
    ///
    /// Most user textures are uploaded with a shared linear-repeat sampler;
    /// prefer [`material_sampler`](Self::material_sampler) when you need
    /// the shared lib sampler rather than the per-texture instance.
    pub fn texture_sampler(&self, id: u64) -> Option<&wgpu::Sampler> {
        self.textures.get(id as usize).map(|t| &t.sampler)
    }

    /// Shared linear-repeat sampler used by the lib's material pipelines.
    ///
    /// Use this when building a plugin bind group that samples user
    /// textures the same way `Material` does (linear filter, repeat wrap).
    pub fn material_sampler(&self) -> &wgpu::Sampler {
        &self.material_sampler
    }

    /// Shared linear-clamp sampler used by the lib for colormap LUTs.
    ///
    /// Use this when sampling 1D LUT-style data (colourmaps, transfer
    /// functions) where the texture should not wrap.
    pub fn lut_sampler(&self) -> &wgpu::Sampler {
        &self.lut_sampler
    }

    /// Comparison sampler used for PCF shadow filtering.
    ///
    /// Plugins that sample the shadow atlas directly (rather than through
    /// `viewport_sample_csm`) use this sampler when binding the atlas.
    pub fn shadow_filter_sampler(&self) -> &wgpu::Sampler {
        &self.shadow_sampler
    }

    /// Bind group layout for the GPU skinning palette.
    ///
    /// Plugins shipping skinned variants of their geometry add this
    /// layout to their pipeline's `extra_bind_group_layouts` list at
    /// group 2, then include
    /// [`SHARED_SKIN_WGSL`](crate::plugin_api::shared_wgsl::SHARED_SKIN_WGSL)
    /// in their vertex shader.
    ///
    /// The host (or the mesh-attach helper) uploads per-instance joint
    /// palettes via [`set_skin_palette`](Self::set_skin_palette); plugins
    /// do not manage palette uploads themselves.
    pub fn skin_palette_layout(&self) -> &wgpu::BindGroupLayout {
        &self.skinning.bind_group_layout
    }

    /// Number of live user-uploaded textures.
    ///
    /// `id` values in `0..texture_count()` are addressable via
    /// [`texture_view`](Self::texture_view), with the caveat that promoted
    /// IDs from async uploads may sit at the high end.
    pub fn texture_count(&self) -> usize {
        self.textures.len()
    }

    // ------------------------------------------------------------------
    // Pipeline builders
    // ------------------------------------------------------------------

    /// Build an opaque scene pipeline that draws into the HDR scene pass.
    ///
    /// Standard depth state: `LessEqual` test, depth write on. The pipeline
    /// layout lists [`shared_bindings`](Self::shared_bindings) as group 0,
    /// then `extra_bind_group_layouts` as groups 1.., in order. The plugin
    /// owns all groups past 0.
    pub fn build_opaque_pipeline(
        &self,
        device: &wgpu::Device,
        opts: &PluginPipelineOpts<'_>,
    ) -> wgpu::RenderPipeline {
        let layout = build_layout(device, opts.label, self, opts.extra_bind_group_layouts);
        let desc = self.opaque_target_desc();
        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: opts.label,
            layout: Some(&layout),
            vertex: wgpu::VertexState {
                module: opts.shader,
                entry_point: Some(opts.vs_entry),
                buffers: opts.vertex_layouts,
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: opts.shader,
                entry_point: Some(opts.fs_entry),
                targets: &[Some(wgpu::ColorTargetState {
                    format: desc.color_format,
                    blend: opts.color_blend,
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            primitive: opts.primitive,
            depth_stencil: Some(wgpu::DepthStencilState {
                format: desc.depth_format,
                depth_write_enabled: opts.depth_write,
                depth_compare: opts.depth_compare,
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState {
                count: desc.sample_count,
                ..Default::default()
            },
            multiview: None,
            cache: None,
        })
    }

    /// Build a transparent pipeline that draws into the OIT pass.
    ///
    /// The fragment shader must return [`OitOutput`](crate::plugin_api::shared_wgsl::SHARED_OIT_WGSL),
    /// writing both `@location(0)` (accum) and `@location(1)` (reveal).
    /// Depth state: `LessEqual` test, depth write off.
    pub fn build_oit_pipeline(
        &self,
        device: &wgpu::Device,
        opts: &PluginPipelineOpts<'_>,
    ) -> wgpu::RenderPipeline {
        let layout = build_layout(device, opts.label, self, opts.extra_bind_group_layouts);
        let desc = self.oit_target_desc();
        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: opts.label,
            layout: Some(&layout),
            vertex: wgpu::VertexState {
                module: opts.shader,
                entry_point: Some(opts.vs_entry),
                buffers: opts.vertex_layouts,
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: opts.shader,
                entry_point: Some(opts.fs_entry),
                targets: &[
                    Some(wgpu::ColorTargetState {
                        format: desc.accum_format,
                        blend: Some(desc.accum_blend),
                        write_mask: wgpu::ColorWrites::ALL,
                    }),
                    Some(wgpu::ColorTargetState {
                        format: desc.reveal_format,
                        blend: Some(desc.reveal_blend),
                        write_mask: wgpu::ColorWrites::RED,
                    }),
                ],
                compilation_options: Default::default(),
            }),
            primitive: opts.primitive,
            depth_stencil: Some(wgpu::DepthStencilState {
                format: desc.depth_format,
                depth_write_enabled: false,
                depth_compare: wgpu::CompareFunction::LessEqual,
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState {
                count: desc.sample_count,
                ..Default::default()
            },
            multiview: None,
            cache: None,
        })
    }

    /// Build a pipeline for the outline-mask pass (R8 target).
    ///
    /// Fragment shader must write `1.0` at `@location(0)` for any covered
    /// pixel; use [`SHARED_MASK_WGSL`](crate::plugin_api::shared_wgsl::SHARED_MASK_WGSL).
    /// Depth state: `LessEqual` test, no depth write.
    pub fn build_mask_pipeline(
        &self,
        device: &wgpu::Device,
        opts: &PluginPipelineOpts<'_>,
    ) -> wgpu::RenderPipeline {
        let layout = build_layout(device, opts.label, self, opts.extra_bind_group_layouts);
        let desc = self.mask_target_desc();
        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: opts.label,
            layout: Some(&layout),
            vertex: wgpu::VertexState {
                module: opts.shader,
                entry_point: Some(opts.vs_entry),
                buffers: opts.vertex_layouts,
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: opts.shader,
                entry_point: Some(opts.fs_entry),
                targets: &[Some(wgpu::ColorTargetState {
                    format: desc.color_format,
                    blend: None,
                    write_mask: wgpu::ColorWrites::RED,
                })],
                compilation_options: Default::default(),
            }),
            primitive: opts.primitive,
            depth_stencil: Some(wgpu::DepthStencilState {
                format: desc.depth_format,
                depth_write_enabled: false,
                depth_compare: wgpu::CompareFunction::LessEqual,
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState {
                count: desc.sample_count,
                ..Default::default()
            },
            multiview: None,
            cache: None,
        })
    }

    /// Build a pipeline for the pick-id pass (R32Uint target).
    ///
    /// Fragment shader must write the item's `PickId` value at
    /// `@location(0)`; use [`SHARED_PICK_WGSL`](crate::plugin_api::shared_wgsl::SHARED_PICK_WGSL).
    pub fn build_pick_pipeline(
        &self,
        device: &wgpu::Device,
        opts: &PluginPipelineOpts<'_>,
    ) -> wgpu::RenderPipeline {
        let layout = build_layout(device, opts.label, self, opts.extra_bind_group_layouts);
        let desc = self.pick_target_desc();
        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: opts.label,
            layout: Some(&layout),
            vertex: wgpu::VertexState {
                module: opts.shader,
                entry_point: Some(opts.vs_entry),
                buffers: opts.vertex_layouts,
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: opts.shader,
                entry_point: Some(opts.fs_entry),
                targets: &[Some(wgpu::ColorTargetState {
                    format: desc.color_format,
                    blend: None,
                    write_mask: wgpu::ColorWrites::RED,
                })],
                compilation_options: Default::default(),
            }),
            primitive: opts.primitive,
            depth_stencil: Some(wgpu::DepthStencilState {
                format: desc.depth_format,
                depth_write_enabled: true,
                depth_compare: wgpu::CompareFunction::LessEqual,
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState {
                count: desc.sample_count,
                ..Default::default()
            },
            multiview: None,
            cache: None,
        })
    }

    /// Build a depth-only pipeline for the shadow-atlas pass.
    ///
    /// No fragment output. The fragment entry is optional; pass an empty
    /// string to use a depth-only configuration with no fragment stage.
    /// Standard depth state: `LessEqual` test, depth write on, with the
    /// lib's standard depth bias.
    pub fn build_shadow_pipeline(
        &self,
        device: &wgpu::Device,
        opts: &PluginPipelineOpts<'_>,
    ) -> wgpu::RenderPipeline {
        let layout = build_layout(device, opts.label, self, opts.extra_bind_group_layouts);
        let desc = self.shadow_target_desc();
        let fragment = if opts.fs_entry.is_empty() {
            None
        } else {
            Some(wgpu::FragmentState {
                module: opts.shader,
                entry_point: Some(opts.fs_entry),
                targets: &[],
                compilation_options: Default::default(),
            })
        };
        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: opts.label,
            layout: Some(&layout),
            vertex: wgpu::VertexState {
                module: opts.shader,
                entry_point: Some(opts.vs_entry),
                buffers: opts.vertex_layouts,
                compilation_options: Default::default(),
            },
            fragment,
            primitive: opts.primitive,
            depth_stencil: Some(wgpu::DepthStencilState {
                format: desc.depth_format,
                depth_write_enabled: true,
                depth_compare: wgpu::CompareFunction::LessEqual,
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState {
                    constant: 2,
                    slope_scale: 2.0,
                    clamp: 0.0,
                },
            }),
            multisample: wgpu::MultisampleState {
                count: desc.sample_count,
                ..Default::default()
            },
            multiview: None,
            cache: None,
        })
    }
}

/// Inputs to a plugin pipeline builder. All builders take this struct; the
/// builder picks the target descriptor and blend state.
pub struct PluginPipelineOpts<'a> {
    /// Pipeline debug label. Forwarded to wgpu.
    pub label: Option<&'a str>,
    /// Shader module containing both the vertex and fragment entry points.
    pub shader: &'a wgpu::ShaderModule,
    /// Vertex-stage entry-point name (e.g. `"vs_main"`).
    pub vs_entry: &'a str,
    /// Fragment-stage entry-point name (e.g. `"fs_main"`). For
    /// `build_shadow_pipeline`, pass `""` to skip the fragment stage.
    pub fs_entry: &'a str,
    /// Vertex buffer layouts.
    pub vertex_layouts: &'a [wgpu::VertexBufferLayout<'a>],
    /// Bind group layouts for groups 1.. (the plugin's per-object data).
    /// Group 0 is supplied automatically from
    /// [`ViewportGpuResources::shared_bindings`].
    pub extra_bind_group_layouts: &'a [&'a wgpu::BindGroupLayout],
    /// Primitive topology, cull mode, polygon mode.
    pub primitive: wgpu::PrimitiveState,
    /// Optional blend state for the opaque builder. `None` = no blending
    /// (the default for opaque pipelines). Ignored by OIT / mask / pick /
    /// shadow builders, which use their pass-specific blend state.
    pub color_blend: Option<wgpu::BlendState>,
    /// Whether the opaque builder writes depth. Ignored by the other
    /// builders. Default `true`.
    pub depth_write: bool,
    /// Depth-compare function for the opaque builder. Ignored by the other
    /// builders.
    pub depth_compare: wgpu::CompareFunction,
}

impl<'a> PluginPipelineOpts<'a> {
    /// Construct an opts struct with sensible defaults for the variable
    /// fields (`TriangleList`, back-face cull, depth write on,
    /// `LessEqual`, no blend). Callers must supply `shader`, vertex / fragment
    /// entry points, and the vertex layout.
    pub fn new(
        label: Option<&'a str>,
        shader: &'a wgpu::ShaderModule,
        vs_entry: &'a str,
        fs_entry: &'a str,
        vertex_layouts: &'a [wgpu::VertexBufferLayout<'a>],
    ) -> Self {
        Self {
            label,
            shader,
            vs_entry,
            fs_entry,
            vertex_layouts,
            extra_bind_group_layouts: &[],
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                cull_mode: Some(wgpu::Face::Back),
                ..Default::default()
            },
            color_blend: None,
            depth_write: true,
            depth_compare: wgpu::CompareFunction::LessEqual,
        }
    }
}

fn build_layout(
    device: &wgpu::Device,
    label: Option<&str>,
    res: &ViewportGpuResources,
    extras: &[&wgpu::BindGroupLayout],
) -> wgpu::PipelineLayout {
    let mut bgls: Vec<&wgpu::BindGroupLayout> = Vec::with_capacity(1 + extras.len());
    bgls.push(&res.camera_bind_group_layout);
    bgls.extend(extras.iter().copied());
    device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label,
        bind_group_layouts: &bgls,
        push_constant_ranges: &[],
    })
}