tiny_wgpu 0.1.10

wgpu helper 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
use std::{collections::HashMap, sync::Arc};
use bytemuck::Pod;
use wgpu::{BufferUsages, ShaderStages};

pub struct Compute {
    pub instance: Arc<wgpu::Instance>,
    pub adapter: Arc<wgpu::Adapter>,
    pub device: Arc<wgpu::Device>,
    pub queue: Arc<wgpu::Queue>
}

impl Compute {
    pub async fn new(features: wgpu::Features, limits: wgpu::Limits) -> Self {
        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { 
            backends: wgpu::Backends::PRIMARY, 
            flags: wgpu::InstanceFlags::empty(), 
            dx12_shader_compiler: wgpu::Dx12Compiler::Fxc, 
            gles_minor_version: wgpu::Gles3MinorVersion::Automatic
        });
    
        let adapter = instance.request_adapter(&wgpu::RequestAdapterOptions::default()).await.unwrap();

        let (device, queue) = adapter.request_device(
            &wgpu::DeviceDescriptor {
                label: None,
                required_features: features,
                required_limits: limits,
                
            }, 
            None
        ).await.unwrap();

        Self {
            instance: Arc::new(instance),
            adapter: Arc::new(adapter),
            device: Arc::new(device),
            queue: Arc::new(queue)
        }
    }
}

