1use crate::{scratch::ScratchBuffers, GpuKdTree, GpuQueryBatch, WgpuRuntime};
2use bytemuck::{Pod, Zeroable};
3use spatialrust_core::{SpatialError, SpatialResult, TransferDirection, TransferStats};
4use spatialrust_math::Isometry3;
5use spatialrust_search::KdTree;
6use std::sync::Arc;
7use wgpu::util::DeviceExt;
8
9const RESULT_BYTES: u64 = 176;
10
11#[path = "icp_geometry_preparation.rs"]
12mod geometry_preparation;
13
14#[path = "icp_trim.rs"]
15pub(crate) mod trim;
16
17#[repr(C)]
18#[derive(Clone, Copy, Pod, Zeroable)]
19struct Params {
20 rows: [[f32; 4]; 3],
21 source_anchor: [f32; 4],
22 target_anchor: [f32; 4],
23 count: u32,
24 targets: u32,
25 groups: u32,
26 unused: u32,
27 bound: f32,
28 max_distance: f32,
29 scale: f32,
30 padding: f32,
31}
32
33fn invalid() -> SpatialError {
34 SpatialError::InvalidArgument("GPU ICP reduction requires matching runtime, finite XYZ/extents, a finite unit-quaternion transform, a positive finite nonzero distance square, nonempty target and supported limits".to_owned())
35}
36
37fn plan(count: u64, limits: &wgpu::Limits) -> SpatialResult<u32> {
38 let groups = count.div_ceil(64).min(256);
39 let bound = limits.max_buffer_size.min(u64::from(limits.max_storage_buffer_binding_size));
40 if count > u64::from(u32::MAX)
41 || count.checked_mul(16).map_or(true, |n| n > bound || n > isize::MAX as u64)
42 || groups * 144 > bound
43 || bound < RESULT_BYTES
44 || limits.max_compute_workgroups_per_dimension < 9
45 || count.div_ceil(64) > u64::from(limits.max_compute_workgroups_per_dimension)
46 || limits.max_compute_workgroup_size_x < 64
47 || limits.max_compute_workgroup_size_y == 0
48 || limits.max_compute_workgroup_size_z == 0
49 || limits.max_compute_invocations_per_workgroup < 64
50 || limits.max_compute_workgroup_storage_size < 768
51 || limits.max_storage_buffers_per_shader_stage < 6
52 || limits.max_bindings_per_bind_group < 7
53 || limits.max_bind_groups == 0
54 || limits.max_uniform_buffers_per_shader_stage == 0
55 || limits.max_uniform_buffer_binding_size < 112
56 {
57 return Err(invalid());
58 }
59 Ok(groups as u32)
60}
61
62fn geometry(points: &[[f32; 3]]) -> SpatialResult<([f32; 4], f64)> {
63 geometry_preparation::prepare(points)
64}
65
66pub struct GpuIcpInput {
70 pub(super) source: GpuQueryBatch,
71 pub(super) target: GpuQueryBatch,
72 pub(super) tree: GpuKdTree,
73 pub(super) source_anchor: [f32; 4],
74 target_anchor: [f32; 4],
75 pub(super) scale: f32,
76 pub(super) identity: Arc<()>,
77 transfers: TransferStats,
78}
79
80impl GpuIcpInput {
81 pub fn upload(
89 runtime: &WgpuRuntime,
90 source: &[[f32; 3]],
91 target: &KdTree,
92 ) -> SpatialResult<Self> {
93 Self::upload_impl(runtime, source, target, false)
94 }
95
96 pub fn upload_with_gpu_gather(
107 runtime: &WgpuRuntime,
108 source: &[[f32; 3]],
109 target: &KdTree,
110 ) -> SpatialResult<Self> {
111 Self::upload_impl(runtime, source, target, true)
112 }
113
114 fn upload_impl(
115 runtime: &WgpuRuntime,
116 source: &[[f32; 3]],
117 target: &KdTree,
118 gpu_gather: bool,
119 ) -> SpatialResult<Self> {
120 plan(source.len() as u64, &runtime.device().limits())?;
121 let layout = target.layout();
122 let (x, y, z) = layout.positions();
123 plan(x.len() as u64, &runtime.device().limits())?;
124 if x.is_empty() {
125 return Err(invalid());
126 }
127 let (source_anchor, source_extent) = geometry(source)?;
128 let (target_anchor, target_extent) = geometry_preparation::prepare_soa([x, y, z])?;
129 let extent = source_extent.max(target_extent);
130 if extent > 0.0 && (extent as f32) < f32::MIN_POSITIVE {
131 return Err(invalid());
132 }
133 let scale = if extent == 0.0 { 1.0 } else { extent.sqrt() as f32 };
134 let (tree, gathered_target) = if gpu_gather {
135 let (tree, queries) = GpuKdTree::upload_and_queries_with_gpu_gather(runtime, target)?;
136 (tree, Some(queries))
137 } else {
138 (GpuKdTree::upload(runtime, target)?, None)
139 };
140 let source = GpuQueryBatch::upload(runtime, source)?;
141 let target = match gathered_target {
142 Some(queries) => queries,
143 None => GpuQueryBatch::upload_soa(runtime, [x, y, z])?,
144 };
145 let mut transfers = tree.upload_transfers();
146 transfers.record(
147 TransferDirection::HostToDevice,
148 source.upload_transfers().host_to_device_bytes(),
149 );
150 transfers.record(
151 TransferDirection::HostToDevice,
152 target.upload_transfers().host_to_device_bytes(),
153 );
154 transfers.record(
155 TransferDirection::DeviceToDevice,
156 target.upload_transfers().device_to_device_bytes(),
157 );
158 Ok(Self {
159 source,
160 target,
161 tree,
162 source_anchor,
163 target_anchor,
164 scale,
165 identity: runtime.profiling_identity(),
166 transfers,
167 })
168 }
169
170 #[must_use]
172 pub const fn upload_transfers(&self) -> TransferStats {
173 self.transfers
174 }
175
176 #[must_use]
178 pub fn source_count(&self) -> u32 {
179 self.source.query_count()
180 }
181
182 pub fn moments_resident(
190 &self,
191 runtime: &WgpuRuntime,
192 transform: Isometry3<f32>,
193 max_distance: f32,
194 ) -> SpatialResult<GpuIcpMoments> {
195 self.moments_impl(
196 runtime,
197 transform,
198 max_distance,
199 None,
200 trim::GpuIcpTrimPrecision::DoubleSingle,
201 )
202 }
203
204 pub fn trimmed_moments_resident(
212 &self,
213 runtime: &WgpuRuntime,
214 transform: Isometry3<f32>,
215 max_distance: f32,
216 fraction: f64,
217 ) -> SpatialResult<GpuIcpTrimmedMoments> {
218 self.trimmed_moments_resident_with_precision(
219 runtime,
220 transform,
221 max_distance,
222 fraction,
223 trim::GpuIcpTrimPrecision::DoubleSingle,
224 )
225 }
226
227 pub fn trimmed_moments_resident_with_precision(
233 &self,
234 runtime: &WgpuRuntime,
235 transform: Isometry3<f32>,
236 max_distance: f32,
237 fraction: f64,
238 precision: trim::GpuIcpTrimPrecision,
239 ) -> SpatialResult<GpuIcpTrimmedMoments> {
240 if !fraction.is_finite() || fraction <= 0.0 || fraction > 1.0 {
241 return Err(SpatialError::InvalidArgument(
242 "trim_fraction must be finite and in (0, 1]".to_owned(),
243 ));
244 }
245 let trimmed = fraction < 1.0;
246 let inner = self.moments_impl(
247 runtime,
248 transform,
249 max_distance,
250 trimmed.then_some(fraction),
251 precision,
252 )?;
253 Ok(GpuIcpTrimmedMoments { inner, trimmed })
254 }
255
256 fn moments_impl(
257 &self,
258 runtime: &WgpuRuntime,
259 transform: Isometry3<f32>,
260 max_distance: f32,
261 fraction: Option<f64>,
262 precision: trim::GpuIcpTrimPrecision,
263 ) -> SpatialResult<GpuIcpMoments> {
264 let q = transform.rotation();
265 let t = transform.translation();
266 let norm = f64::from(q.x).hypot(f64::from(q.y)).hypot(f64::from(q.z)).hypot(f64::from(q.w));
267 let bound = max_distance * max_distance;
268 if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity())
269 || !norm.is_finite()
270 || (norm - 1.0).abs() > 1e-4
271 || !t.x.is_finite()
272 || !t.y.is_finite()
273 || !t.z.is_finite()
274 || !max_distance.is_finite()
275 || max_distance <= 0.0
276 || !bound.is_finite()
277 || bound == 0.0
278 {
279 return Err(invalid());
280 }
281 let count = self.source_count();
282 let groups = if fraction.is_some() {
283 trim::plan_trim(u64::from(count), &runtime.device().limits())?
284 } else {
285 plan(u64::from(count), &runtime.device().limits())?
286 };
287 let output = GpuIcpMoments {
288 buffer: runtime.device().create_buffer(&wgpu::BufferDescriptor {
289 label: Some("icp-moments"),
290 size: RESULT_BYTES,
291 usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
292 mapped_at_creation: false,
293 }),
294 count,
295 scale: self.scale,
296 bound,
297 identity: Arc::clone(&self.identity),
298 };
299 if count == 0 {
300 return Ok(output);
301 }
302 let r = transform.rotation().to_mat3();
303 let params = Params {
304 rows: [
305 [r.m[0][0], r.m[0][1], r.m[0][2], t.x],
306 [r.m[1][0], r.m[1][1], r.m[1][2], t.y],
307 [r.m[2][0], r.m[2][1], r.m[2][2], t.z],
308 ],
309 source_anchor: self.source_anchor,
310 target_anchor: self.target_anchor,
311 count,
312 targets: self.target.query_count(),
313 groups,
314 unused: 0,
315 bound,
316 max_distance,
317 scale: self.scale,
318 padding: 0.0,
319 };
320 let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
321 label: Some("icp-reduction-params"),
322 contents: bytemuck::bytes_of(¶ms),
323 usage: wgpu::BufferUsages::UNIFORM,
324 });
325 let mut scratch = ScratchBuffers::new(runtime);
326 let queries = scratch.acquire("icp-transformed", u64::from(count) * 16);
327 let matches = scratch.acquire("icp-matches", u64::from(count) * 8);
328 let partials = scratch.acquire("icp-partials", u64::from(groups) * 144);
329 let selection = fraction.map(|_| scratch.acquire("icp-trim-selection", 32));
330 let cache = if fraction.is_some() {
331 runtime
332 .icp_trim_pipelines
333 .get_or_init(|| trim::TrimPipelines::new(runtime.device()))
334 .reduction(runtime.device(), precision)
335 } else {
336 runtime
337 .icp_reduction_pipelines
338 .get_or_init(|| IcpReductionPipelines::new(runtime.device()))
339 };
340 let mut buffers = vec![
341 &uniform,
342 self.source.buffer().unwrap(),
343 self.target.buffer().unwrap(),
344 &queries,
345 &matches,
346 &partials,
347 &output.buffer,
348 ];
349 if let Some(selection) = &selection {
350 buffers.push(selection);
351 }
352 let entries: Vec<_> = buffers
353 .iter()
354 .enumerate()
355 .map(|(binding, buffer)| wgpu::BindGroupEntry {
356 binding: binding as u32,
357 resource: buffer.as_entire_binding(),
358 })
359 .collect();
360 let group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
361 label: Some("icp-reduction-bindings"),
362 layout: &cache.layout,
363 entries: &entries,
364 });
365 let mut encoder = runtime.device().create_command_encoder(&Default::default());
366 dispatch(&mut encoder, &cache.pipelines[0], &group, count.div_ceil(64), 1);
367 self.tree.encode_nearest(runtime, &mut encoder, &queries, count, bound, &matches)?;
368 if let Some(fraction) = fraction {
369 trim::encode_selection(
370 runtime,
371 &mut encoder,
372 &mut scratch,
373 ¶ms,
374 fraction,
375 &matches,
376 selection.as_ref().unwrap(),
377 );
378 }
379 for (index, x, y) in [(1, groups, 7), (2, 1, 1), (3, groups, 9), (4, 1, 1)] {
380 dispatch(&mut encoder, &cache.pipelines[index], &group, x, y);
381 }
382 scratch.submit_and_recycle(encoder);
383 Ok(output)
384 }
385}
386
387fn dispatch(
388 encoder: &mut wgpu::CommandEncoder,
389 pipeline: &wgpu::ComputePipeline,
390 group: &wgpu::BindGroup,
391 x: u32,
392 y: u32,
393) {
394 let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
395 label: Some("icp-reduction"),
396 timestamp_writes: None,
397 });
398 pass.set_pipeline(pipeline);
399 pass.set_bind_group(0, group, &[]);
400 pass.dispatch_workgroups(x, y, 1);
401}
402
403#[derive(Clone, Debug, PartialEq)]
405pub struct GpuIcpStatistics {
406 pub correspondences: u32,
409 pub source_centroid: [f64; 3],
411 pub target_centroid: [f64; 3],
413 pub cross_covariance: [[f64; 3]; 3],
415 pub squared_error_sum: f64,
418 pub transfers: TransferStats,
420}
421
422pub struct GpuIcpMoments {
424 buffer: wgpu::Buffer,
425 count: u32,
426 scale: f32,
427 bound: f32,
428 identity: Arc<()>,
429}
430impl GpuIcpMoments {
431 #[must_use]
433 pub const fn normalization_scale(&self) -> f32 {
434 self.scale
435 }
436
437 #[must_use]
439 pub const fn squared_distance_scale(&self) -> f32 {
440 self.bound
441 }
442
443 #[must_use]
455 pub fn buffer(&self) -> &wgpu::Buffer {
456 &self.buffer
457 }
458
459 #[must_use]
461 pub const fn readback_bytes(&self) -> u64 {
462 if self.count == 0 {
463 0
464 } else {
465 RESULT_BYTES
466 }
467 }
468
469 pub fn download(&self, runtime: &WgpuRuntime) -> SpatialResult<GpuIcpStatistics> {
472 self.download_impl(runtime, false).map(|(statistics, _)| statistics)
473 }
474
475 fn download_impl(
476 &self,
477 runtime: &WgpuRuntime,
478 trimmed: bool,
479 ) -> SpatialResult<(GpuIcpStatistics, u32)> {
480 if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity()) {
481 return Err(invalid());
482 }
483 let mut transfers = TransferStats::default();
484 let mut words = vec![0u32; RESULT_BYTES as usize / 4];
485 if self.count > 0 {
486 let staging = runtime.device().create_buffer(&wgpu::BufferDescriptor {
487 label: Some("icp-moments-readback"),
488 size: RESULT_BYTES,
489 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
490 mapped_at_creation: false,
491 });
492 let mut encoder = runtime.device().create_command_encoder(&Default::default());
493 encoder.copy_buffer_to_buffer(&self.buffer, 0, &staging, 0, RESULT_BYTES);
494 runtime.queue().submit(Some(encoder.finish()));
495 let slice = staging.slice(..);
496 let (sender, receiver) = std::sync::mpsc::channel();
497 slice.map_async(wgpu::MapMode::Read, move |r| {
498 let _ = sender.send(r);
499 });
500 runtime.device().poll(wgpu::Maintain::Wait);
501 receiver
502 .recv()
503 .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?
504 .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?;
505 let mapped = slice.get_mapped_range();
506 words.copy_from_slice(bytemuck::cast_slice(&mapped));
507 drop(mapped);
508 staging.unmap();
509 transfers.record(TransferDirection::DeviceToHost, RESULT_BYTES);
510 }
511 let evaluated = if trimmed { words[2] } else { words[1] };
512 if words[0] != 0
513 || words[1] > evaluated
514 || evaluated > self.count
515 || words[3] != 0
516 || (!trimmed && words[2] != 0)
517 || (evaluated == 0 && words[4..].iter().any(|&v| v != 0))
518 || (words[1] == 0 && words[4..42].iter().any(|&v| v != 0))
519 {
520 return Err(SpatialError::InvalidArgument(format!(
521 "GPU ICP reduction invalid status/count: {:?}",
522 &words[..4]
523 )));
524 }
525 let values: Vec<_> = words[4..].iter().map(|&v| f64::from(f32::from_bits(v))).collect();
526 if values.iter().any(|v| !v.is_finite()) {
527 return Err(invalid());
528 }
529 let sum = |term: usize| values[8 + term * 2] + values[9 + term * 2];
530 let scale = f64::from(self.scale);
531 let source_centroid =
532 std::array::from_fn(|i| if words[1] == 0 { 0.0 } else { values[i] + sum(i) * scale });
533 let target_centroid = std::array::from_fn(|i| {
534 if words[1] == 0 {
535 0.0
536 } else {
537 values[4 + i] + sum(3 + i) * scale
538 }
539 });
540 let cross_covariance =
541 std::array::from_fn(|i| std::array::from_fn(|j| sum(6 + i * 3 + j) * scale * scale));
542 let squared_error_sum = sum(15) * f64::from(self.bound);
543 if squared_error_sum < 0.0 {
544 return Err(invalid());
545 }
546 Ok((
547 GpuIcpStatistics {
548 correspondences: words[1],
549 source_centroid,
550 target_centroid,
551 cross_covariance,
552 squared_error_sum,
553 transfers,
554 },
555 evaluated,
556 ))
557 }
558}
559
560#[derive(Clone, Debug, PartialEq)]
562pub struct GpuIcpTrimmedStatistics {
563 pub moments: GpuIcpStatistics,
565 pub evaluated_correspondences: u32,
567}
568
569pub struct GpuIcpTrimmedMoments {
571 inner: GpuIcpMoments,
572 trimmed: bool,
573}
574
575impl GpuIcpTrimmedMoments {
576 #[must_use]
582 pub fn buffer(&self) -> &wgpu::Buffer {
583 self.inner.buffer()
584 }
585
586 #[must_use]
588 pub const fn readback_bytes(&self) -> u64 {
589 self.inner.readback_bytes()
590 }
591
592 #[must_use]
594 pub const fn normalization_scale(&self) -> f32 {
595 self.inner.normalization_scale()
596 }
597
598 #[must_use]
600 pub const fn squared_distance_scale(&self) -> f32 {
601 self.inner.squared_distance_scale()
602 }
603
604 pub fn download(&self, runtime: &WgpuRuntime) -> SpatialResult<GpuIcpTrimmedStatistics> {
606 let (moments, evaluated_correspondences) =
607 self.inner.download_impl(runtime, self.trimmed)?;
608 Ok(GpuIcpTrimmedStatistics { moments, evaluated_correspondences })
609 }
610}
611
612pub(crate) struct IcpReductionPipelines {
613 layout: wgpu::BindGroupLayout,
614 pipelines: [wgpu::ComputePipeline; 5],
615}
616impl IcpReductionPipelines {
617 fn new(device: &wgpu::Device) -> Self {
618 Self::with_shader(device, include_str!("../shaders/icp_reduction.wgsl"), false)
619 }
620
621 fn with_shader(device: &wgpu::Device, shader_source: &str, trimmed: bool) -> Self {
622 let entries: Vec<_> = (0..if trimmed { 8 } else { 7 })
623 .map(|binding| wgpu::BindGroupLayoutEntry {
624 binding,
625 visibility: wgpu::ShaderStages::COMPUTE,
626 ty: wgpu::BindingType::Buffer {
627 ty: if binding == 0 {
628 wgpu::BufferBindingType::Uniform
629 } else {
630 wgpu::BufferBindingType::Storage {
631 read_only: matches!(binding, 1 | 2 | 4 | 7),
632 }
633 },
634 has_dynamic_offset: false,
635 min_binding_size: None,
636 },
637 count: None,
638 })
639 .collect();
640 let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
641 label: Some("icp-reduction-layout"),
642 entries: &entries,
643 });
644 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
645 label: Some("icp-reduction-layout"),
646 bind_group_layouts: &[&layout],
647 push_constant_ranges: &[],
648 });
649 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
650 label: Some("icp-reduction-shader"),
651 source: wgpu::ShaderSource::Wgsl(shader_source.into()),
652 });
653 let pipelines = [
654 "transform_source",
655 "centroid_partials",
656 "finish_centroids",
657 "covariance_partials",
658 "finish_covariance",
659 ]
660 .map(|entry| {
661 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
662 label: Some("icp-reduction-pipeline"),
663 layout: Some(&pipeline_layout),
664 module: &shader,
665 entry_point: Some(entry),
666 compilation_options: Default::default(),
667 cache: None,
668 })
669 });
670 Self { layout, pipelines }
671 }
672}
673
674#[cfg(all(test, not(target_arch = "wasm32")))]
675#[path = "icp_reduction_tests.rs"]
676mod tests;
677
678#[cfg(all(test, not(target_arch = "wasm32")))]
679#[path = "icp_reduction_gather_reference.rs"]
680pub(crate) mod gather_reference;