Skip to main content

spatialrust_gpu/kernels/
covariances_grid.rs

1use bytemuck::{Pod, Zeroable};
2use spatialrust_core::{SpatialError, SpatialResult, TransferStats};
3
4use super::point_estimators::{self, Kind};
5use crate::runtime::WgpuRuntime;
6
7#[repr(C)]
8#[derive(Clone, Copy, Debug, Pod, Zeroable)]
9struct CovUniform {
10    origin: [f32; 4],
11    dims: [u32; 4], // dimx, dimy, dimz, point_count
12    inv_cell: f32,
13    radius_sq: f32,
14    epsilon: f32,
15    _pad: f32,
16}
17
18/// Per-point plane-regularized covariance as 6 unique elements:
19/// `[c00, c11, c22, c01, c02, c12]`.
20pub type GpuCovariance = [f32; 6];
21
22pub(crate) const COV_GRID_WGSL: &str = r#"
23struct Params {
24    origin: vec4<f32>,
25    dims: vec4<u32>,
26    inv_cell: f32,
27    radius_sq: f32,
28    epsilon: f32,
29    pad: f32,
30};
31
32@group(0) @binding(0) var<uniform> params: Params;
33@group(0) @binding(1) var<storage, read> xs: array<f32>;
34@group(0) @binding(2) var<storage, read> ys: array<f32>;
35@group(0) @binding(3) var<storage, read> zs: array<f32>;
36@group(0) @binding(4) var<storage, read> sorted: array<u32>;
37@group(0) @binding(5) var<storage, read> cell_start: array<u32>;
38@group(0) @binding(6) var<storage, read_write> out_cov: array<vec4<f32>>;
39
40fn rotate(a: ptr<function, array<vec3<f32>, 3>>,
41          v: ptr<function, array<vec3<f32>, 3>>,
42          p: u32, q: u32) {
43    let apq = (*a)[p][q];
44    if (abs(apq) < 1e-20) {
45        return;
46    }
47    let app = (*a)[p][p];
48    let aqq = (*a)[q][q];
49    let phi = 0.5 * (aqq - app) / apq;
50    var t: f32;
51    if (phi >= 0.0) {
52        t = 1.0 / (phi + sqrt(1.0 + phi * phi));
53    } else {
54        t = -1.0 / (-phi + sqrt(1.0 + phi * phi));
55    }
56    let c = 1.0 / sqrt(1.0 + t * t);
57    let s = t * c;
58    for (var r: u32 = 0u; r < 3u; r = r + 1u) {
59        let arp = (*a)[r][p];
60        let arq = (*a)[r][q];
61        (*a)[r][p] = c * arp - s * arq;
62        (*a)[r][q] = s * arp + c * arq;
63    }
64    for (var r: u32 = 0u; r < 3u; r = r + 1u) {
65        let apr = (*a)[p][r];
66        let aqr = (*a)[q][r];
67        (*a)[p][r] = c * apr - s * aqr;
68        (*a)[q][r] = s * apr + c * aqr;
69    }
70    for (var r: u32 = 0u; r < 3u; r = r + 1u) {
71        let vrp = (*v)[r][p];
72        let vrq = (*v)[r][q];
73        (*v)[r][p] = c * vrp - s * vrq;
74        (*v)[r][q] = s * vrp + c * vrq;
75    }
76}
77
78fn cell_coord(value: f32, origin: f32, inv_cell: f32, dim: u32) -> i32 {
79    let c = i32(floor((value - origin) * inv_cell));
80    return clamp(c, 0, i32(dim) - 1);
81}
82
83@compute @workgroup_size(256)
84fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
85    let i = gid.x;
86    if (i >= params.dims.w) {
87        return;
88    }
89    let px = xs[i];
90    let py = ys[i];
91    let pz = zs[i];
92    let dimx = params.dims.x;
93    let dimy = params.dims.y;
94    let dimz = params.dims.z;
95    let cx = cell_coord(px, params.origin.x, params.inv_cell, dimx);
96    let cy = cell_coord(py, params.origin.y, params.inv_cell, dimy);
97    let cz = cell_coord(pz, params.origin.z, params.inv_cell, dimz);
98    // Adjacent x cells occupy one contiguous counting-sort interval.
99    let first_x = u32(max(cx - 1, 0));
100    let after_x = u32(min(cx + 1, i32(dimx) - 1)) + 1u;
101
102    var mean = vec3<f32>(0.0, 0.0, 0.0);
103    var count = 0.0;
104    for (var dz = -1; dz <= 1; dz = dz + 1) {
105        let nz = cz + dz;
106        if (nz < 0 || nz >= i32(dimz)) { continue; }
107        for (var dy = -1; dy <= 1; dy = dy + 1) {
108            let ny = cy + dy;
109            if (ny < 0 || ny >= i32(dimy)) { continue; }
110            let row = (u32(nz) * dimy + u32(ny)) * dimx;
111            let begin = cell_start[row + first_x];
112            let end = cell_start[row + after_x];
113            for (var s = begin; s < end; s = s + 1u) {
114                let j = sorted[s];
115                let d = vec3<f32>(xs[j] - px, ys[j] - py, zs[j] - pz);
116                if (dot(d, d) <= params.radius_sq) {
117                    mean = mean + vec3<f32>(xs[j], ys[j], zs[j]);
118                    count = count + 1.0;
119                }
120            }
121        }
122    }
123
124    // Too few neighbors: emit an isotropic epsilon-scaled covariance.
125    if (count < 3.0) {
126        out_cov[i] = vec4<f32>(params.epsilon, params.epsilon, params.epsilon, 0.0);
127        // Recycled output storage is uninitialized; overwrite the second row.
128        out_cov[params.dims.w + i] = vec4<f32>(0.0);
129        return;
130    }
131    mean = mean / count;
132
133    var c00 = 0.0; var c11 = 0.0; var c22 = 0.0;
134    var c01 = 0.0; var c02 = 0.0; var c12 = 0.0;
135    for (var dz = -1; dz <= 1; dz = dz + 1) {
136        let nz = cz + dz;
137        if (nz < 0 || nz >= i32(dimz)) { continue; }
138        for (var dy = -1; dy <= 1; dy = dy + 1) {
139            let ny = cy + dy;
140            if (ny < 0 || ny >= i32(dimy)) { continue; }
141            let row = (u32(nz) * dimy + u32(ny)) * dimx;
142            let begin = cell_start[row + first_x];
143            let end = cell_start[row + after_x];
144            for (var s = begin; s < end; s = s + 1u) {
145                let j = sorted[s];
146                let p = vec3<f32>(xs[j], ys[j], zs[j]);
147                let rel = p - vec3<f32>(px, py, pz);
148                if (dot(rel, rel) <= params.radius_sq) {
149                    let dd = p - mean;
150                    c00 = c00 + dd.x * dd.x;
151                    c11 = c11 + dd.y * dd.y;
152                    c22 = c22 + dd.z * dd.z;
153                    c01 = c01 + dd.x * dd.y;
154                    c02 = c02 + dd.x * dd.z;
155                    c12 = c12 + dd.y * dd.z;
156                }
157            }
158        }
159    }
160
161    var a = array<vec3<f32>, 3>(
162        vec3<f32>(c00, c01, c02),
163        vec3<f32>(c01, c11, c12),
164        vec3<f32>(c02, c12, c22),
165    );
166    var v = array<vec3<f32>, 3>(
167        vec3<f32>(1.0, 0.0, 0.0),
168        vec3<f32>(0.0, 1.0, 0.0),
169        vec3<f32>(0.0, 0.0, 1.0),
170    );
171    for (var sweep: u32 = 0u; sweep < 16u; sweep = sweep + 1u) {
172        rotate(&a, &v, 0u, 1u);
173        rotate(&a, &v, 0u, 2u);
174        rotate(&a, &v, 1u, 2u);
175    }
176
177    // GICP plane regularization: rebuild covariance with eigenvalues (eps, 1, 1),
178    // smallest eigenvalue (surface normal) -> eps.
179    let eig = vec3<f32>(a[0][0], a[1][1], a[2][2]);
180    var min_idx = 0u;
181    if (eig[1] < eig[min_idx]) { min_idx = 1u; }
182    if (eig[2] < eig[min_idx]) { min_idx = 2u; }
183
184    var reg = array<f32, 6>(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
185    for (var col = 0u; col < 3u; col = col + 1u) {
186        var lambda = 1.0;
187        if (col == min_idx) {
188            lambda = params.epsilon;
189        }
190        let ax = v[0][col];
191        let ay = v[1][col];
192        let az = v[2][col];
193        reg[0] = reg[0] + lambda * ax * ax;
194        reg[1] = reg[1] + lambda * ay * ay;
195        reg[2] = reg[2] + lambda * az * az;
196        reg[3] = reg[3] + lambda * ax * ay;
197        reg[4] = reg[4] + lambda * ax * az;
198        reg[5] = reg[5] + lambda * ay * az;
199    }
200
201    out_cov[i] = vec4<f32>(reg[0], reg[1], reg[2], reg[3]);
202    out_cov[params.dims.w + i] = vec4<f32>(reg[4], reg[5], 0.0, 0.0);
203}
204"#;
205
206#[cfg(all(test, not(target_arch = "wasm32")))]
207#[path = "covariance_output_tests.rs"]
208mod output_tests;
209
210/// Estimates per-point plane-regularized covariances on the GPU via a uniform
211/// grid radius neighbor search.
212///
213/// Returns one [`GpuCovariance`] per point — the unique elements of a covariance
214/// matrix whose eigenvalues have been set to `(epsilon, 1, 1)` (the GICP
215/// plane-to-plane model). Grid construction (counting sort) runs on the CPU; the
216/// neighbor gather, covariance, and eigen-decomposition run on the GPU.
217/// Fewer than three radius neighbors produce the isotropic covariance
218/// `[epsilon, epsilon, epsilon, 0, 0, 0]`, including when output storage is reused.
219/// Nonempty inputs require finite coordinates and a positive radius with a
220/// finite reciprocal; positive infinity retains the unbounded one-cell grid.
221pub fn estimate_plane_covariances_grid_gpu(
222    runtime: &WgpuRuntime,
223    x: &[f32],
224    y: &[f32],
225    z: &[f32],
226    radius: f32,
227    epsilon: f32,
228) -> SpatialResult<Vec<GpuCovariance>> {
229    estimate_plane_covariances_grid_gpu_with_receipt(runtime, x, y, z, radius, epsilon)
230        .map(|(covariances, _)| covariances)
231}
232
233/// Explicit covariance upload/readback with payload transfer accounting.
234/// Includes XYZ, sorted indices and grid offsets uploaded, and the complete
235/// padded 32-byte-per-point output downloaded; uniform controls are excluded.
236/// Grid construction remains CPU, and errors propagate without fallback.
237pub fn estimate_plane_covariances_grid_gpu_with_receipt(
238    runtime: &WgpuRuntime,
239    x: &[f32],
240    y: &[f32],
241    z: &[f32],
242    radius: f32,
243    epsilon: f32,
244) -> SpatialResult<(Vec<GpuCovariance>, TransferStats)> {
245    let point_count = x.len();
246    if y.len() != point_count {
247        return Err(SpatialError::BufferLengthMismatch { expected: point_count, found: y.len() });
248    }
249    if z.len() != point_count {
250        return Err(SpatialError::BufferLengthMismatch { expected: point_count, found: z.len() });
251    }
252    if point_count == 0 {
253        return Ok((Vec::new(), TransferStats::default()));
254    }
255    if radius <= 0.0 || radius.is_nan() {
256        return Err(SpatialError::InvalidArgument("grid radius must be positive".to_owned()));
257    }
258    let (origin, dims, sorted, cell_start) =
259        point_estimators::prepare_grid(runtime, Kind::PlaneCovariances, x, y, z, radius)?;
260    let params = CovUniform {
261        origin: [origin[0], origin[1], origin[2], 0.0],
262        dims: [dims[0], dims[1], dims[2], point_count as u32],
263        inv_cell: 1.0 / radius,
264        radius_sq: radius * radius,
265        epsilon,
266        _pad: 0.0,
267    };
268    point_estimators::run_with_receipt(
269        runtime,
270        Kind::PlaneCovariances,
271        point_count,
272        bytemuck::bytes_of(&params),
273        &[
274            bytemuck::cast_slice(x),
275            bytemuck::cast_slice(y),
276            bytemuck::cast_slice(z),
277            bytemuck::cast_slice(&sorted),
278            bytemuck::cast_slice(&cell_start),
279        ],
280        |rows| {
281            (0..point_count)
282                .map(|i| {
283                    let a = rows[i];
284                    let b = rows[point_count + i];
285                    [a[0], a[1], a[2], a[3], b[0], b[1]]
286                })
287                .collect()
288        },
289    )
290}
291
292#[cfg(test)]
293mod tests {
294    use super::estimate_plane_covariances_grid_gpu;
295    use crate::runtime::WgpuRuntime;
296
297    #[test]
298    fn planar_patch_covariance_is_disk() {
299        let runtime = WgpuRuntime::new_headless().expect("wgpu runtime");
300        let mut x: Vec<f32> = Vec::new();
301        let mut y: Vec<f32> = Vec::new();
302        let mut z: Vec<f32> = Vec::new();
303        for i in 0..12 {
304            for j in 0..12 {
305                x.push(i as f32 * 0.1);
306                y.push(j as f32 * 0.1);
307                z.push(0.0);
308            }
309        }
310        let eps = 1e-3_f32;
311        let cov = estimate_plane_covariances_grid_gpu(&runtime, &x, &y, &z, 0.25, eps)
312            .expect("gpu covariances");
313        assert_eq!(cov.len(), x.len());
314        // For a z=0 plane, the regularized covariance ~ diag(1, 1, eps):
315        // in-plane variance ~1, out-of-plane (z) ~eps.
316        for c in &cov {
317            let [c00, c11, c22, _c01, _c02, _c12] = *c;
318            assert!((c22 - eps).abs() < 1e-2, "c22 not ~eps: {c22}");
319            assert!(c00 > 0.5 && c11 > 0.5, "in-plane variance too small: {c00},{c11}");
320        }
321    }
322}