pub enum BindGroupItem {
    StorageBuffer { label: &'static str, min_binding_size: u64, read_only: bool },
    UniformBuffer { label: &'static str, min_binding_size: u64 },
    Texture { label: &'static str },
    TextureView { label: &'static str, sample_type: wgpu::TextureSampleType },
    StorageTexture { label: &'static str, access: wgpu::StorageTextureAccess },
    Sampler { label: &'static str }
}

pub struct ComputeKernel {
    pub label: &'static str,
    pub entry_point: &'static str
}

pub struct RenderKernel {
    pub label: &'static str,
    pub vertex: &'static str,
    pub fragment: &'static str
}

pub struct Storage {
    pub modules: HashMap<&'static str, wgpu::ShaderModule>,
    pub buffers: HashMap<&'static str, wgpu::Buffer>,
    pub textures: HashMap<&'static str, wgpu::Texture>,
    pub texture_views: HashMap<&'static str, wgpu::TextureView>,
    pub samplers: HashMap<&'static str, wgpu::Sampler>,
    pub bind_groups: HashMap<&'static str, wgpu::BindGroup>,
    pub bind_group_layouts: HashMap<&'static str, wgpu::BindGroupLayout>,
    pub compute_pipelines: HashMap<&'static str, wgpu::ComputePipeline>,
    pub render_pipelines: HashMap<&'static str, wgpu::RenderPipeline>,
    
    pub staging_buffers: HashMap<&'static str, wgpu::Buffer>,
    pub staging_senders: HashMap<&'static str, flume::Sender<Result<(), wgpu::BufferAsyncError>>>,
    pub staging_receivers: HashMap<&'static str, flume::Receiver<Result<(), wgpu::BufferAsyncError>>>
}

impl Default for Storage {
    fn default() -> Self {
        Self { 
            modules: Default::default(), 
            buffers: Default::default(), 
            textures: Default::default(), 
            texture_views: Default::default(), 
            samplers: Default::default(), 
            bind_groups: Default::default(), 
            bind_group_layouts: Default::default(), 
            compute_pipelines: Default::default(), 
            render_pipelines: Default::default(), 
            staging_buffers: Default::default(), 
            staging_senders: Default::default(),
            staging_receivers: Default::default()
        }
    }
}

pub trait ComputeProgram {
    fn storage(&self) -> &Storage;
    fn storage_mut(&mut self) -> &mut Storage;
    fn compute(&self) -> &Compute;

    fn add_buffer(&mut self, label: &'static str, usage: wgpu::BufferUsages, size: u64) {
        let buffer = self.compute().device.create_buffer(&wgpu::BufferDescriptor {
            label: None,
            size: size.into(),
            usage,
            mapped_at_creation: false
        });

        self.storage_mut().buffers.insert(label, buffer);
    }
    
    fn add_module(&mut self, label: &'static str, shader: wgpu::ShaderModuleDescriptor) {
        let module = self.compute().device.create_shader_module(shader);
        self.storage_mut().modules.insert(label, module);
    }
    
    fn add_staging_buffer(&mut self, label: &'static str) {
        let buffer = self.compute().device.create_buffer(&wgpu::BufferDescriptor {
            label: None,
            usage: BufferUsages::MAP_READ | BufferUsages::COPY_DST,
            size: self.storage().buffers[label].size(),
            mapped_at_creation: false
        });

        self.storage_mut().staging_buffers.insert(label, buffer);

        let (sender, receiver) = flume::bounded(1);

        self.storage_mut().staging_senders.insert(label, sender);
        self.storage_mut().staging_receivers.insert(label, receiver);
    }
    
    fn add_texture(&mut self, label: &'static str, usage: wgpu::TextureUsages, format: wgpu::TextureFormat, size: wgpu::Extent3d) {
        let texture = self.compute().device.create_texture(&wgpu::TextureDescriptor {
            label: None,
            size,
            usage,
            format,
            dimension: wgpu::TextureDimension::D2,
            mip_level_count: 1,
            sample_count: 1,
            view_formats: &[]
        });

        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());

        self.storage_mut().texture_views.insert(label, view);
        self.storage_mut().textures.insert(label, texture);
    }
    
    fn add_sampler(&mut self, label: &'static str, descriptor: wgpu::SamplerDescriptor) {
        let sampler = self.compute().device.create_sampler(&descriptor);
        self.storage_mut().samplers.insert(label, sampler);
    }
    
    fn add_bind_group(&mut self, label: &'static str, items: &[BindGroupItem]) {
        let mut bind_group_layout_entries = Vec::new();
        let mut bind_group_entries = Vec::new();

        for (i, bind_group_item) in items.iter().enumerate() {
            match bind_group_item {
                BindGroupItem::StorageBuffer { label, min_binding_size, read_only } => {
                    bind_group_layout_entries.push(wgpu::BindGroupLayoutEntry {
                        binding: i as u32,
                        // Cannot use storage buffers in vertex shader without feature flag
                        visibility: wgpu::ShaderStages::COMPUTE | wgpu::ShaderStages::FRAGMENT,
                        ty: wgpu::BindingType::Buffer { 
                            ty: wgpu::BufferBindingType::Storage { read_only: *read_only }, 
                            has_dynamic_offset: false, 
                            min_binding_size: Some(std::num::NonZeroU64::new(*min_binding_size).unwrap())
                        },
                        count: None
                    });

                    bind_group_entries.push(wgpu::BindGroupEntry {
                        binding: i as u32,
                        resource: self.storage().buffers[label].as_entire_binding()
                    });
                },
                BindGroupItem::UniformBuffer { label, min_binding_size } => {
                    bind_group_layout_entries.push(wgpu::BindGroupLayoutEntry {
                        binding: i as u32,
                        visibility: wgpu::ShaderStages::all(),
                        ty: wgpu::BindingType::Buffer { 
                            ty: wgpu::BufferBindingType::Uniform, 
                            has_dynamic_offset: false, 
                            min_binding_size: Some(std::num::NonZeroU64::new(*min_binding_size).unwrap())
                        },
                        count: None
                    });

                    bind_group_entries.push(wgpu::BindGroupEntry {
                        binding: i as u32,
                        resource: self.storage().buffers[label].as_entire_binding()
                    });
                },
                BindGroupItem::Texture { label } => {
                    let sample_type = self.storage().textures[label].format().sample_type(None, None).unwrap();

                    bind_group_layout_entries.push(wgpu::BindGroupLayoutEntry {
                        binding: i as u32,
                        visibility: wgpu::ShaderStages::all(),
                        ty: wgpu::BindingType::Texture { 
                            sample_type,
                            view_dimension: wgpu::TextureViewDimension::D2, 
                            multisampled: false
                        },
                        count: None
                    });

                    bind_group_entries.push(wgpu::BindGroupEntry {
                        binding: i as u32,
                        resource: wgpu::BindingResource::TextureView(&self.storage().texture_views[label])
                    });
                },
                BindGroupItem::TextureView { label, sample_type } => {
                    bind_group_layout_entries.push(wgpu::BindGroupLayoutEntry {
                        binding: i as u32,
                        visibility: wgpu::ShaderStages::all(),
                        ty: wgpu::BindingType::Texture { 
                            sample_type: *sample_type,
                            view_dimension: wgpu::TextureViewDimension::D2, 
                            multisampled: false
                        },
                        count: None
                    });

                    bind_group_entries.push(wgpu::BindGroupEntry {
                        binding: i as u32,
                        resource: wgpu::BindingResource::TextureView(&self.storage().texture_views[label])
                    });
                },
                BindGroupItem::StorageTexture { label, access } => {
                    let format = self.storage().textures[label].format();
                    bind_group_layout_entries.push(wgpu::BindGroupLayoutEntry {
                        binding: i as u32,
                        visibility: wgpu::ShaderStages::COMPUTE | wgpu::ShaderStages::FRAGMENT,
                        ty: wgpu::BindingType::StorageTexture { 
                            access: *access, 
                            format, 
                            view_dimension: wgpu::TextureViewDimension::D2
                        },
                        count: None
                    });

                    bind_group_entries.push(wgpu::BindGroupEntry {
                        binding: i as u32,
                        resource: wgpu::BindingResource::TextureView(&self.storage().texture_views[label])
                    });
                },
                BindGroupItem::Sampler { label } => {
                    bind_group_layout_entries.push(wgpu::BindGroupLayoutEntry {
                        binding: i as u32,
                        ty: wgpu::BindingType::Sampler(
                            wgpu::SamplerBindingType::Filtering
                        ),
                        visibility: ShaderStages::all(),
                        count: None
                    });

                    bind_group_entries.push(wgpu::BindGroupEntry {
                        binding: i as u32,
                        resource: wgpu::BindingResource::Sampler(&self.storage().samplers[label])
                    });
                }
            }
        }

        let bind_group_layout = self.compute().device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: None,
            entries: &bind_group_layout_entries
        });

        let bind_group = self.compute().device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: None,
            layout: &bind_group_layout,
            entries: &bind_group_entries
        });

        self.storage_mut().bind_groups.insert(label, bind_group);
        self.storage_mut().bind_group_layouts.insert(label, bind_group_layout);
    }
    
    fn copy_buffer_to_buffer_full(&self, encoder: &mut wgpu::CommandEncoder, buffer_a: &'static str, buffer_b: &'static str) {
        encoder.copy_buffer_to_buffer(
            &self.storage().buffers[buffer_a], 
            0, 
            &self.storage().buffers[buffer_b],
            0, 
            self.storage().buffers[buffer_b].size()
        );
    }
    
    fn copy_buffer_to_staging(&self, encoder: &mut wgpu::CommandEncoder, label: &'static str) {
        encoder.copy_buffer_to_buffer(
            &self.storage().buffers[label], 
            0, 
            &self.storage().staging_buffers[label],
            0, 
            self.storage().buffers[label].size()
        );
    }
    
    fn prepare_staging_buffer(&self, label: &'static str) {
        let slice = self.storage().staging_buffers[label].slice(..);
        let sender = self.storage().staging_senders[label].clone();
        slice.map_async(wgpu::MapMode::Read, move |v| sender.send(v).unwrap());
    }
    
    fn read_staging_buffer<T: Pod>(&self, label: &'static str, dst: &mut [T]) {
        // Wait for the mapping to finish
        self.storage().staging_receivers[label].recv().unwrap().unwrap();

        // Read data
        {
            let data_size = std::mem::size_of::<T>();
            let data_len = dst.len();
            let num_bytes = (data_len * data_size) as u64;

            let dst = bytemuck::cast_slice_mut(dst);
            let data = self.storage().staging_buffers[label].slice(..num_bytes).get_mapped_range();
            dst.copy_from_slice(&data);
        }

        // Unmap for the GPU to use again
        self.storage().staging_buffers[label].unmap();
    }
    
    fn add_compute_pipelines(
        &mut self,
        module: &'static str,
        bind_groups: &[&'static str],
        kernels: &[ComputeKernel],
        push_constant_ranges: &[wgpu::PushConstantRange],
        compilation_options: Option<wgpu::PipelineCompilationOptions>
    ) {
        let bind_group_layouts: Vec<_> = bind_groups
            .iter()
            .map(|x| &self.storage().bind_group_layouts[x])
            .collect();

        let pipeline_layout = self.compute().device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: None,
            bind_group_layouts: &bind_group_layouts,
            push_constant_ranges
        });

        let empty_map = HashMap::new();
        let compilation_options = compilation_options.unwrap_or(wgpu::PipelineCompilationOptions {
            zero_initialize_workgroup_memory: true,
            constants: &empty_map
        });  
        
        for kernel in kernels {
            let pipeline = self.compute().device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
                label: None,
                layout: Some(&pipeline_layout),
                module: &self.storage().modules[module],
                entry_point: &kernel.entry_point,
                compilation_options: compilation_options.clone()
            });

