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
//! Compute pipeline management for GPU operations
//!
//! This module provides high-level abstractions for managing compute pipelines,
//! including pipeline creation, caching, and execution.
use crate::{GpuDevice, Result};
use parking_lot::RwLock;
use std::collections::HashMap;
use std::sync::Arc;
use wgpu::{
BindGroupLayout, CommandEncoder, ComputePass, ComputePassDescriptor, ComputePipeline,
ComputePipelineDescriptor, PipelineLayoutDescriptor, ShaderModule,
};
/// Compute pipeline wrapper with metadata
pub struct ComputePipelineHandle {
pipeline: ComputePipeline,
workgroup_size: (u32, u32, u32),
label: String,
}
impl ComputePipelineHandle {
/// Create a new compute pipeline handle
#[must_use]
pub fn new(pipeline: ComputePipeline, workgroup_size: (u32, u32, u32), label: String) -> Self {
Self {
pipeline,
workgroup_size,
label,
}
}
/// Get the underlying pipeline
#[must_use]
pub fn pipeline(&self) -> &ComputePipeline {
&self.pipeline
}
/// Get the workgroup size
#[must_use]
pub fn workgroup_size(&self) -> (u32, u32, u32) {
self.workgroup_size
}
/// Get the pipeline label
#[must_use]
pub fn label(&self) -> &str {
&self.label
}
}
/// Compute pipeline manager with caching
pub struct ComputePipelineManager {
device: Arc<wgpu::Device>,
pipelines: RwLock<HashMap<String, Arc<ComputePipelineHandle>>>,
}
impl ComputePipelineManager {
/// Create a new compute pipeline manager
#[must_use]
pub fn new(device: &GpuDevice) -> Self {
Self {
device: Arc::clone(device.device()),
pipelines: RwLock::new(HashMap::new()),
}
}
/// Get or create a compute pipeline
///
/// # Arguments
///
/// * `key` - Unique key for caching the pipeline
/// * `label` - Human-readable label for debugging
/// * `shader` - Compiled shader module
/// * `entry_point` - Entry point function name
/// * `bind_group_layout` - Bind group layout for resources
/// * `workgroup_size` - Workgroup size (x, y, z)
///
/// # Errors
///
/// Returns an error if pipeline creation fails.
#[allow(clippy::too_many_arguments)]
pub fn get_or_create(
&self,
key: &str,
label: &str,
shader: &ShaderModule,
entry_point: &str,
bind_group_layout: &BindGroupLayout,
workgroup_size: (u32, u32, u32),
) -> Result<Arc<ComputePipelineHandle>> {
// Check cache first
{
let cache = self.pipelines.read();
if let Some(pipeline) = cache.get(key) {
return Ok(Arc::clone(pipeline));
}
}
// Create pipeline
let pipeline = self.create_pipeline(label, shader, entry_point, bind_group_layout)?;
let handle = Arc::new(ComputePipelineHandle::new(
pipeline,
workgroup_size,
label.to_string(),
));
// Cache it
{
let mut cache = self.pipelines.write();
cache.insert(key.to_string(), Arc::clone(&handle));
}
Ok(handle)
}
/// Create a new compute pipeline
fn create_pipeline(
&self,
label: &str,
shader: &ShaderModule,
entry_point: &str,
bind_group_layout: &BindGroupLayout,
) -> Result<ComputePipeline> {
let pipeline_layout = self
.device
.create_pipeline_layout(&PipelineLayoutDescriptor {
label: Some(&format!("{label} Layout")),
bind_group_layouts: &[bind_group_layout],
push_constant_ranges: &[],
});
Ok(self
.device
.create_compute_pipeline(&ComputePipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
module: shader,
entry_point: Some(entry_point),
cache: None,
compilation_options: Default::default(),
}))
}
/// Clear the pipeline cache
pub fn clear_cache(&self) {
let mut cache = self.pipelines.write();
cache.clear();
}
/// Get number of cached pipelines
pub fn cache_size(&self) -> usize {
let cache = self.pipelines.read();
cache.len()
}
}
/// Compute pass builder for easier command encoding
pub struct ComputePassBuilder<'a> {
encoder: &'a mut CommandEncoder,
label: Option<String>,
}
impl<'a> ComputePassBuilder<'a> {
/// Create a new compute pass builder
pub fn new(encoder: &'a mut CommandEncoder) -> Self {
Self {
encoder,
label: None,
}
}
/// Set the compute pass label
pub fn with_label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
/// Begin the compute pass and execute commands
///
/// # Arguments
///
/// * `f` - Function that configures the compute pass
pub fn execute<F>(self, f: F)
where
F: FnOnce(&mut ComputePass<'_>),
{
let mut pass = self.encoder.begin_compute_pass(&ComputePassDescriptor {
label: self.label.as_deref(),
timestamp_writes: None,
});
f(&mut pass);
}
}
/// Helper for dispatching compute workgroups
pub struct DispatchHelper;
impl DispatchHelper {
/// Calculate dispatch dimensions for 1D workload
///
/// # Arguments
///
/// * `count` - Total number of elements
/// * `workgroup_size` - Workgroup size
///
/// # Returns
///
/// Number of workgroups to dispatch
#[must_use]
pub fn dispatch_1d(count: u32, workgroup_size: u32) -> u32 {
count.div_ceil(workgroup_size)
}
/// Calculate dispatch dimensions for 2D workload
///
/// # Arguments
///
/// * `width` - Width of the workload
/// * `height` - Height of the workload
/// * `workgroup_size` - Workgroup size (x, y)
///
/// # Returns
///
/// Number of workgroups to dispatch (x, y)
#[must_use]
pub fn dispatch_2d(width: u32, height: u32, workgroup_size: (u32, u32)) -> (u32, u32) {
let x = width.div_ceil(workgroup_size.0);
let y = height.div_ceil(workgroup_size.1);
(x, y)
}
/// Calculate dispatch dimensions for 3D workload
///
/// # Arguments
///
/// * `width` - Width of the workload
/// * `height` - Height of the workload
/// * `depth` - Depth of the workload
/// * `workgroup_size` - Workgroup size (x, y, z)
///
/// # Returns
///
/// Number of workgroups to dispatch (x, y, z)
#[must_use]
pub fn dispatch_3d(
width: u32,
height: u32,
depth: u32,
workgroup_size: (u32, u32, u32),
) -> (u32, u32, u32) {
let x = width.div_ceil(workgroup_size.0);
let y = height.div_ceil(workgroup_size.1);
let z = depth.div_ceil(workgroup_size.2);
(x, y, z)
}
}
/// Compute operation executor
pub struct ComputeExecutor<'a> {
device: &'a GpuDevice,
encoder: CommandEncoder,
}
impl<'a> ComputeExecutor<'a> {
/// Create a new compute executor
#[must_use]
pub fn new(device: &'a GpuDevice, label: &str) -> Self {
let encoder = device
.device()
.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some(label) });
Self { device, encoder }
}
/// Begin a compute pass
pub fn begin_pass(&mut self, label: &str) -> ComputePassBuilder<'_> {
ComputePassBuilder::new(&mut self.encoder).with_label(label)
}
// Note: Simple dispatch helper removed due to lifetime complexity.
// Use begin_pass() directly for compute dispatches.
// Example:
// executor.begin_pass("My Compute Pass").execute(|pass| {
// pass.set_pipeline(&pipeline);
// pass.set_bind_group(0, &bind_group, &[]);
// pass.dispatch_workgroups(x, y, z);
// });
/// Finish encoding and submit commands
pub fn submit(self) {
let command_buffer = self.encoder.finish();
self.device.queue().submit(Some(command_buffer));
}
/// Get a mutable reference to the encoder for advanced operations
pub fn encoder_mut(&mut self) -> &mut CommandEncoder {
&mut self.encoder
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_dispatch_1d() {
assert_eq!(DispatchHelper::dispatch_1d(100, 64), 2);
assert_eq!(DispatchHelper::dispatch_1d(64, 64), 1);
assert_eq!(DispatchHelper::dispatch_1d(65, 64), 2);
assert_eq!(DispatchHelper::dispatch_1d(0, 64), 0);
}
#[test]
fn test_dispatch_2d() {
assert_eq!(DispatchHelper::dispatch_2d(100, 100, (16, 16)), (7, 7));
assert_eq!(DispatchHelper::dispatch_2d(16, 16, (16, 16)), (1, 1));
assert_eq!(DispatchHelper::dispatch_2d(17, 17, (16, 16)), (2, 2));
}
#[test]
fn test_dispatch_3d() {
assert_eq!(
DispatchHelper::dispatch_3d(100, 100, 100, (8, 8, 8)),
(13, 13, 13)
);
assert_eq!(DispatchHelper::dispatch_3d(8, 8, 8, (8, 8, 8)), (1, 1, 1));
assert_eq!(DispatchHelper::dispatch_3d(9, 9, 9, (8, 8, 8)), (2, 2, 2));
}
}