1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
use crate::hgrid::HGrid;
use crate::marching_cubes::{march_cube_idx, MeshBuffers};
use crate::poisson_layer::PoissonLayer;
use crate::poisson_vector_field::PoissonVectorField;
use crate::polynomial::{eval_bspline, eval_bspline_diff};
use crate::Real;
use na::{vector, Point3, Vector3};
use parry::bounding_volume::{Aabb, BoundingVolume};
use parry::partitioning::IndexedData;
use parry::shape::{TriMesh, TriMeshFlags};
use std::collections::HashMap;
use std::ops::{AddAssign, Mul};
/// An implicit surface reconstructed with the Screened Poisson reconstruction algorithm.
#[derive(Clone)]
pub struct PoissonReconstruction {
layers: Vec<PoissonLayer>,
isovalue: Real,
}
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct CellWithId {
pub cell: Point3<i64>,
pub id: usize,
}
impl IndexedData for CellWithId {
fn default() -> Self {
Self {
cell: Point3::default(),
id: 0,
}
}
fn index(&self) -> usize {
self.id
}
}
impl PoissonReconstruction {
/// Reconstruct a surface using the Screened Poisson reconstruction algorithm,
/// given a set of sample points and normals at these points.
///
/// # Parameters
/// - `points`: the sample points.
/// - `normals`: the normals at the sample points. Must have the same length as `points`.
/// - `screening`: the screening coefficient. Larger values increase the fitting of the
/// reconstructed surface relative to the sample point’s positions. Setting this to `0.0`
/// disables screening (but reduces computation times).
/// - `density_estimation_depth`: the depth on the multigrid solver where point density estimation
/// is calculated. The estimation kernel radius will be equal to the maximum extent of the
/// input point’s AABB, divided by `2.pow(max_depth)`. Smaller value of this parameter results
/// in more robustness wrt. occasional holes and sampling irregularities, but reduces the
/// detail accuracies.
/// - `max_depth`: the max depth of the multigrid solver. Larger values result in higher accuracy
/// (which requires higher sampling densities, or a `density_estimation_depth` set to a smaller
/// value). Higher values increases computation times.
/// - `max_relaxation_iters`: the maximum number of iterations for the internal
/// conjugate-gradient solver. Values around `10` should be enough for most cases.
pub fn from_points_and_normals(
points: &[Point3<Real>],
normals: &[Vector3<Real>],
screening: Real,
density_estimation_depth: usize,
max_depth: usize,
max_relaxation_iters: usize,
) -> Self {
assert_eq!(
points.len(),
normals.len(),
"Exactly one normal per point must be provided."
);
assert!(density_estimation_depth <= max_depth);
let mut root_aabb = Aabb::from_points(points);
let max_extent = root_aabb.extents().max();
let leaf_cell_width = max_extent / (2.0 as Real).powi(max_depth as i32);
root_aabb.loosen(leaf_cell_width);
let grid_origin = root_aabb.mins;
let mut layers = vec![];
layers.push(PoissonLayer::from_points(
points,
grid_origin,
leaf_cell_width,
));
for i in 0..max_depth {
let layer = PoissonLayer::from_next_layer(points, &layers[i]);
layers.push(layer);
}
// Reverse so the coarser layers go first.
layers.reverse();
let vector_field =
PoissonVectorField::new(&layers, points, normals, density_estimation_depth);
for i in 0..layers.len() {
let result = PoissonLayer::solve(
&layers,
i,
&vector_field,
points,
normals,
screening,
max_relaxation_iters,
);
layers[i].node_weights = result;
}
let mut total_weight = 0.0;
let mut result = Self {
layers,
isovalue: 0.0,
};
let mut isovalue = 0.0;
for (pt, w) in points.iter().zip(vector_field.densities.iter()) {
isovalue += result.eval(pt) / *w;
total_weight += 1.0 / *w;
}
result.isovalue = isovalue / total_weight;
result
}
/// The domain where the surface’s implicit function is defined.
pub fn aabb(&self) -> &Aabb {
self.layers.last().unwrap().cells_qbvh.root_aabb()
}
/// Does the given AABB intersect any of the smallest grid cells of the reconstruction?
pub fn leaf_cells_intersect_aabb(&self, aabb: &Aabb) -> bool {
let mut intersections = vec![];
self.layers
.last()
.unwrap()
.cells_qbvh
.intersect_aabb(aabb, &mut intersections);
!intersections.is_empty()
}
/// Evaluates the value of the implicit function at the given 3D point.
///
/// In order to get a meaningful value, the point must be located inside of [`Self::aabb`].
pub fn eval(&self, pt: &Point3<Real>) -> Real {
let mut result = 0.0;
for layer in &self.layers {
result += layer.eval_triquadratic(pt);
}
result - self.isovalue
}
/// Evaluates the value of the implicit function’s gradient at the given 3D point.
///
/// In order to get a meaningful value, the point must be located inside of [`Self::aabb`].
pub fn eval_gradient(&self, pt: &Point3<Real>) -> Vector3<Real> {
let mut result = Vector3::zeros();
for layer in &self.layers {
result += layer.eval_triquadratic_gradient(pt);
}
result
}
/// Reconstructs a mesh from this implicit function using a simple marching-cubes, extracting
/// the isosurface at 0.
#[deprecated = "use `reconstruct_mesh_buffers` or `reconstruct_trimesh` instead"]
pub fn reconstruct_mesh(&self) -> Vec<Point3<Real>> {
self.reconstruct_mesh_buffers().result_as_triangle_soup()
}
/// Reconstructs a `TriMesh` from this implicit function using a simple marching-cubes, extracting
/// the isosurface at 0.
pub fn reconstruct_trimesh(&self, flags: TriMeshFlags) -> Option<TriMesh> {
self.reconstruct_mesh_buffers().result(flags)
}
/// Reconstructs a mesh from this implicit function using a simple marching-cubes, extracting
/// the isosurface at 0.
pub fn reconstruct_mesh_buffers(&self) -> MeshBuffers {
let mut result = MeshBuffers::default();
let mut visited = HashMap::new();
if let Some(last_layer) = self.layers.last() {
// Check all the existing leaves.
let mut eval_cell = |key: Point3<i64>, visited: &mut HashMap<Point3<i64>, bool>| {
let cell_center = last_layer.grid.cell_center(&key);
let cell_width = Vector3::repeat(last_layer.grid.cell_width() / 2.0);
let aabb = Aabb::from_half_extents(cell_center, cell_width);
let mut vertex_values = [0.0; 8];
for (pt, val) in aabb.vertices().iter().zip(vertex_values.iter_mut()) {
*val = self.eval(pt);
}
let len_before = result.indices().len();
march_cube_idx(
&aabb,
&vertex_values,
key.cast::<i32>().into(),
0.0,
&mut result,
);
let has_sign_change = result.indices().len() != len_before;
visited.insert(key, has_sign_change);
has_sign_change
};
for cell in last_layer.cells_qbvh.raw_proxies() {
// let aabb = last_layer.cells_qbvh.node_aabb(cell.node).unwrap();
eval_cell(cell.data.cell, &mut visited);
}
// Checking only the leaves isn’t enough, isosurfaces might escape leaves through levels
// at a coarser level. So we also check adjacent leaves that experienced a sign change.
// PERF: instead of traversing ALL the adjacent leaves, only traverse the ones adjacent
// to an edge that actually experienced a sign change.
// PERF: don’t re-evaluate vertices that were already evaluated.
let mut stack: Vec<_> = visited
.iter()
.filter(|(_key, sign_change)| **sign_change)
.map(|e| *e.0)
.collect();
while let Some(cell) = stack.pop() {
for i in -1..=1 {
for j in -1..=1 {
for k in -1..=1 {
let new_cell = cell + Vector3::new(i, j, k);
if !visited.contains_key(&new_cell) {
let has_sign_change = eval_cell(new_cell, &mut visited);
if has_sign_change {
stack.push(new_cell);
}
}
}
}
}
}
}
result
}
}
pub fn eval_triquadratic<T: Mul<Real, Output = T> + AddAssign + Copy + Default>(
pt: &Point3<Real>,
grid: &HGrid<usize>,
grid_node_idx: &HashMap<Point3<i64>, usize>,
node_weights: &[T],
) -> T {
let cell_width = grid.cell_width();
let ref_cell = grid.key(pt);
let mut result = T::default();
for i in -1..=1 {
for j in -1..=1 {
for k in -1..=1 {
let curr_cell = ref_cell + vector![i, j, k];
if let Some(node_id) = grid_node_idx.get(&curr_cell) {
let spline_origin = grid.cell_center(&curr_cell);
let valx = eval_bspline(pt.x, spline_origin.x, cell_width);
let valy = eval_bspline(pt.y, spline_origin.y, cell_width);
let valz = eval_bspline(pt.z, spline_origin.z, cell_width);
result += node_weights[*node_id] * valx * valy * valz;
}
}
}
}
result
}
pub fn eval_triquadratic_gradient(
pt: &Point3<Real>,
grid: &HGrid<usize>,
grid_node_idx: &HashMap<Point3<i64>, usize>,
node_weights: &[Real],
) -> Vector3<Real> {
let cell_width = grid.cell_width();
let ref_cell = grid.key(pt);
let mut result = Vector3::default();
for i in -1..=1 {
for j in -1..=1 {
for k in -1..=1 {
let curr_cell = ref_cell + vector![i, j, k];
if let Some(node_id) = grid_node_idx.get(&curr_cell) {
let spline_origin = grid.cell_center(&curr_cell);
let valx = eval_bspline(pt.x, spline_origin.x, cell_width);
let valy = eval_bspline(pt.y, spline_origin.y, cell_width);
let valz = eval_bspline(pt.z, spline_origin.z, cell_width);
let diffx = eval_bspline_diff(pt.x, spline_origin.x, cell_width);
let diffy = eval_bspline_diff(pt.y, spline_origin.y, cell_width);
let diffz = eval_bspline_diff(pt.z, spline_origin.z, cell_width);
result += Vector3::new(
diffx * valy * valz,
valx * diffy * valz,
valx * valy * diffz,
) * node_weights[*node_id];
}
}
}
}
result
}