brepkit_math/nurbs/intersection/
chaining.rs1use crate::MathError;
4use crate::nurbs::fitting::{approximate_lspia, chord_length_params, interpolate};
5use crate::nurbs::projection::project_point_to_curve;
6use crate::vec::Point3;
7
8use super::{IntersectionCurve, IntersectionPoint};
9
10pub(super) fn build_curves_from_points(
15 points: &[IntersectionPoint],
16) -> Result<Vec<IntersectionCurve>, MathError> {
17 if points.is_empty() {
18 return Ok(Vec::new());
19 }
20
21 let threshold = estimate_chain_threshold(points);
23
24 let chains = chain_intersection_points(points, threshold);
26
27 let mut curves = Vec::with_capacity(chains.len());
28
29 for chain in &chains {
30 let mut deduped: Vec<IntersectionPoint> = Vec::new();
32 for pt in chain {
33 let is_dup = deduped
34 .last()
35 .is_some_and(|last: &IntersectionPoint| (last.point - pt.point).length() < 1e-6);
36 if !is_dup {
37 deduped.push(*pt);
38 }
39 }
40
41 if deduped.len() < 2 {
42 continue;
43 }
44
45 let positions: Vec<Point3> = deduped.iter().map(|p| p.point).collect();
47 let degree = if positions.len() <= 3 {
48 1
49 } else {
50 3.min(positions.len() - 1)
51 };
52 let curve = if positions.len() > 50 {
53 let num_cps = (positions.len() / 3).max(degree + 1).min(positions.len());
54 let fitted = approximate_lspia(&positions, degree, num_cps, 1e-6, 100)?;
55
56 let fit_params = chord_length_params(&positions);
62 let mut max_residual = 0.0f64;
63 let mut bbox_min = positions[0];
64 let mut bbox_max = positions[0];
65 for (i, &t) in fit_params.iter().enumerate() {
66 let src = positions[i];
67 let d = if let Ok(proj) = project_point_to_curve(&fitted, src, 1e-6) {
70 proj.distance
71 } else {
72 let pt = fitted.evaluate(t);
73 (pt.x() - src.x()).hypot((pt.y() - src.y()).hypot(pt.z() - src.z()))
74 };
75 max_residual = max_residual.max(d);
76 bbox_min = Point3::new(
77 bbox_min.x().min(src.x()),
78 bbox_min.y().min(src.y()),
79 bbox_min.z().min(src.z()),
80 );
81 bbox_max = Point3::new(
82 bbox_max.x().max(src.x()),
83 bbox_max.y().max(src.y()),
84 bbox_max.z().max(src.z()),
85 );
86 }
87 let diagonal = (bbox_max.x() - bbox_min.x())
88 .hypot((bbox_max.y() - bbox_min.y()).hypot(bbox_max.z() - bbox_min.z()));
89 let rel_residual = if diagonal > 1e-12 {
90 max_residual / diagonal
91 } else {
92 max_residual
93 };
94 if rel_residual > 1e-2 {
95 log::warn!(
96 "SSI: LSPIA fit relative residual {rel_residual:.2e} (abs={max_residual:.2e}) \
97 exceeds 1% of curve extent — intersection curve may be inaccurate \
98 (degree={degree}, num_cps={num_cps}, samples={})",
99 positions.len()
100 );
101 }
102 fitted
103 } else {
104 interpolate(&positions, degree)?
105 };
106
107 curves.push(IntersectionCurve {
108 curve,
109 points: deduped,
110 });
111 }
112
113 Ok(curves)
114}
115
116#[allow(clippy::cast_precision_loss)]
118#[must_use]
119pub(super) fn estimate_chain_threshold(points: &[IntersectionPoint]) -> f64 {
120 if points.len() < 2 {
121 return 1.0;
122 }
123
124 let sample_size = points.len().min(100);
126 let mut total_min_dist = 0.0_f64;
127 let mut count = 0_usize;
128 for i in 0..sample_size {
129 let mut min_d = f64::MAX;
130 for (j, q) in points.iter().enumerate() {
131 if i == j {
132 continue;
133 }
134 let d = (points[i].point - q.point).length();
135 if d < min_d {
136 min_d = d;
137 }
138 }
139 if min_d < f64::MAX {
140 total_min_dist += min_d;
141 count += 1;
142 }
143 }
144
145 if count == 0 {
146 return 1.0;
147 }
148
149 let avg = total_min_dist / count as f64;
154
155 let mut bb_min = [f64::MAX; 3];
157 let mut bb_max = [f64::MIN; 3];
158 for p in points {
159 bb_min[0] = bb_min[0].min(p.point.x());
160 bb_min[1] = bb_min[1].min(p.point.y());
161 bb_min[2] = bb_min[2].min(p.point.z());
162 bb_max[0] = bb_max[0].max(p.point.x());
163 bb_max[1] = bb_max[1].max(p.point.y());
164 bb_max[2] = bb_max[2].max(p.point.z());
165 }
166 let diag = ((bb_max[0] - bb_min[0]).powi(2)
167 + (bb_max[1] - bb_min[1]).powi(2)
168 + (bb_max[2] - bb_min[2]).powi(2))
169 .sqrt();
170
171 let floor = diag * 0.05;
174 (avg * 3.0).max(floor).max(1e-4)
175}
176
177#[must_use]
184pub fn chain_intersection_points(
185 points: &[IntersectionPoint],
186 threshold: f64,
187) -> Vec<Vec<IntersectionPoint>> {
188 if points.is_empty() {
189 return Vec::new();
190 }
191
192 let n = points.len();
193 let threshold_sq = threshold * threshold;
194
195 let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
197 for i in 0..n {
198 for j in (i + 1)..n {
199 let d = points[i].point - points[j].point;
200 if d.x().mul_add(d.x(), d.y().mul_add(d.y(), d.z() * d.z())) < threshold_sq {
201 adj[i].push(j);
202 adj[j].push(i);
203 }
204 }
205 }
206
207 let mut visited = vec![false; n];
209 let mut components: Vec<Vec<usize>> = Vec::new();
210
211 for start in 0..n {
212 if visited[start] {
213 continue;
214 }
215 let mut component = Vec::new();
216 let mut queue = std::collections::VecDeque::new();
217 queue.push_back(start);
218 visited[start] = true;
219 while let Some(idx) = queue.pop_front() {
220 component.push(idx);
221 for &neighbor in &adj[idx] {
222 if !visited[neighbor] {
223 visited[neighbor] = true;
224 queue.push_back(neighbor);
225 }
226 }
227 }
228 components.push(component);
229 }
230
231 let mut chains = Vec::with_capacity(components.len());
233 for comp in &components {
234 if comp.is_empty() {
235 continue;
236 }
237
238 let start_idx = comp
240 .iter()
241 .copied()
242 .min_by_key(|&i| adj[i].iter().filter(|&&j| comp.contains(&j)).count())
243 .unwrap_or(comp[0]);
244
245 let mut chain = Vec::with_capacity(comp.len());
246 let mut used = vec![false; n];
247 let mut current = start_idx;
248 used[current] = true;
249 chain.push(points[current]);
250
251 for _ in 1..comp.len() {
252 let mut best_dist = f64::MAX;
254 let mut best_idx = None;
255 for &idx in comp {
256 if used[idx] {
257 continue;
258 }
259 let d = points[current].point - points[idx].point;
260 let dist_sq = d.x().mul_add(d.x(), d.y().mul_add(d.y(), d.z() * d.z()));
261 if dist_sq < best_dist {
262 best_dist = dist_sq;
263 best_idx = Some(idx);
264 }
265 }
266
267 if let Some(next) = best_idx {
268 used[next] = true;
269 chain.push(points[next]);
270 current = next;
271 } else {
272 break;
273 }
274 }
275
276 chains.push(chain);
277 }
278
279 chains
280}