1use std::sync::Arc;
2
3use bytemuck::{Pod, Zeroable};
4use spatialrust_core::{SpatialError, SpatialResult, TransferDirection, TransferStats};
5use spatialrust_search::KdTree;
6use wgpu::util::DeviceExt;
7
8use crate::{scratch::ScratchBuffers, GpuKdTree, GpuNeighborhoods, GpuQueryBatch, WgpuRuntime};
9
10#[path = "fpfh_sample_gather.rs"]
11pub(crate) mod sample_gather;
12
13#[path = "fpfh_two_pass_reference.rs"]
14#[cfg(all(test, not(target_arch = "wasm32")))]
15pub(crate) mod two_pass_reference;
16
17pub const GPU_FPFH_DESCRIPTOR_LEN: usize = 33;
19
20const FUSED_POINT_LIMIT: u32 = 1_048_576;
23
24#[repr(C)]
25#[derive(Clone, Copy, Pod, Zeroable)]
26struct Sample {
27 position: [f32; 4],
28 normal: [f32; 4],
29}
30
31#[repr(C)]
32#[derive(Clone, Copy, Pod, Zeroable)]
33struct Params {
34 count: u32,
35 capacity: u32,
36 padding: [u32; 2],
37}
38
39fn invalid() -> SpatialError {
40 SpatialError::InvalidArgument("GPU FPFH requires matching input/runtime ownership, finite XYZ/unit normals, a positive finite radius square and supported buffers/dispatch".to_owned())
41}
42
43fn plan(points: u64, limits: &wgpu::Limits) -> SpatialResult<(u32, u64)> {
44 let bytes = points.checked_mul(132).ok_or_else(invalid)?;
45 let bound = limits.max_buffer_size.min(u64::from(limits.max_storage_buffer_binding_size));
46 if points > u64::from(u32::MAX)
47 || bytes > bound
48 || bytes > isize::MAX as u64
49 || limits.max_compute_workgroup_size_x < 64
50 || limits.max_compute_workgroup_size_y == 0
51 || limits.max_compute_workgroup_size_z == 0
52 || limits.max_compute_invocations_per_workgroup < 64
53 || points.div_ceil(64) > u64::from(limits.max_compute_workgroups_per_dimension)
54 || limits.max_storage_buffers_per_shader_stage < 5
55 || limits.max_bindings_per_bind_group < 6
56 || limits.max_bind_groups == 0
57 || limits.max_uniform_buffers_per_shader_stage == 0
58 || limits.max_uniform_buffer_binding_size < 16
59 || bound < 32
60 || bytes
61 .checked_add(16)
62 .map_or(true, |v| v > limits.max_buffer_size || v > isize::MAX as u64)
63 {
64 return Err(invalid());
65 }
66 Ok((points as u32, bytes))
67}
68
69pub struct GpuFpfhInput {
73 samples: Option<wgpu::Buffer>,
74 tree: GpuKdTree,
75 queries: GpuQueryBatch,
76 points: u32,
77 identity: Arc<()>,
78 input_identity: Arc<()>,
79 transfers: TransferStats,
80}
81
82impl GpuFpfhInput {
83 pub fn upload(
88 runtime: &WgpuRuntime,
89 tree: &KdTree,
90 normals: &[[f32; 3]],
91 ) -> SpatialResult<Self> {
92 Self::upload_impl(runtime, tree, normals, false)
93 }
94
95 pub fn upload_with_gpu_gather(
108 runtime: &WgpuRuntime,
109 tree: &KdTree,
110 normals: &[[f32; 3]],
111 ) -> SpatialResult<Self> {
112 Self::upload_impl(runtime, tree, normals, true)
113 }
114
115 fn upload_impl(
116 runtime: &WgpuRuntime,
117 tree: &KdTree,
118 normals: &[[f32; 3]],
119 gpu_gather: bool,
120 ) -> SpatialResult<Self> {
121 let layout = tree.layout();
122 let (x, y, z) = layout.positions();
123 let (points, _) = plan(x.len() as u64, &runtime.device().limits())?;
124 if normals.len() != x.len() {
125 return Err(SpatialError::BufferLengthMismatch {
126 expected: x.len(),
127 found: normals.len(),
128 });
129 }
130 if !super::feature_validation::valid([x, y, z], Some(normals)) {
131 return Err(invalid());
132 }
133 let (tree, queries, gathered_samples) = if gpu_gather {
134 if points < FUSED_POINT_LIMIT {
135 GpuKdTree::upload_with_gpu_samples(runtime, tree, normals)?
136 } else {
137 let (tree, queries) = GpuKdTree::upload_and_queries_with_gpu_gather(runtime, tree)?;
138 (tree, queries, None)
139 }
140 } else {
141 (
142 GpuKdTree::upload(runtime, tree)?,
143 GpuQueryBatch::upload_soa(runtime, [x, y, z])?,
144 None,
145 )
146 };
147 let mut transfers = tree.upload_transfers();
148 transfers.record(
149 TransferDirection::HostToDevice,
150 queries.upload_transfers().host_to_device_bytes(),
151 );
152 transfers.record(
153 TransferDirection::DeviceToDevice,
154 queries.upload_transfers().device_to_device_bytes(),
155 );
156 let samples = if points == 0 {
157 None
158 } else if gpu_gather {
159 transfers.record(TransferDirection::HostToDevice, u64::from(points) * 12);
160 transfers.record(TransferDirection::DeviceToDevice, u64::from(points) * 32);
161 Some(
162 gathered_samples
163 .unwrap_or_else(|| sample_gather::upload(runtime, &queries, normals)),
164 )
165 } else {
166 let samples: Vec<_> = x
167 .iter()
168 .zip(y)
169 .zip(z)
170 .zip(normals)
171 .map(|(((&x, &y), &z), n)| Sample {
172 position: [x, y, z, 0.0],
173 normal: [n[0], n[1], n[2], 0.0],
174 })
175 .collect();
176 transfers.record(TransferDirection::HostToDevice, u64::from(points) * 32);
177 Some(runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
178 label: Some("fpfh-samples"),
179 contents: bytemuck::cast_slice(&samples),
180 usage: wgpu::BufferUsages::STORAGE,
181 }))
182 };
183 Ok(Self {
184 samples,
185 tree,
186 queries,
187 points,
188 identity: runtime.profiling_identity(),
189 input_identity: Arc::new(()),
190 transfers,
191 })
192 }
193
194 #[must_use]
196 pub const fn point_count(&self) -> u32 {
197 self.points
198 }
199
200 #[must_use]
203 pub const fn upload_transfers(&self) -> TransferStats {
204 self.transfers
205 }
206
207 pub fn radius_neighborhoods_resident(
211 &self,
212 runtime: &WgpuRuntime,
213 radius: f32,
214 capacity: u32,
215 ) -> SpatialResult<GpuFpfhNeighborhoods> {
216 if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity())
217 || !radius.is_finite()
218 || radius <= 0.0
219 || !(radius * radius).is_finite()
220 || radius * radius == 0.0
221 {
222 return Err(invalid());
223 }
224 let neighborhoods =
225 self.tree.radius_neighbors_resident(runtime, &self.queries, radius, capacity)?;
226 Ok(GpuFpfhNeighborhoods {
227 neighborhoods,
228 input_identity: Arc::clone(&self.input_identity),
229 radius,
230 })
231 }
232
233 pub fn descriptors_resident(
240 &self,
241 runtime: &WgpuRuntime,
242 neighbors: &GpuFpfhNeighborhoods,
243 ) -> SpatialResult<GpuFpfhDescriptors> {
244 if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity())
245 || !Arc::ptr_eq(&self.input_identity, &neighbors.input_identity)
246 {
247 return Err(invalid());
248 }
249 let (_, bytes) = plan(u64::from(self.points), &runtime.device().limits())?;
250 let create = |label, size| {
251 runtime.device().create_buffer(&wgpu::BufferDescriptor {
252 label: Some(label),
253 size,
254 usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
255 mapped_at_creation: false,
256 })
257 };
258 let output = GpuFpfhDescriptors {
259 buffer: create("fpfh-descriptors", bytes.max(4)),
260 status: create("fpfh-status", 16),
261 points: self.points,
262 bytes,
263 identity: Arc::clone(&self.identity),
264 };
265 if self.points == 0 {
266 return Ok(output);
267 }
268 let cache = runtime.fpfh_pipelines.get_or_init(|| FpfhPipelines::new(runtime.device()));
269 let mut scratch = ScratchBuffers::new(runtime);
270 let spfh = scratch.acquire("fpfh-spfh", bytes);
271 let params = Params {
272 count: self.points,
273 capacity: neighbors.neighborhoods.capacity(),
274 padding: [0; 2],
275 };
276 let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
277 label: Some("fpfh-params"),
278 contents: bytemuck::bytes_of(¶ms),
279 usage: wgpu::BufferUsages::UNIFORM,
280 });
281 let buffers = [
282 &uniform,
283 self.samples.as_ref().unwrap(),
284 neighbors.neighborhoods.buffer(),
285 &spfh,
286 &output.buffer,
287 &output.status,
288 ];
289 let entries: Vec<_> = buffers
290 .iter()
291 .enumerate()
292 .map(|(i, b)| wgpu::BindGroupEntry {
293 binding: i as u32,
294 resource: b.as_entire_binding(),
295 })
296 .collect();
297 let group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
298 label: Some("fpfh-bindings"),
299 layout: &cache.layout,
300 entries: &entries,
301 });
302 let mut encoder = runtime.device().create_command_encoder(&Default::default());
303 for pipeline in [&cache.spfh, &cache.fpfh] {
304 let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
305 label: Some("fpfh-compute"),
306 timestamp_writes: None,
307 });
308 pass.set_pipeline(pipeline);
309 pass.set_bind_group(0, &group, &[]);
310 pass.dispatch_workgroups(self.points.div_ceil(64), 1, 1);
311 }
312 scratch.submit_and_recycle(encoder);
313 Ok(output)
314 }
315}
316
317pub struct GpuFpfhNeighborhoods {
319 neighborhoods: GpuNeighborhoods,
320 input_identity: Arc<()>,
321 radius: f32,
322}
323
324impl GpuFpfhNeighborhoods {
325 #[must_use]
327 pub fn neighborhoods(&self) -> &GpuNeighborhoods {
328 &self.neighborhoods
329 }
330 #[must_use]
332 pub const fn radius(&self) -> f32 {
333 self.radius
334 }
335}
336
337pub struct GpuFpfhDescriptors {
341 buffer: wgpu::Buffer,
342 status: wgpu::Buffer,
343 points: u32,
344 bytes: u64,
345 identity: Arc<()>,
346}
347
348impl GpuFpfhDescriptors {
349 #[must_use]
351 pub fn buffer(&self) -> &wgpu::Buffer {
352 &self.buffer
353 }
354 #[must_use]
357 pub fn status_buffer(&self) -> &wgpu::Buffer {
358 &self.status
359 }
360 #[must_use]
362 pub const fn point_count(&self) -> u32 {
363 self.points
364 }
365 #[must_use]
367 pub const fn readback_bytes(&self) -> u64 {
368 if self.points == 0 {
369 0
370 } else {
371 self.bytes + 16
372 }
373 }
374 pub fn download(
379 &self,
380 runtime: &WgpuRuntime,
381 ) -> SpatialResult<(Vec<[f32; 33]>, TransferStats)> {
382 if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity()) {
383 return Err(invalid());
384 }
385 if self.points == 0 {
386 return Ok((Vec::new(), TransferStats::default()));
387 }
388 let staging = runtime.device().create_buffer(&wgpu::BufferDescriptor {
389 label: Some("fpfh-readback"),
390 size: self.bytes + 16,
391 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
392 mapped_at_creation: false,
393 });
394 let mut encoder = runtime.device().create_command_encoder(&Default::default());
395 encoder.copy_buffer_to_buffer(&self.buffer, 0, &staging, 0, self.bytes);
396 encoder.copy_buffer_to_buffer(&self.status, 0, &staging, self.bytes, 16);
397 runtime.queue().submit(Some(encoder.finish()));
398 let slice = staging.slice(..);
399 let (sender, receiver) = std::sync::mpsc::channel();
400 slice.map_async(wgpu::MapMode::Read, move |r| {
401 let _ = sender.send(r);
402 });
403 runtime.device().poll(wgpu::Maintain::Wait);
404 receiver
405 .recv()
406 .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?
407 .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?;
408 let mapped = slice.get_mapped_range();
409 let status: &[u32] = bytemuck::cast_slice(&mapped[self.bytes as usize..]);
410 if status[0] > 0 {
411 let error=SpatialError::InvalidArgument(format!("GPU FPFH rejected {} incomplete/malformed neighborhood rows; last row {}, required capacity {}, malformed rows {}",status[0],status[1].saturating_sub(1),status[2],status[3]));
412 drop(mapped);
413 staging.unmap();
414 return Err(error);
415 }
416 let descriptors = bytemuck::cast_slice::<u8, f32>(&mapped[..self.bytes as usize])
417 .chunks_exact(GPU_FPFH_DESCRIPTOR_LEN)
418 .map(|row| row.try_into().expect("FPFH rows contain exactly 33 values"))
419 .collect();
420 drop(mapped);
421 staging.unmap();
422 let mut transfers = TransferStats::default();
423 transfers.record(TransferDirection::DeviceToHost, self.bytes + 16);
424 Ok((descriptors, transfers))
425 }
426}
427
428pub(crate) struct FpfhPipelines {
429 layout: wgpu::BindGroupLayout,
430 spfh: wgpu::ComputePipeline,
431 fpfh: wgpu::ComputePipeline,
432}
433impl FpfhPipelines {
434 fn new(device: &wgpu::Device) -> Self {
435 let entries: Vec<_> = (0..6)
436 .map(|binding| wgpu::BindGroupLayoutEntry {
437 binding,
438 visibility: wgpu::ShaderStages::COMPUTE,
439 ty: wgpu::BindingType::Buffer {
440 ty: if binding == 0 {
441 wgpu::BufferBindingType::Uniform
442 } else {
443 wgpu::BufferBindingType::Storage { read_only: binding < 3 }
444 },
445 has_dynamic_offset: false,
446 min_binding_size: None,
447 },
448 count: None,
449 })
450 .collect();
451 let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
452 label: Some("fpfh-layout"),
453 entries: &entries,
454 });
455 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
456 label: Some("fpfh-layout"),
457 bind_group_layouts: &[&layout],
458 push_constant_ranges: &[],
459 });
460 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
461 label: Some("fpfh-shader"),
462 source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/fpfh.wgsl").into()),
463 });
464 let create = |entry| {
465 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
466 label: Some("fpfh-pipeline"),
467 layout: Some(&pipeline_layout),
468 module: &shader,
469 entry_point: Some(entry),
470 compilation_options: Default::default(),
471 cache: None,
472 })
473 };
474 Self { spfh: create("build_spfh"), fpfh: create("build_fpfh"), layout }
475 }
476}
477
478#[cfg(all(test, not(target_arch = "wasm32")))]
479#[path = "fpfh_tests.rs"]
480mod tests;
481
482#[cfg(all(test, not(target_arch = "wasm32")))]
483#[path = "fpfh_soa_upload_reference.rs"]
484pub(crate) mod soa_upload_reference;
485
486#[cfg(all(test, not(target_arch = "wasm32")))]
487#[path = "fpfh_validation_reference.rs"]
488pub(crate) mod validation_reference;