            self.storage_mut().compute_pipelines.insert(&kernel.label, pipeline);
        }
    }

    fn add_render_pipelines_2(
        &mut self,
        
    ) {}
    
    fn add_render_pipelines(
        &mut self,
        module: &'static str,
        bind_groups: &[&'static str],
        kernels: &[RenderKernel],
        push_constant_ranges: &[wgpu::PushConstantRange],
        targets: &[Option<wgpu::ColorTargetState>],
        vertex_buffer_layouts: &[wgpu::VertexBufferLayout],
        vertex_compilation_options: Option<wgpu::PipelineCompilationOptions>,
        fragment_compilation_options: Option<wgpu::PipelineCompilationOptions>
    ) {
        let bind_group_layouts: Vec<_> = bind_groups
            .iter()
            .map(|x| &self.storage().bind_group_layouts[x])
            .collect();

        let pipeline_layout = self.compute().device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: None,
            bind_group_layouts: &bind_group_layouts,
            push_constant_ranges
        });

        let empty_map = HashMap::new();
        let vertex_compilation_options = vertex_compilation_options.unwrap_or(wgpu::PipelineCompilationOptions { constants: &empty_map, zero_initialize_workgroup_memory: true });
        let fragment_compilation_options = fragment_compilation_options.unwrap_or(wgpu::PipelineCompilationOptions { constants: &empty_map, zero_initialize_workgroup_memory: true });

        for kernel in kernels {
            let render_pipeline = self.compute().device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: None,
                layout: Some(&pipeline_layout),
                vertex: wgpu::VertexState {
                    module: &self.storage().modules[module],
                    entry_point: &kernel.vertex,
                    buffers: vertex_buffer_layouts,
                    compilation_options: vertex_compilation_options.clone()
                },
                fragment: Some(wgpu::FragmentState {
                    module: &self.storage().modules[module],
                    entry_point: &kernel.fragment,
                    targets,
                    compilation_options: fragment_compilation_options.clone()
                }),
                primitive: wgpu::PrimitiveState::default(),
                depth_stencil: None,
                multisample: wgpu::MultisampleState::default(),
                multiview: None,
            });

            self.storage_mut().render_pipelines.insert(&kernel.label, render_pipeline);
        }
    }
}