Skip to main content

threecrate_gpu/
icp.rs

1//! GPU-accelerated ICP
2//!
3//! The target cloud is uploaded once as a kd-tree. Each iteration runs one
4//! kernel that moves every source point by the current estimate, finds its
5//! nearest target point in the tree (starting from last iteration's match), and
6//! sums the values the update needs within each workgroup. Only those small
7//! per-workgroup sums come back to the CPU.
8
9use crate::device::workgroup_grid;
10use crate::spatial::{morton_order, vec4s, GpuKdTree, KD_TREE_WGSL};
11use crate::GpuContext;
12use bytemuck::{Pod, Zeroable};
13use nalgebra::{Isometry3, Matrix3, Matrix6, Translation3, UnitQuaternion, Vector3, Vector6};
14use threecrate_algorithms::{icp_converged, rigid_transform_from_sums, CloudScale};
15use threecrate_core::{Error, Point3f, PointCloud, Result, Vector3f};
16
17/// Sums per workgroup for point-to-point: count, source sum (3), target sum
18/// (3), source * target^T (9), squared distance, distance.
19const STATS_POINT: usize = 18;
20/// Sums per workgroup for point-to-plane: count, squared residual, the upper
21/// triangle of A^T A (21), and A^T b (6).
22const STATS_PLANE: usize = 29;
23/// Workgroup size of the matching kernels (`WG` in WGSL).
24const WORKGROUP: usize = 128;
25
26fn icp_match_shader() -> String {
27    format!(
28        "{}{}",
29        KD_TREE_WGSL,
30        r#"
31struct IcpParams {
32    // Rows of the current transform; w holds the translation.
33    row0: vec4<f32>,
34    row1: vec4<f32>,
35    row2: vec4<f32>,
36    num_source: u32,
37    max_dist_sq: f32,
38    use_seed: u32,
39    _pad: u32,
40}
41
42const WG: u32 = 128u;
43
44@group(0) @binding(1) var<storage, read> source: array<vec4<f32>>;
45// Matched node per source point (NO_NODE if none); also the seed for the next
46// iteration's search.
47@group(0) @binding(2) var<storage, read_write> matches: array<u32>;
48// Sums per workgroup.
49@group(0) @binding(3) var<storage, read_write> partials: array<f32>;
50@group(0) @binding(4) var<uniform> params: IcpParams;
51// Target normals by original target index (point-to-plane only).
52@group(0) @binding(5) var<storage, read> target_normals: array<vec4<f32>>;
53
54var<workgroup> scratch_point: array<f32, 2304>; // WG * 18
55var<workgroup> scratch_plane: array<f32, 3712>; // WG * 29
56
57struct Match {
58    found: Nearest,
59    moved: vec3<f32>,
60}
61
62// Move source point `i` by the current transform and find its nearest target.
63fn match_point(i: u32) -> Match {
64    let p = source[i].xyz;
65    let q = vec3<f32>(
66        dot(params.row0.xyz, p) + params.row0.w,
67        dot(params.row1.xyz, p) + params.row1.w,
68        dot(params.row2.xyz, p) + params.row2.w,
69    );
70    var seed = NO_NODE;
71    if (params.use_seed == 1u) {
72        seed = matches[i];
73    }
74    let found = find_nearest(q, params.max_dist_sq, seed);
75    matches[i] = found.node;
76    return Match(found, q);
77}
78
79@compute @workgroup_size(128)
80fn icp_match(
81    @builtin(global_invocation_id) gid: vec3<u32>,
82    @builtin(local_invocation_id) lid: vec3<u32>,
83    @builtin(workgroup_id) wid: vec3<u32>,
84    @builtin(num_workgroups) nwg: vec3<u32>,
85) {
86    // Large clouds spread groups over x and y (65,535 per dimension).
87    let group = wid.x + wid.y * nwg.x;
88    let i = group * WG + lid.x;
89    const STATS: u32 = 18u;
90    var s: array<f32, 18>;
91    for (var j = 0u; j < STATS; j++) {
92        s[j] = 0.0;
93    }
94
95    if (i < params.num_source) {
96        let m = match_point(i);
97        if (m.found.node != NO_NODE) {
98            let q = m.moved;
99            let t = nodes[m.found.node].pos;
100            s[0] = 1.0;
101            s[1] = q.x; s[2] = q.y; s[3] = q.z;
102            s[4] = t.x; s[5] = t.y; s[6] = t.z;
103            s[7] = q.x * t.x; s[8] = q.x * t.y; s[9] = q.x * t.z;
104            s[10] = q.y * t.x; s[11] = q.y * t.y; s[12] = q.y * t.z;
105            s[13] = q.z * t.x; s[14] = q.z * t.y; s[15] = q.z * t.z;
106            s[16] = m.found.dist_sq;
107            s[17] = sqrt(m.found.dist_sq);
108        }
109    }
110
111    // Tree reduction of the per-point values within the workgroup.
112    let base = lid.x * STATS;
113    for (var j = 0u; j < STATS; j++) {
114        scratch_point[base + j] = s[j];
115    }
116    workgroupBarrier();
117    var stride = WG / 2u;
118    loop {
119        if (stride == 0u) {
120            break;
121        }
122        if (lid.x < stride) {
123            let other = (lid.x + stride) * STATS;
124            for (var j = 0u; j < STATS; j++) {
125                scratch_point[base + j] += scratch_point[other + j];
126            }
127        }
128        workgroupBarrier();
129        stride = stride / 2u;
130    }
131    if (lid.x == 0u) {
132        for (var j = 0u; j < STATS; j++) {
133            partials[group * STATS + j] = scratch_point[j];
134        }
135    }
136}
137
138// Point-to-plane: each match adds row a = (q x n, n) and residual
139// b = n . (t - q) to the linearised 6x6 system (Chen & Medioni 1992).
140@compute @workgroup_size(128)
141fn icp_match_plane(
142    @builtin(global_invocation_id) gid: vec3<u32>,
143    @builtin(local_invocation_id) lid: vec3<u32>,
144    @builtin(workgroup_id) wid: vec3<u32>,
145    @builtin(num_workgroups) nwg: vec3<u32>,
146) {
147    // Large clouds spread groups over x and y (65,535 per dimension).
148    let group = wid.x + wid.y * nwg.x;
149    let i = group * WG + lid.x;
150    const STATS: u32 = 29u;
151    var s: array<f32, 29>;
152    for (var j = 0u; j < STATS; j++) {
153        s[j] = 0.0;
154    }
155
156    if (i < params.num_source) {
157        let m = match_point(i);
158        if (m.found.node != NO_NODE) {
159            let node = nodes[m.found.node];
160            let n = target_normals[node.index].xyz;
161            let q = m.moved;
162            let c = cross(q, n);
163            var a = array<f32, 6>(c.x, c.y, c.z, n.x, n.y, n.z);
164            let b = dot(n, node.pos - q);
165            s[0] = 1.0;
166            s[1] = b * b;
167            var k = 2u;
168            for (var r = 0u; r < 6u; r++) {
169                for (var col = r; col < 6u; col++) {
170                    s[k] = a[r] * a[col];
171                    k += 1u;
172                }
173            }
174            for (var r = 0u; r < 6u; r++) {
175                s[23u + r] = a[r] * b;
176            }
177        }
178    }
179
180    let base = lid.x * STATS;
181    for (var j = 0u; j < STATS; j++) {
182        scratch_plane[base + j] = s[j];
183    }
184    workgroupBarrier();
185    var stride = WG / 2u;
186    loop {
187        if (stride == 0u) {
188            break;
189        }
190        if (lid.x < stride) {
191            let other = (lid.x + stride) * STATS;
192            for (var j = 0u; j < STATS; j++) {
193                scratch_plane[base + j] += scratch_plane[other + j];
194            }
195        }
196        workgroupBarrier();
197        stride = stride / 2u;
198    }
199    if (lid.x == 0u) {
200        for (var j = 0u; j < STATS; j++) {
201            partials[group * STATS + j] = scratch_plane[j];
202        }
203    }
204}
205"#
206    )
207}
208
209/// Uniform block of the matching kernels (`IcpParams` in WGSL).
210#[repr(C)]
211#[derive(Copy, Clone, Pod, Zeroable)]
212struct IcpParams {
213    row0: [f32; 4],
214    row1: [f32; 4],
215    row2: [f32; 4],
216    num_source: u32,
217    max_dist_sq: f32,
218    use_seed: u32,
219    _pad: u32,
220}
221
222/// GPU state for one ICP run: target tree, source points, and the buffers the
223/// matching kernel reads and writes. Everything stays on the GPU between
224/// iterations except the small per-workgroup sums, which are copied into one
225/// staging buffer that is reused every iteration.
226struct IcpSession<'a> {
227    gpu: &'a GpuContext,
228    tree: GpuKdTree,
229    /// Size of the source cloud (centroid and spread) in the tree's frame.
230    source_scale: CloudScale,
231    num_source: usize,
232    pipeline: &'a wgpu::ComputePipeline,
233    partials: wgpu::Buffer,
234    staging: wgpu::Buffer,
235    params: wgpu::Buffer,
236    bind_group: wgpu::BindGroup,
237    stats_len: usize,
238    max_dist_sq: f32,
239    iteration: usize,
240}
241
242impl<'a> IcpSession<'a> {
243    /// `target_normals` selects point-to-plane (`Some`) or point-to-point.
244    fn new(
245        gpu: &'a GpuContext,
246        source: &[Point3f],
247        target: &[Point3f],
248        target_normals: Option<&[Vector3f]>,
249        max_correspondence_distance: f32,
250    ) -> Result<Self> {
251        let tree = GpuKdTree::new(gpu, target)?;
252        if tree.is_empty() {
253            return Err(Error::InvalidData(
254                "Target point cloud has no finite points".to_string(),
255            ));
256        }
257        let source_local = tree.frame.points_to_local(source);
258        let source_scale = CloudScale::of(&source_local);
259
260        // Upload in Morton order so neighboring GPU threads search neighboring
261        // parts of the target tree. The sums do not depend on point order.
262        let uploaded: Vec<Point3f> = morton_order(&source_local)
263            .into_iter()
264            .map(|i| source_local[i as usize])
265            .collect();
266        let source_buffer =
267            gpu.create_buffer_init("ICP Source", &vec4s(&uploaded), wgpu::BufferUsages::STORAGE);
268        let matches = gpu.create_buffer_init(
269            "ICP Matches",
270            &vec![u32::MAX; source.len()],
271            wgpu::BufferUsages::STORAGE,
272        );
273
274        let stats_len = if target_normals.is_some() {
275            STATS_PLANE
276        } else {
277            STATS_POINT
278        };
279        // One slot of sums per workgroup in the (possibly 2-D) grid; groups past
280        // the last point write zeros.
281        let (gx, gy) = workgroup_grid(source.len().div_ceil(WORKGROUP));
282        let partials_size =
283            (gx as usize * gy as usize * stats_len * std::mem::size_of::<f32>()) as u64;
284        let partials = gpu.create_buffer(
285            "ICP Partials",
286            partials_size,
287            wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
288        );
289        let staging = gpu.create_staging_buffer("ICP Partials Staging", partials_size);
290        let params = gpu.create_buffer(
291            "ICP Params",
292            std::mem::size_of::<IcpParams>() as u64,
293            wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
294        );
295
296        let mut entries = vec![
297            wgpu::BindGroupEntry {
298                binding: 0,
299                resource: tree.nodes.as_entire_binding(),
300            },
301            wgpu::BindGroupEntry {
302                binding: 1,
303                resource: source_buffer.as_entire_binding(),
304            },
305            wgpu::BindGroupEntry {
306                binding: 2,
307                resource: matches.as_entire_binding(),
308            },
309            wgpu::BindGroupEntry {
310                binding: 3,
311                resource: partials.as_entire_binding(),
312            },
313            wgpu::BindGroupEntry {
314                binding: 4,
315                resource: params.as_entire_binding(),
316            },
317        ];
318        let normals_buffer;
319        let pipeline = if let Some(normals) = target_normals {
320            let data: Vec<[f32; 4]> = normals.iter().map(|n| [n.x, n.y, n.z, 0.0]).collect();
321            normals_buffer =
322                gpu.create_buffer_init("ICP Target Normals", &data, wgpu::BufferUsages::STORAGE);
323            entries.push(wgpu::BindGroupEntry {
324                binding: 5,
325                resource: normals_buffer.as_entire_binding(),
326            });
327            gpu.cached_pipeline(
328                &gpu.pipelines.icp_match_plane,
329                "ICP Match Plane",
330                icp_match_shader,
331                "icp_match_plane",
332            )
333        } else {
334            gpu.cached_pipeline(
335                &gpu.pipelines.icp_match,
336                "ICP Match",
337                icp_match_shader,
338                "icp_match",
339            )
340        };
341        let bind_group =
342            gpu.create_bind_group("ICP Match", &pipeline.get_bind_group_layout(0), &entries);
343
344        // Same cutoff semantics as the CPU ICP: negative rejects everything.
345        let max_dist_sq = if max_correspondence_distance < 0.0 {
346            0.0
347        } else {
348            max_correspondence_distance * max_correspondence_distance
349        };
350
351        Ok(Self {
352            gpu,
353            tree,
354            source_scale,
355            num_source: source.len(),
356            pipeline,
357            partials,
358            staging,
359            params,
360            bind_group,
361            stats_len,
362            max_dist_sq,
363            iteration: 0,
364        })
365    }
366
367    /// Match every source point (moved by `transform`, in the tree's frame) to
368    /// its nearest target point on the GPU, and return the summed statistics.
369    fn match_points(&mut self, transform: &Isometry3<f32>) -> Result<Vec<f64>> {
370        let m = transform.to_homogeneous();
371        let row = |r: usize| [m[(r, 0)], m[(r, 1)], m[(r, 2)], m[(r, 3)]];
372        let params = IcpParams {
373            row0: row(0),
374            row1: row(1),
375            row2: row(2),
376            num_source: self.num_source as u32,
377            max_dist_sq: self.max_dist_sq,
378            use_seed: (self.iteration > 0) as u32,
379            _pad: 0,
380        };
381        self.gpu
382            .queue
383            .write_buffer(&self.params, 0, bytemuck::bytes_of(&params));
384
385        let mut encoder = self
386            .gpu
387            .device
388            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
389                label: Some("ICP Match"),
390            });
391        {
392            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
393                label: Some("ICP Match"),
394                timestamp_writes: None,
395            });
396            pass.set_pipeline(self.pipeline);
397            pass.set_bind_group(0, &self.bind_group, &[]);
398            let (x, y) = workgroup_grid(self.num_source.div_ceil(WORKGROUP));
399            pass.dispatch_workgroups(x, y, 1);
400        }
401        encoder.copy_buffer_to_buffer(&self.partials, 0, &self.staging, 0, self.partials.size());
402        self.gpu.queue.submit(std::iter::once(encoder.finish()));
403        self.iteration += 1;
404
405        let partials: Vec<f32> = self.gpu.read_staging(&self.staging)?;
406        let mut totals = vec![0.0f64; self.stats_len];
407        for group in partials.chunks_exact(self.stats_len) {
408            for (total, value) in totals.iter_mut().zip(group) {
409                *total += *value as f64;
410            }
411        }
412        Ok(totals)
413    }
414
415    /// The source centroid moved by `transform`, for the convergence check.
416    fn moved_centroid(&self, transform: &Isometry3<f32>) -> Point3f {
417        transform * self.source_scale.centroid
418    }
419}
420
421/// Batch ICP operation for multiple point cloud pairs
422#[derive(Debug, Clone)]
423pub struct BatchICPJob {
424    pub source: PointCloud<Point3f>,
425    pub target: PointCloud<Point3f>,
426    pub max_iterations: usize,
427    pub convergence_threshold: f32,
428    pub max_correspondence_distance: f32,
429}
430
431/// Result of a batch ICP operation
432#[derive(Debug, Clone)]
433pub struct BatchICPResult {
434    pub transformation: Isometry3<f32>,
435    pub final_error: f32,
436    pub iterations: usize,
437}
438
439impl GpuContext {
440    /// Execute multiple ICP operations in parallel batches
441    pub async fn batch_icp_align(&self, jobs: &[BatchICPJob]) -> Result<Vec<BatchICPResult>> {
442        let mut results = Vec::with_capacity(jobs.len());
443        for job in jobs {
444            results.push(
445                self.optimized_icp_align(
446                    &job.source,
447                    &job.target,
448                    job.max_iterations,
449                    job.convergence_threshold,
450                    job.max_correspondence_distance,
451                )
452                .await?,
453            );
454        }
455        Ok(results)
456    }
457
458    /// Point-to-point ICP with GPU matching.
459    ///
460    /// Uses the same stopping rule as the CPU ICP: stop when the RMSE improves
461    /// by less than `convergence_threshold` as a fraction, or an update barely
462    /// moves the points relative to the cloud's size. `final_error` is the
463    /// mean correspondence distance of the last iteration.
464    async fn optimized_icp_align(
465        &self,
466        source: &PointCloud<Point3f>,
467        target: &PointCloud<Point3f>,
468        max_iterations: usize,
469        convergence_threshold: f32,
470        max_correspondence_distance: f32,
471    ) -> Result<BatchICPResult> {
472        if source.is_empty() || target.is_empty() {
473            return Err(Error::InvalidData("Empty point clouds".to_string()));
474        }
475
476        let mut session = IcpSession::new(
477            self,
478            &source.points,
479            &target.points,
480            None,
481            max_correspondence_distance,
482        )?;
483        let mut current = Isometry3::identity();
484        let mut previous_mse = f32::INFINITY;
485        let mut final_error = f32::INFINITY;
486        let mut iterations_used = 0;
487
488        for iteration in 0..max_iterations {
489            iterations_used = iteration + 1;
490            let s = session.match_points(&current)?;
491            let count = s[0];
492            if count < 3.0 {
493                break;
494            }
495            final_error = (s[17] / count) as f32;
496            let mse = (s[16] / count) as f32;
497
498            let delta = rigid_transform_from_sums(
499                count,
500                &Vector3::new(s[1], s[2], s[3]),
501                &Vector3::new(s[4], s[5], s[6]),
502                &Matrix3::new(s[7], s[8], s[9], s[10], s[11], s[12], s[13], s[14], s[15]),
503            )?;
504            let moved_centroid = session.moved_centroid(&current);
505            current = delta * current;
506
507            if icp_converged(
508                previous_mse,
509                mse,
510                &delta,
511                &moved_centroid,
512                session.source_scale.radius,
513                convergence_threshold,
514            ) {
515                break;
516            }
517            previous_mse = mse;
518        }
519
520        Ok(BatchICPResult {
521            transformation: session.tree.frame.transform_to_world(&current),
522            final_error,
523            iterations: iterations_used,
524        })
525    }
526
527    /// GPU-accelerated ICP alignment (original single implementation)
528    pub async fn icp_align(
529        &self,
530        source: &PointCloud<Point3f>,
531        target: &PointCloud<Point3f>,
532        max_iterations: usize,
533        convergence_threshold: f32,
534        max_correspondence_distance: f32,
535    ) -> Result<Isometry3<f32>> {
536        let result = self
537            .optimized_icp_align(
538                source,
539                target,
540                max_iterations,
541                convergence_threshold,
542                max_correspondence_distance,
543            )
544            .await?;
545        Ok(result.transformation)
546    }
547}
548
549/// Result of GPU point-to-plane ICP
550#[derive(Debug, Clone)]
551pub struct GpuPointToPlaneICPResult {
552    pub transformation: Isometry3<f32>,
553    pub final_error: f32,
554    pub iterations: usize,
555    pub converged: bool,
556}
557
558impl GpuContext {
559    /// GPU-accelerated point-to-plane ICP.
560    ///
561    /// The GPU matches points and sums the linearised 6×6 system
562    /// (Chen & Medioni 1992); the CPU only solves it. Stops with the same rule
563    /// as the CPU ICP (see [`icp_converged`]).
564    pub async fn icp_point_to_plane_align(
565        &self,
566        source: &PointCloud<Point3f>,
567        target: &PointCloud<Point3f>,
568        target_normals: &[Vector3f],
569        max_iterations: usize,
570        convergence_threshold: f32,
571        max_correspondence_distance: f32,
572    ) -> Result<GpuPointToPlaneICPResult> {
573        if source.is_empty() || target.is_empty() {
574            return Err(Error::InvalidData("Empty point clouds".to_string()));
575        }
576        if target_normals.len() != target.points.len() {
577            return Err(Error::InvalidData(
578                "target_normals length must equal target point count".to_string(),
579            ));
580        }
581
582        let mut session = IcpSession::new(
583            self,
584            &source.points,
585            &target.points,
586            Some(target_normals),
587            max_correspondence_distance,
588        )?;
589        let mut current = Isometry3::identity();
590        let mut previous_mse = f32::INFINITY;
591        let mut final_error = f32::INFINITY;
592        let mut iterations_used = 0;
593        let mut converged = false;
594
595        for iteration in 0..max_iterations {
596            iterations_used = iteration + 1;
597            let s = session.match_points(&current)?;
598            let count = s[0];
599            if count < 6.0 {
600                break;
601            }
602            let mse = (s[1] / count) as f32;
603            final_error = mse;
604
605            let delta = solve_point_to_plane(&s[2..23], &s[23..29])?;
606            let moved_centroid = session.moved_centroid(&current);
607            current = delta * current;
608
609            if icp_converged(
610                previous_mse,
611                mse,
612                &delta,
613                &moved_centroid,
614                session.source_scale.radius,
615                convergence_threshold,
616            ) {
617                converged = true;
618                break;
619            }
620            previous_mse = mse;
621        }
622
623        Ok(GpuPointToPlaneICPResult {
624            transformation: session.tree.frame.transform_to_world(&current),
625            final_error,
626            iterations: iterations_used,
627            converged,
628        })
629    }
630}
631
632/// Solve the linearised point-to-plane system `AᵀA x = Aᵀb` given the upper
633/// triangle of `AᵀA` (row-major, 21 values) and `Aᵀb`, and turn
634/// `x = (rx, ry, rz, tx, ty, tz)` into a rigid update.
635fn solve_point_to_plane(ata_upper: &[f64], atb: &[f64]) -> Result<Isometry3<f32>> {
636    let mut ata = Matrix6::<f64>::zeros();
637    let mut k = 0;
638    for r in 0..6 {
639        for c in r..6 {
640            ata[(r, c)] = ata_upper[k];
641            ata[(c, r)] = ata_upper[k];
642            k += 1;
643        }
644    }
645    let atb = Vector6::from_column_slice(atb);
646
647    let x = if let Some(chol) = ata.cholesky() {
648        chol.solve(&atb)
649    } else {
650        ata.lu().solve(&atb).ok_or_else(|| {
651            Error::Algorithm("Point-to-plane GPU system is ill-conditioned".to_string())
652        })?
653    };
654    let x = x.cast::<f32>();
655
656    let rot_x = UnitQuaternion::from_axis_angle(&nalgebra::Vector3::x_axis(), x[0]);
657    let rot_y = UnitQuaternion::from_axis_angle(&nalgebra::Vector3::y_axis(), x[1]);
658    let rot_z = UnitQuaternion::from_axis_angle(&nalgebra::Vector3::z_axis(), x[2]);
659
660    Ok(Isometry3::from_parts(
661        Translation3::new(x[3], x[4], x[5]),
662        rot_z * rot_y * rot_x,
663    ))
664}
665
666/// GPU-accelerated ICP registration
667pub async fn gpu_icp(
668    gpu_context: &GpuContext,
669    source: &PointCloud<Point3f>,
670    target: &PointCloud<Point3f>,
671    max_iterations: usize,
672    convergence_threshold: f32,
673    max_correspondence_distance: f32,
674) -> Result<Isometry3<f32>> {
675    gpu_context
676        .icp_align(
677            source,
678            target,
679            max_iterations,
680            convergence_threshold,
681            max_correspondence_distance,
682        )
683        .await
684}
685
686/// Execute batch ICP operations on multiple point cloud pairs
687pub async fn gpu_batch_icp(
688    gpu_context: &GpuContext,
689    jobs: &[BatchICPJob],
690) -> Result<Vec<BatchICPResult>> {
691    gpu_context.batch_icp_align(jobs).await
692}
693
694/// GPU-accelerated point-to-plane ICP registration.
695///
696/// The GPU finds correspondences and sums the linearised 6×6 system; the CPU
697/// only solves it (Chen & Medioni 1992).
698///
699/// # Arguments
700/// * `gpu_context`                  - Initialized GPU context
701/// * `source`                       - Source point cloud
702/// * `target`                       - Target point cloud
703/// * `target_normals`               - Surface normals at each target point
704/// * `max_iterations`               - Maximum number of iterations
705/// * `convergence_threshold`        - Stop when the RMSE improves by less than this
706///   fraction, or an update barely moves the points (same rule as the CPU ICP)
707/// * `max_correspondence_distance`  - Maximum distance for valid correspondences
708pub async fn gpu_icp_point_to_plane(
709    gpu_context: &GpuContext,
710    source: &PointCloud<Point3f>,
711    target: &PointCloud<Point3f>,
712    target_normals: &[Vector3f],
713    max_iterations: usize,
714    convergence_threshold: f32,
715    max_correspondence_distance: f32,
716) -> Result<GpuPointToPlaneICPResult> {
717    gpu_context
718        .icp_point_to_plane_align(
719            source,
720            target,
721            target_normals,
722            max_iterations,
723            convergence_threshold,
724            max_correspondence_distance,
725        )
726        .await
727}
728
729#[cfg(test)]
730mod tests {
731    use super::*;
732
733    async fn try_create_gpu_context() -> Option<GpuContext> {
734        GpuContext::new().await.ok()
735    }
736
737    /// Curved grid far from the origin, scaled by `scale`, and a copy moved by
738    /// a known transform. The move is under half the grid spacing at the
739    /// edges; larger moves can trap point-to-point ICP on a regular grid (on
740    /// the CPU as well).
741    fn test_pair(scale: f32) -> (PointCloud<Point3f>, PointCloud<Point3f>, Isometry3<f32>) {
742        let mut source = PointCloud::new();
743        for i in 0..60 {
744            for j in 0..60 {
745                let (x, y) = (i as f32 * 0.1, j as f32 * 0.1);
746                let z = 0.4 * (x * 1.1).sin() * (y * 0.8).cos();
747                source.push(Point3f::new(x + 500.0, y - 200.0, z + 10.0) * scale);
748            }
749        }
750        let centre = Translation3::new(503.0 * scale, -197.0 * scale, 10.0 * scale);
751        let truth = centre
752            * Isometry3::from_parts(
753                Translation3::new(0.02 * scale, -0.01 * scale, 0.01 * scale),
754                UnitQuaternion::from_euler_angles(0.003, -0.002, 0.01),
755            )
756            * centre.inverse();
757        let target = PointCloud::from_points(source.points.iter().map(|p| truth * p).collect());
758        (source, target, truth)
759    }
760
761    fn max_point_error(
762        estimate: &Isometry3<f32>,
763        truth: &Isometry3<f32>,
764        cloud: &[Point3f],
765    ) -> f32 {
766        cloud
767            .iter()
768            .map(|p| (estimate * p - truth * p).norm())
769            .fold(0.0, f32::max)
770    }
771
772    #[test]
773    fn test_gpu_icp_recovers_known_transform() {
774        pollster::block_on(async {
775            let Some(gpu) = try_create_gpu_context().await else {
776                return;
777            };
778            let (source, target, truth) = test_pair(1.0);
779            let estimate = gpu_icp(&gpu, &source, &target, 50, 1e-7, 1.0)
780                .await
781                .unwrap();
782            let error = max_point_error(&estimate, &truth, &source.points);
783            assert!(error < 1e-3, "GPU ICP points are {error} m off");
784
785            // Same answer as the CPU implementation
786            let cpu = threecrate_algorithms::icp_point_to_point(
787                &source,
788                &target,
789                Isometry3::identity(),
790                50,
791                1e-7,
792                Some(1.0),
793            )
794            .unwrap();
795            let gap = max_point_error(&estimate, &cpu.transformation, &source.points);
796            assert!(gap < 1e-3, "GPU and CPU ICP differ by {gap} m");
797        });
798    }
799
800    #[test]
801    fn test_gpu_icp_convergence_is_scale_invariant() {
802        // The same problem at full and 1000x scale must stop at the same point
803        // and be solved just as well. An absolute translation threshold made
804        // the stopping point depend on the scene size: rounding noise in a large
805        // scene stayed above it, so ICP never stopped.
806        pollster::block_on(async {
807            let Some(gpu) = try_create_gpu_context().await else {
808                return;
809            };
810            let mut runs = Vec::new();
811            for scale in [1.0f32, 1000.0] {
812                let (source, target, truth) = test_pair(scale);
813                let result = gpu
814                    .optimized_icp_align(&source, &target, 50, 1e-5, scale)
815                    .await
816                    .unwrap();
817                let error = max_point_error(&result.transformation, &truth, &source.points) / scale;
818                assert!(error < 1e-3, "scale {scale}: {error} (relative) off");
819                runs.push(result.iterations);
820            }
821            assert!(
822                runs[0].abs_diff(runs[1]) <= 1,
823                "iterations differ with scale: {runs:?}"
824            );
825        });
826    }
827
828    #[test]
829    fn test_gpu_point_to_plane_recovers_known_transform() {
830        pollster::block_on(async {
831            let Some(gpu) = try_create_gpu_context().await else {
832                return;
833            };
834            let (source, target, truth) = test_pair(1.0);
835            let normals: Vec<Vector3f> = threecrate_algorithms::estimate_normals(&target, 10)
836                .unwrap()
837                .points
838                .iter()
839                .map(|p| p.normal)
840                .collect();
841            let result = gpu_icp_point_to_plane(&gpu, &source, &target, &normals, 50, 1e-7, 1.0)
842                .await
843                .unwrap();
844            let error = max_point_error(&result.transformation, &truth, &source.points);
845            assert!(
846                error < 1e-3,
847                "GPU point-to-plane ICP points are {error} m off"
848            );
849            assert!(result.converged);
850        });
851    }
852}