Skip to main content

threecrate_gpu/
device.rs

1//! GPU device management
2
3use std::sync::{Arc, Mutex, OnceLock};
4use threecrate_core::{Error, Result};
5use wgpu::util::DeviceExt;
6
7/// Compute pipelines that are built once per context and reused across calls.
8/// Building a pipeline compiles its shader, which costs far more than running
9/// it on small inputs.
10#[derive(Default)]
11pub(crate) struct PipelineCache {
12    pub(crate) knn: OnceLock<wgpu::ComputePipeline>,
13    pub(crate) normals: OnceLock<wgpu::ComputePipeline>,
14    pub(crate) icp_match: OnceLock<wgpu::ComputePipeline>,
15    pub(crate) icp_match_plane: OnceLock<wgpu::ComputePipeline>,
16    pub(crate) radius_outlier: OnceLock<wgpu::ComputePipeline>,
17}
18
19/// GPU context for managing compute and rendering operations
20pub struct GpuContext {
21    pub instance: wgpu::Instance,
22    pub device: wgpu::Device,
23    pub queue: wgpu::Queue,
24    pub adapter: wgpu::Adapter,
25    pub(crate) pipelines: PipelineCache,
26    /// First GPU validation error since the last readback (for example a
27    /// buffer past the device's size limit). wgpu's default handler panics;
28    /// ours records it so the next readback returns it as an `Err`.
29    pub(crate) errors: Arc<Mutex<Option<String>>>,
30}
31
32/// Work-group grid for `groups` groups. wgpu allows at most 65,535 per
33/// dimension, so large jobs spill into y; shaders recover the linear group as
34/// `wid.x + wid.y * num_workgroups.x` and must skip indices past the end.
35pub(crate) fn workgroup_grid(groups: usize) -> (u32, u32) {
36    let x = groups.clamp(1, 65_535);
37    (x as u32, groups.div_ceil(x) as u32)
38}
39
40impl GpuContext {
41    /// Create a new GPU context
42    pub async fn new() -> Result<Self> {
43        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
44            backends: wgpu::Backends::all(),
45            flags: wgpu::InstanceFlags::default(),
46            ..wgpu::InstanceDescriptor::new_without_display_handle_from_env()
47        });
48
49        let adapter = instance
50            .request_adapter(&wgpu::RequestAdapterOptions {
51                power_preference: wgpu::PowerPreference::HighPerformance,
52                compatible_surface: None,
53                force_fallback_adapter: false,
54            })
55            .await
56            .map_err(|e| {
57                threecrate_core::Error::Gpu(format!("Failed to find suitable adapter: {:?}", e))
58            })?;
59
60        let (device, queue) = adapter
61            .request_device(&wgpu::DeviceDescriptor {
62                label: Some("ThreeCrate GPU Device"),
63                required_features: wgpu::Features::empty(),
64                // The defaults cap one buffer at 128 MiB (about 4M points);
65                // most cards allow far more.
66                required_limits: adapter.limits(),
67                ..Default::default()
68            })
69            .await
70            .map_err(|e| threecrate_core::Error::Gpu(format!("Failed to create device: {}", e)))?;
71
72        let context = Self::from_parts(instance, adapter, device, queue);
73        let errors = Arc::clone(&context.errors);
74        context.device.on_uncaptured_error(Arc::new(move |error| {
75            let mut slot = errors.lock().unwrap_or_else(|e| e.into_inner());
76            slot.get_or_insert_with(|| error.to_string());
77        }));
78        Ok(context)
79    }
80
81    /// Return (and clear) the first GPU error recorded since the last check.
82    pub(crate) fn take_error(&self) -> Result<()> {
83        let mut slot = self.errors.lock().unwrap_or_else(|e| e.into_inner());
84        match slot.take() {
85            Some(message) => Err(Error::Gpu(message)),
86            None => Ok(()),
87        }
88    }
89
90    /// Wrap a device the caller already created (for example to share it with
91    /// a renderer). Pipelines are compiled on first use, as with [`Self::new`].
92    pub fn from_parts(
93        instance: wgpu::Instance,
94        adapter: wgpu::Adapter,
95        device: wgpu::Device,
96        queue: wgpu::Queue,
97    ) -> Self {
98        Self {
99            instance,
100            device,
101            queue,
102            adapter,
103            pipelines: PipelineCache::default(),
104            errors: Arc::default(),
105        }
106    }
107
108    /// Return the pipeline in `slot`, compiling `source` on first use. The bind
109    /// group layout is derived from the shader (`layout: None`).
110    pub(crate) fn cached_pipeline<'a>(
111        &self,
112        slot: &'a OnceLock<wgpu::ComputePipeline>,
113        label: &str,
114        source: impl FnOnce() -> String,
115        entry_point: &str,
116    ) -> &'a wgpu::ComputePipeline {
117        slot.get_or_init(|| {
118            let shader = self.create_shader_module(label, &source());
119            self.create_compute_pipeline(label, &shader, entry_point)
120        })
121    }
122
123    /// Copy `buffer` (which needs `COPY_SRC`) to the CPU and return its contents
124    /// as `T`s. Blocks until the GPU has finished all submitted work. For
125    /// repeated reads of the same size, keep a staging buffer and use
126    /// [`Self::read_staging`] instead.
127    pub(crate) fn read_buffer<T: bytemuck::Pod>(&self, buffer: &wgpu::Buffer) -> Result<Vec<T>> {
128        let staging = self.create_staging_buffer("Readback", buffer.size());
129        let mut encoder = self
130            .device
131            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
132                label: Some("Readback"),
133            });
134        encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, buffer.size());
135        self.queue.submit(std::iter::once(encoder.finish()));
136        self.read_staging(&staging)
137    }
138
139    /// A `MAP_READ` buffer that GPU results can be copied into.
140    pub(crate) fn create_staging_buffer(&self, label: &str, size: u64) -> wgpu::Buffer {
141        self.create_buffer(
142            label,
143            size,
144            wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
145        )
146    }
147
148    /// Read a staging buffer whose copy has already been submitted, and unmap
149    /// it again so it can be reused. Blocks until the GPU has finished.
150    pub(crate) fn read_staging<T: bytemuck::Pod>(&self, staging: &wgpu::Buffer) -> Result<Vec<T>> {
151        let slice = staging.slice(..);
152        let (sender, receiver) = std::sync::mpsc::channel();
153        slice.map_async(wgpu::MapMode::Read, move |result| {
154            let _ = sender.send(result);
155        });
156        self.device
157            .poll(wgpu::PollType::Wait {
158                submission_index: None,
159                timeout: None,
160            })
161            .map_err(|e| Error::Gpu(format!("GPU poll failed: {e}")))?;
162        // A validation error (such as a buffer too large for the device)
163        // explains a failed or garbage readback, so report it first.
164        self.take_error()?;
165        receiver
166            .recv()
167            .map_err(|_| Error::Gpu("GPU readback was dropped".to_string()))?
168            .map_err(|e| Error::Gpu(format!("Failed to map GPU buffer: {e}")))?;
169
170        // `pod_collect_to_vec` copies into a correctly aligned Vec; the mapped
171        // range itself is only guaranteed 8-byte alignment.
172        let data = bytemuck::pod_collect_to_vec(&slice.get_mapped_range());
173        staging.unmap();
174        Ok(data)
175    }
176
177    /// Create a buffer from data
178    pub fn create_buffer_init<T: bytemuck::Pod>(
179        &self,
180        label: &str,
181        data: &[T],
182        usage: wgpu::BufferUsages,
183    ) -> wgpu::Buffer {
184        self.device
185            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
186                label: Some(label),
187                contents: bytemuck::cast_slice(data),
188                usage,
189            })
190    }
191
192    /// Create an empty buffer
193    pub fn create_buffer(&self, label: &str, size: u64, usage: wgpu::BufferUsages) -> wgpu::Buffer {
194        self.device.create_buffer(&wgpu::BufferDescriptor {
195            label: Some(label),
196            size,
197            usage,
198            mapped_at_creation: false,
199        })
200    }
201
202    /// Create a compute pipeline
203    pub fn create_compute_pipeline(
204        &self,
205        label: &str,
206        shader: &wgpu::ShaderModule,
207        entry_point: &str,
208    ) -> wgpu::ComputePipeline {
209        self.device
210            .create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
211                label: Some(label),
212                layout: None,
213                module: shader,
214                entry_point: Some(entry_point),
215                compilation_options: wgpu::PipelineCompilationOptions::default(),
216                cache: None,
217            })
218    }
219
220    /// Create a shader module from WGSL source
221    pub fn create_shader_module(&self, label: &str, source: &str) -> wgpu::ShaderModule {
222        self.device
223            .create_shader_module(wgpu::ShaderModuleDescriptor {
224                label: Some(label),
225                source: wgpu::ShaderSource::Wgsl(source.into()),
226            })
227    }
228
229    /// Create a bind group layout
230    pub fn create_bind_group_layout(
231        &self,
232        label: &str,
233        entries: &[wgpu::BindGroupLayoutEntry],
234    ) -> wgpu::BindGroupLayout {
235        self.device
236            .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
237                label: Some(label),
238                entries,
239            })
240    }
241
242    /// Create a bind group
243    pub fn create_bind_group(
244        &self,
245        label: &str,
246        layout: &wgpu::BindGroupLayout,
247        entries: &[wgpu::BindGroupEntry],
248    ) -> wgpu::BindGroup {
249        self.device.create_bind_group(&wgpu::BindGroupDescriptor {
250            label: Some(label),
251            layout,
252            entries,
253        })
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260
261    #[test]
262    fn workgroup_grid_stays_within_the_dimension_limit() {
263        assert_eq!(workgroup_grid(0), (1, 0));
264        assert_eq!(workgroup_grid(10), (10, 1));
265        assert_eq!(workgroup_grid(65_535), (65_535, 1));
266        assert_eq!(workgroup_grid(65_536), (65_535, 2));
267        // 4.3M points at 64 per group, the case that used to panic.
268        let (x, y) = workgroup_grid(4_300_000usize.div_ceil(64));
269        assert!(x <= 65_535 && x as usize * y as usize * 64 >= 4_300_000);
270    }
271
272    #[test]
273    fn gpu_validation_errors_come_back_as_err() {
274        pollster::block_on(async {
275            let Ok(gpu) = GpuContext::new().await else {
276                return; // no GPU here
277            };
278            // Copying past the end of a buffer is a validation error. wgpu's
279            // default handler panics; the readback must return it instead.
280            let usage = wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST;
281            let small = gpu.create_buffer("small", 16, usage);
282            let big = gpu.create_buffer("big", 64, usage);
283            let mut encoder = gpu.device.create_command_encoder(&Default::default());
284            encoder.copy_buffer_to_buffer(&big, 0, &small, 0, 64);
285            gpu.queue.submit(std::iter::once(encoder.finish()));
286            assert!(gpu.read_buffer::<f32>(&small).is_err());
287            // The error is cleared, so the next readback works again.
288            assert_eq!(gpu.read_buffer::<f32>(&small).unwrap().len(), 4);
289        });
290    }
291}