1use super::{invalid, plan as equation_plan, GpuGicpInput};
3use crate::{
4 kernels::point_estimators::{prepare_grid, Kind},
5 scratch::ScratchBuffers,
6 GpuIcpInput, WgpuRuntime,
7};
8use bytemuck::{Pod, Zeroable};
9use spatialrust_core::{SpatialError, SpatialResult, TransferDirection};
10use spatialrust_search::KdTree;
11use wgpu::util::DeviceExt;
12
13#[repr(C)]
14#[derive(Clone, Copy, Pod, Zeroable)]
15struct Params {
16 origin: [f32; 4],
17 dims: [u32; 4],
18 inv_cell: f32,
19 radius_sq: f32,
20 epsilon: f32,
21 capacity: u32,
22 offset: u32,
23 total: u32,
24 padding: [u32; 2],
25}
26
27fn grid_plan(
28 source: u64,
29 target: u64,
30 radius: f32,
31 capacity: u32,
32 epsilon: f32,
33 limits: &wgpu::Limits,
34) -> SpatialResult<u64> {
35 let total = source.checked_add(target).ok_or_else(invalid)?;
36 if source == 0
37 || target == 0
38 || source > 1 << 24
39 || target > 1 << 24
40 || capacity == 0
41 || !radius.is_finite()
42 || radius <= 0.0
43 || !(radius * radius).is_normal()
44 || !(1e-4..=1.0).contains(&epsilon)
45 || limits.max_compute_workgroup_size_x < 256
46 || limits.max_compute_invocations_per_workgroup < 256
47 || total.div_ceil(256) > u64::from(limits.max_compute_workgroups_per_dimension)
48 || total
49 .checked_add(1)
50 .and_then(|n| n.checked_mul(8))
51 .map_or(true, |n| n > u64::from(u32::MAX))
52 {
53 return Err(invalid());
54 }
55 equation_plan(source, total + 1, limits)?;
56 Ok((total + 1) * 32)
57}
58
59impl GpuGicpInput {
60 pub fn upload_with_gpu_grid_covariances(
75 runtime: &WgpuRuntime,
76 source: (&[f32], &[f32], &[f32]),
77 target: &KdTree,
78 radius: f32,
79 capacity: u32,
80 epsilon: f32,
81 ) -> SpatialResult<Self> {
82 let (x, y, z) = source;
83 for axis in [y, z] {
84 if axis.len() != x.len() {
85 return Err(SpatialError::BufferLengthMismatch {
86 expected: x.len(),
87 found: axis.len(),
88 });
89 }
90 }
91 let target_axes = target.layout().positions();
92 let targets = target_axes.0.len();
93 let bytes = grid_plan(
94 x.len() as u64,
95 targets as u64,
96 radius,
97 capacity,
98 epsilon,
99 &runtime.device().limits(),
100 )?;
101 let grids = [
102 prepare_grid(runtime, Kind::PlaneCovariances, x, y, z, radius)?,
103 prepare_grid(
104 runtime,
105 Kind::PlaneCovariances,
106 target_axes.0,
107 target_axes.1,
108 target_axes.2,
109 radius,
110 )?,
111 ];
112 let points: Vec<_> = (0..x.len()).map(|i| [x[i], y[i], z[i]]).collect();
113 let positions = GpuIcpInput::upload(runtime, &points, target)?;
114 let covariances = runtime.device().create_buffer(&wgpu::BufferDescriptor {
115 label: Some("gicp-grid-covariances"),
116 size: bytes,
117 usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
118 mapped_at_creation: false,
119 });
120 let total = (x.len() + targets) as u32;
121 let counts = [x.len() as u32, targets as u32];
122 let offsets = [0, x.len() as u32];
123 let cache = runtime
124 .gicp_grid_covariance_pipelines
125 .get_or_init(|| GridPipelines::new(runtime.device()));
126 let mut scratch = ScratchBuffers::new(runtime);
127 let mut transfers = positions.upload_transfers();
128 let groups: Vec<_> = grids
129 .iter()
130 .enumerate()
131 .map(|(i, (origin, dims, sorted, starts))| {
132 let params = Params {
133 origin: [origin[0], origin[1], origin[2], 0.0],
134 dims: [dims[0], dims[1], dims[2], counts[i]],
135 inv_cell: 1.0 / radius,
136 radius_sq: radius * radius,
137 epsilon,
138 capacity,
139 offset: offsets[i],
140 total,
141 padding: [0; 2],
142 };
143 let uniform =
144 runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
145 label: Some("gicp-grid-params"),
146 contents: bytemuck::bytes_of(¶ms),
147 usage: wgpu::BufferUsages::UNIFORM,
148 });
149 let aux = [sorted, starts].map(|words| {
150 let data = bytemuck::cast_slice(words);
151 let buffer = scratch.acquire("gicp-grid-index", data.len() as u64);
152 runtime.queue().write_buffer(&buffer, 0, data);
153 transfers.record(TransferDirection::HostToDevice, data.len() as u64);
154 buffer
155 });
156 let queries = if i == 0 { &positions.source } else { &positions.target };
157 let buffers = [&uniform, queries.buffer().unwrap(), &aux[0], &aux[1], &covariances];
158 let entries: Vec<_> = buffers
159 .iter()
160 .enumerate()
161 .map(|(binding, buffer)| wgpu::BindGroupEntry {
162 binding: binding as u32,
163 resource: buffer.as_entire_binding(),
164 })
165 .collect();
166 runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
167 label: Some("gicp-grid-bindings"),
168 layout: &cache.layout,
169 entries: &entries,
170 })
171 })
172 .collect();
173 let mut encoder = runtime.device().create_command_encoder(&Default::default());
174 {
175 let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
176 label: Some("gicp-grid-build"),
177 timestamp_writes: None,
178 });
179 pass.set_pipeline(&cache.build);
180 for (i, group) in groups.iter().enumerate() {
181 pass.set_bind_group(0, group, &[]);
182 pass.dispatch_workgroups(counts[i].div_ceil(256), 1, 1);
183 }
184 }
185 {
186 let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
187 label: Some("gicp-grid-finalize"),
188 timestamp_writes: None,
189 });
190 pass.set_pipeline(&cache.finalize);
191 pass.set_bind_group(0, &groups[0], &[]);
192 pass.dispatch_workgroups(total.div_ceil(256), 1, 1);
193 }
194 scratch.submit_and_recycle(encoder);
195 Ok(Self {
196 positions,
197 covariances,
198 weight_scale: 6.0 / epsilon,
199 covariance_offset: 1,
200 transfers,
201 })
202 }
203}
204
205fn shader_source() -> String {
209 let old = crate::kernels::covariances_grid::COV_GRID_WGSL;
210 let mut body = old[old.find("fn rotate(").expect("canonical grid rotate")..].to_owned();
211 for (axis, component) in [("xs", "x"), ("ys", "y"), ("zs", "z")] {
212 for index in ["i", "j"] {
213 let from = format!("{axis}[{index}]");
214 assert!(body.contains(&from));
215 body = body.replace(&from, &format!("points[{index}].{component}"));
216 }
217 }
218 let edits=[
219 ("count = count + 1.0;", "count = count + 1.0;\n if u32(count) > params.capacity { atomicOr(&result.status,8u); return; }"),
220 ("out_cov[i] = vec4<f32>(params.epsilon, params.epsilon, params.epsilon, 0.0);", "store_covariance(i,vec4<f32>(params.epsilon,params.epsilon,params.epsilon,0.0),vec4<f32>(0.0));"),
221 ("out_cov[params.dims.w + i] = vec4<f32>(0.0);", ""),
222 ("out_cov[i] = vec4<f32>(reg[0], reg[1], reg[2], reg[3]);", "store_covariance(i,vec4<f32>(reg[0],reg[1],reg[2],reg[3]),vec4<f32>(reg[4],reg[5],0.0,0.0));"),
223 ("out_cov[params.dims.w + i] = vec4<f32>(reg[4], reg[5], 0.0, 0.0);", ""),
224 ];
225 for (from, to) in edits {
226 assert_eq!(body.matches(from).count(), 1);
227 body = body.replace(from, to);
228 }
229 for from in ["let end = cell_start[row + after_x];", "let j = sorted[s];"] {
230 assert_eq!(body.matches(from).count(), 2);
231 let check = if from.starts_with("let end") {
232 "if begin>end || end>params.dims.w {atomicOr(&result.status,1u);return;}"
233 } else {
234 "if j>=params.dims.w {atomicOr(&result.status,1u);return;}"
235 };
236 body = body.replace(from, &format!("{from}\n {check}"));
237 }
238 body =
240 body.replace("// Recycled output storage is uninitialized; overwrite the second row.", "");
241 format!("{}\n{body}", include_str!("../shaders/gicp_grid_covariances.wgsl"))
242}
243
244pub(crate) struct GridPipelines {
245 layout: wgpu::BindGroupLayout,
246 build: wgpu::ComputePipeline,
247 finalize: wgpu::ComputePipeline,
248}
249impl GridPipelines {
250 fn new(device: &wgpu::Device) -> Self {
251 let entries: Vec<_> = (0..5)
252 .map(|binding| wgpu::BindGroupLayoutEntry {
253 binding,
254 visibility: wgpu::ShaderStages::COMPUTE,
255 ty: wgpu::BindingType::Buffer {
256 ty: if binding == 0 {
257 wgpu::BufferBindingType::Uniform
258 } else {
259 wgpu::BufferBindingType::Storage { read_only: binding != 4 }
260 },
261 has_dynamic_offset: false,
262 min_binding_size: None,
263 },
264 count: None,
265 })
266 .collect();
267 let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
268 label: Some("gicp-grid-layout"),
269 entries: &entries,
270 });
271 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
272 label: Some("gicp-grid-pipeline-layout"),
273 bind_group_layouts: &[&layout],
274 push_constant_ranges: &[],
275 });
276 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
277 label: Some("gicp-grid-shader"),
278 source: wgpu::ShaderSource::Wgsl(shader_source().into()),
279 });
280 let pipeline = |entry| {
281 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
282 label: Some("gicp-grid-pipeline"),
283 layout: Some(&pipeline_layout),
284 module: &shader,
285 entry_point: Some(entry),
286 compilation_options: Default::default(),
287 cache: None,
288 })
289 };
290 Self { build: pipeline("main"), finalize: pipeline("finalize"), layout }
291 }
292}
293
294#[cfg(all(test, not(target_arch = "wasm32")))]
295#[path = "gicp_grid_covariance_tests.rs"]
296mod tests;