1use super::*;
2
3fn face_normal(face: &FaceRecord, u: f64, v: f64) -> Result<Vec3, String> {
4 let normal = match face.surface.normal(u, v) {
5 Ok(normal) => normal,
6 Err(error) => {
7 if !error.contains("zero-length")
17 || std::env::var("BREP_POLE_NORMAL_RESCUE").as_deref() == Ok("0")
18 {
19 return Err(error);
20 }
21 let [u0, u1] = face.surface.domain_u()?;
22 let [v0, v1] = face.surface.domain_v()?;
23 let step_u = (u1 - u0) * 1e-4;
24 let step_v = (v1 - v0) * 1e-4;
25 let inner_u = u.clamp(u0 + step_u, u1 - step_u);
26 let inner_v = v.clamp(v0 + step_v, v1 - step_v);
27 let mut recovered = None;
28 for (cu, cv) in [(u, inner_v), (inner_u, v), (inner_u, inner_v)] {
29 if let Ok(normal) = face.surface.normal(cu, cv) {
30 recovered = Some(normal);
31 break;
32 }
33 }
34 match recovered {
35 Some(normal) => normal,
36 None => return Err(error),
37 }
38 }
39 };
40 Ok(if face.same_sense {
41 normal
42 } else {
43 normal.scale(-1.0)
44 })
45}
46
47fn face_uv_tolerance(face: &FaceRecord, u: f64, v: f64, spatial: f64) -> f64 {
53 surface_uv_band(&face.surface, u, v, spatial)
54}
55
56pub fn surface_uv_band(surface: &crate::NurbsSurface, u: f64, v: f64, spatial: f64) -> f64 {
58 let Ok(derivatives) = surface.derivatives(u, v, 1) else {
59 return spatial;
60 };
61 let band = crate::tolerance::surface_uv_tolerance(
62 spatial,
63 derivatives[1][0].length(),
64 derivatives[0][1].length(),
65 );
66 let cap = match (surface.domain_u(), surface.domain_v()) {
67 (Ok([u0, u1]), Ok([v0, v1])) => ((u1 - u0).min(v1 - v0) * 0.05).max(1e-12),
68 _ => f64::INFINITY,
69 };
70 band.min(cap)
71}
72
73#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
74#[serde(rename_all = "lowercase")]
75pub enum PointClass {
76 In,
77 Out,
78 On,
79}
80
81#[derive(Clone, Copy, Debug, Serialize)]
82pub struct PointClassification {
83 pub class: PointClass,
84 #[serde(skip_serializing_if = "Option::is_none")]
85 pub on_normal: Option<Vec3>,
86}
87
88#[derive(Default, Clone, Copy)]
95pub struct ClassifyProfile {
96 pub enabled: bool,
97 pub classify_calls: u64,
98 pub band_candidates: u64,
99 pub band_project_ms: f64,
100 pub band_trim_tests: u64,
101 pub band_trim_ms: f64,
102 pub rays: u64,
103 pub ray_faces: u64,
104 pub ray_csi_ms: f64,
105 pub ray_exact_faces: u64,
108 pub ray_fallback_faces: u64,
109 pub ray_trim_tests: u64,
110 pub ray_trim_ms: f64,
111 pub coincident_calls: u64,
112 pub coincident_ms: f64,
113 pub classifier_builds: u64,
114 pub classifier_build_ms: f64,
115}
116
117thread_local! {
118 static CLASSIFY_PROFILE: std::cell::Cell<ClassifyProfile> =
119 const { std::cell::Cell::new(ClassifyProfile {
120 enabled: false, classify_calls: 0, band_candidates: 0, band_project_ms: 0.0,
121 band_trim_tests: 0, band_trim_ms: 0.0, rays: 0, ray_faces: 0, ray_csi_ms: 0.0,
122 ray_exact_faces: 0, ray_fallback_faces: 0, ray_trim_tests: 0, ray_trim_ms: 0.0, coincident_calls: 0, coincident_ms: 0.0,
123 classifier_builds: 0, classifier_build_ms: 0.0,
124 }) };
125}
126
127impl crate::profile::Counters for ClassifyProfile {
128 fn armed(&self) -> bool {
129 self.enabled
130 }
131}
132
133fn classify_profile(update: impl FnOnce(&mut ClassifyProfile)) {
134 crate::profile::update(&CLASSIFY_PROFILE, update)
135}
136
137fn classify_profile_started() -> Option<web_time::Instant> {
138 crate::profile::started(&CLASSIFY_PROFILE)
139}
140
141use crate::profile::elapsed_ms as classify_elapsed_ms;
142
143pub fn classify_profile_begin() {
145 let enabled = crate::profile::profile_enabled();
146 CLASSIFY_PROFILE.with(|cell| {
147 cell.set(ClassifyProfile {
148 enabled,
149 ..ClassifyProfile::default()
150 })
151 });
152}
153
154pub fn classify_profile_report(label: &str) {
157 let p = CLASSIFY_PROFILE.with(|cell| cell.get());
158 if !p.enabled {
159 return;
160 }
161 profile_line!(
162 "classify.profile {label} calls={} builds={} build_ms={:.2} band: candidates={} project_ms={:.2} trim_tests={} trim_ms={:.2} rays={} ray_faces={} csi_ms={:.2} exact_faces={} fallback_faces={} ray_trim_tests={} ray_trim_ms={:.2} coincident: calls={} ms={:.2}",
163 p.classify_calls, p.classifier_builds, p.classifier_build_ms, p.band_candidates,
164 p.band_project_ms, p.band_trim_tests, p.band_trim_ms, p.rays, p.ray_faces,
165 p.ray_csi_ms, p.ray_exact_faces, p.ray_fallback_faces, p.ray_trim_tests, p.ray_trim_ms, p.coincident_calls, p.coincident_ms,
166 );
167 CLASSIFY_PROFILE.with(|cell| cell.set(ClassifyProfile::default()));
168}
169
170fn exact_ray_enabled() -> bool {
177 switch!("BREP_CLASSIFY_EXACT_RAY", true)
178}
179
180fn ray_face_intersections(
184 sub_ray: &NurbsCurve,
185 surface: &crate::NurbsSurface,
186 tolerance: f64,
187) -> Result<Vec<crate::CurveSurfaceIntersection>, String> {
188 if exact_ray_enabled() {
189 if let Some(seeds) = crate::exact_line_surface::exact_line_surface_seeds(sub_ray, surface, tolerance) {
190 classify_profile(|p| p.ray_exact_faces += 1);
191 return crate::curve_surface_intersection::intersect_curve_surface_from_seeds(sub_ray, surface, tolerance, seeds);
192 }
193 classify_profile(|p| p.ray_fallback_faces += 1);
194 }
195 intersect_curve_surface(sub_ray, surface, tolerance)
196}
197
198pub struct SolidClassifier<'a> {
203 faces: Vec<&'a FaceRecord>,
204 face_boxes: Vec<Aabb>,
205 bounds: Aabb,
206 bvh: Bvh,
207 tolerance: f64,
208 coincident_caps: Vec<(Aabb, f64)>,
212}
213
214fn clip_segment_to_aabb(
218 start: Vec3,
219 direction: Vec3,
220 length: f64,
221 bounds: &Aabb,
222) -> Option<[f64; 2]> {
223 let mut s0 = 0.0f64;
224 let mut s1 = length;
225 for axis in 0..3 {
226 let (origin, delta, minimum, maximum) = match axis {
227 0 => (start.x, direction.x, bounds.minimum.x, bounds.maximum.x),
228 1 => (start.y, direction.y, bounds.minimum.y, bounds.maximum.y),
229 _ => (start.z, direction.z, bounds.minimum.z, bounds.maximum.z),
230 };
231 if delta.abs() <= 1e-15 {
232 if origin < minimum || origin > maximum {
233 return None;
234 }
235 continue;
236 }
237 let mut near = (minimum - origin) / delta;
238 let mut far = (maximum - origin) / delta;
239 if near > far {
240 std::mem::swap(&mut near, &mut far);
241 }
242 s0 = s0.max(near);
243 s1 = s1.min(far);
244 if s0 > s1 {
245 return None;
246 }
247 }
248 Some([s0, s1])
249}
250
251impl<'a> SolidClassifier<'a> {
252 pub fn new(solid: &'a BrepSolid, tolerance: f64) -> Result<Self, String> {
253 let build_started = classify_profile_started();
254 let faces: Vec<&FaceRecord> = solid.shells.iter().flat_map(|shell| &shell.faces).collect();
255 let face_boxes = faces
256 .iter()
257 .map(|face| Aabb::from_surface_controls(&face.surface))
258 .collect::<Result<Vec<_>, _>>()?;
259 let mut bounds = Aabb::empty();
260 for face_box in &face_boxes {
261 bounds.include(*face_box);
262 }
263 let bvh = Bvh::build(&face_boxes);
264 classify_profile(|p| {
265 p.classifier_builds += 1;
266 p.classifier_build_ms += classify_elapsed_ms(build_started);
267 });
268 Ok(Self {
269 faces,
270 face_boxes,
271 bounds,
272 bvh,
273 tolerance,
274 coincident_caps: Vec::new(),
275 })
276 }
277
278 pub fn near_surface(&self, point: Vec3) -> Result<bool, String> {
284 let on_tolerance = self.tolerance * 10.0;
285 if !self.bounds.expanded(on_tolerance).contains(point) {
286 return Ok(false);
287 }
288 let mut candidates = Vec::new();
289 self.bvh
290 .containing_point(point, on_tolerance, &mut candidates);
291 for &index in &candidates {
292 let projection = project_point_to_surface(&self.faces[index].surface, point)?;
293 if projection.distance <= on_tolerance {
294 return Ok(true);
295 }
296 }
297 Ok(false)
298 }
299
300 pub fn within_band(&self, point: Vec3, band: f64) -> Result<bool, String> {
309 if !self.bounds.expanded(band).contains(point) {
310 return Ok(false);
311 }
312 let mut candidates = Vec::new();
313 self.bvh.containing_point(point, band, &mut candidates);
314 for &index in &candidates {
315 let projection = project_point_to_surface(&self.faces[index].surface, point)?;
316 if projection.distance <= band {
317 return Ok(true);
318 }
319 }
320 Ok(false)
321 }
322
323 pub fn classify(&self, point: Vec3) -> Result<PointClassification, String> {
324 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::CLASSIFY);
325 classify_profile(|p| p.classify_calls += 1);
326 let tolerance = self.tolerance;
327 if !self.bounds.expanded(tolerance).contains(point) {
328 return Ok(PointClassification {
329 class: PointClass::Out,
330 on_normal: None,
331 });
332 }
333 let on_tolerance = self.capped_band(point, tolerance * 10.0);
337 if !self.coincident_caps.is_empty() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
338 eprintln!("feature_scale: classify at {point:?} on band {on_tolerance:.3e} (uncapped {:.3e}, {} caps)", tolerance * 10.0, self.coincident_caps.len());
339 }
340 let mut candidates = Vec::new();
341 self.bvh
342 .containing_point(point, on_tolerance, &mut candidates);
343 candidates.sort_unstable();
344 let mut interior_normals: Vec<Vec3> = Vec::new();
351 let mut boundary_normals: Vec<Vec3> = Vec::new();
352 for &index in &candidates {
353 let face = self.faces[index];
354 let project_started = classify_profile_started();
355 let projection = project_point_to_surface(&face.surface, point)?;
356 classify_profile(|p| {
357 p.band_candidates += 1;
358 p.band_project_ms += classify_elapsed_ms(project_started);
359 });
360 if projection.distance > on_tolerance {
361 continue;
362 }
363 let uv_tolerance = face_uv_tolerance(face, projection.u, projection.v, on_tolerance);
364 let trim_started = classify_profile_started();
365 let trim = parameter_point_in_face(
366 face,
367 Vec2 {
368 x: projection.u,
369 y: projection.v,
370 },
371 uv_tolerance,
372 )?;
373 classify_profile(|p| {
374 p.band_trim_tests += 1;
375 p.band_trim_ms += classify_elapsed_ms(trim_started);
376 });
377 match trim {
378 PolygonClass::Inside => {
379 interior_normals.push(face_normal(face, projection.u, projection.v)?)
380 }
381 PolygonClass::Boundary => {
382 boundary_normals.push(face_normal(face, projection.u, projection.v)?)
383 }
384 PolygonClass::Outside => {}
385 }
386 }
387 let pool = if interior_normals.is_empty() {
388 &boundary_normals
389 } else {
390 &interior_normals
391 };
392 if !pool.is_empty() {
393 let mut sum = Vec3::default();
394 for normal in pool {
395 sum = sum.add(*normal);
396 }
397 if sum.length() > 1e-3 {
401 return Ok(PointClassification {
402 class: PointClass::On,
403 on_normal: Some(sum.normalized()?),
404 });
405 }
406 }
407 let directions = [
408 Vec3::new(0.577215, 0.618034, 0.532088),
409 Vec3::new(-0.707107, 0.267949, 0.654321),
410 Vec3::new(0.316228, -0.741657, 0.585786),
411 Vec3::new(-0.414214, -0.552786, -0.723607),
412 Vec3::new(0.9482, 0.11893, -0.29456),
413 Vec3::new(-0.13947, 0.90271, -0.40718),
414 Vec3::new(0.62361, -0.33912, -0.70414),
415 Vec3::new(0.20912, 0.51293, 0.83261),
416 ];
417 let ray_length = self.bounds.diagonal() * 3.0 + 1.0;
418 let require_agreement = std::env::var("BREP_CLASSIFY_RAY_AGREE").as_deref() != Ok("0");
428 let mut verdicts: Vec<PointClass> = Vec::new();
429 'directions: for direction in directions {
430 classify_profile(|p| p.rays += 1);
431 let direction = direction.normalized()?;
432 let ray_end = point.add(direction.scale(ray_length));
433 candidates.clear();
434 self.bvh
435 .intersecting_segment(point, ray_end, on_tolerance, &mut candidates);
436 candidates.sort_unstable();
437 let mut crossings = 0;
438 for &index in &candidates {
439 let face = self.faces[index];
440 let margin = on_tolerance.max(self.face_boxes[index].diagonal() * 1e-3);
450 let Some([span_start, span_end]) = clip_segment_to_aabb(
451 point,
452 direction,
453 ray_length,
454 &self.face_boxes[index].expanded(margin),
455 ) else {
456 continue;
457 };
458 let span_start = (span_start - margin).max(0.0);
459 let span_end = (span_end + margin).min(ray_length);
460 if span_end - span_start <= 1e-12 {
461 continue;
462 }
463 let sub_ray = make_line(
464 point.add(direction.scale(span_start)),
465 point.add(direction.scale(span_end)),
466 )?;
467 let csi_started = classify_profile_started();
468 let intersections = ray_face_intersections(&sub_ray, &face.surface, tolerance)?;
469 classify_profile(|p| {
470 p.ray_faces += 1;
471 p.ray_csi_ms += classify_elapsed_ms(csi_started);
472 });
473 for intersection in intersections {
474 if intersection.point.sub(point).length() <= on_tolerance {
475 let trim_started = classify_profile_started();
476 let trim = parameter_point_in_face(
477 face,
478 Vec2 {
479 x: intersection.u,
480 y: intersection.v,
481 },
482 face_uv_tolerance(face, intersection.u, intersection.v, on_tolerance),
483 )?;
484 classify_profile(|p| {
485 p.ray_trim_tests += 1;
486 p.ray_trim_ms += classify_elapsed_ms(trim_started);
487 });
488 if trim != PolygonClass::Outside {
489 return Ok(PointClassification {
490 class: PointClass::On,
491 on_normal: Some(face_normal(face, intersection.u, intersection.v)?),
492 });
493 }
494 continue;
495 }
496 if intersection.tangential {
497 continue 'directions;
498 }
499 let trim_started = classify_profile_started();
500 let trim_class = parameter_point_in_face(
501 face,
502 Vec2 {
503 x: intersection.u,
504 y: intersection.v,
505 },
506 face_uv_tolerance(face, intersection.u, intersection.v, on_tolerance),
507 )?;
508 classify_profile(|p| {
509 p.ray_trim_tests += 1;
510 p.ray_trim_ms += classify_elapsed_ms(trim_started);
511 });
512 if std::env::var("BREP_DEBUG_CLASSIFY").is_ok() {
513 eprintln!(
514 "classify ray dir=({:.3},{:.3},{:.3}) face={} hit=({:.4},{:.4},{:.4}) t3d={:.4} uv=({:.6},{:.6}) trim={:?}",
515 direction.x, direction.y, direction.z,
516 face.id,
517 intersection.point.x, intersection.point.y, intersection.point.z,
518 intersection.point.sub(point).length(),
519 intersection.u, intersection.v,
520 trim_class
521 );
522 }
523 match trim_class {
524 PolygonClass::Boundary => continue 'directions,
525 PolygonClass::Inside => crossings += 1,
526 PolygonClass::Outside => {}
527 }
528 }
529 }
530 let verdict = if crossings % 2 == 1 {
531 PointClass::In
532 } else {
533 PointClass::Out
534 };
535 if std::env::var("BREP_DEBUG_CLASSIFY").is_ok() {
536 eprintln!(
537 "classify verdict dir=({:.3},{:.3},{:.3}) crossings={crossings} -> {verdict:?}",
538 direction.x, direction.y, direction.z
539 );
540 }
541 if !require_agreement || verdicts.contains(&verdict) {
542 return Ok(PointClassification {
543 class: verdict,
544 on_normal: None,
545 });
546 }
547 verdicts.push(verdict);
548 }
549 if let Some(&verdict) = verdicts.last() {
553 return Ok(PointClassification {
554 class: verdict,
555 on_normal: None,
556 });
557 }
558 Err("classifyPointVsSolid: no clean ray direction found".into())
559 }
560
561 pub fn with_coincident_caps(mut self, caps: Vec<(Aabb, f64)>) -> Self {
579 self.coincident_caps = caps;
580 self
581 }
582
583 fn capped_band(&self, point: Vec3, band: f64) -> f64 {
586 self.coincident_caps
587 .iter()
588 .filter(|(region, _)| region.expanded(band).contains(point))
589 .fold(band, |band, &(_, cap)| band.min(cap * (1.0 - 1e-9)))
590 }
591
592 pub fn coincident_on_normal(&self, point: Vec3) -> Result<Option<Vec3>, String> {
593 let started = classify_profile_started();
594 let result = self.coincident_on_normal_inner(point);
595 classify_profile(|p| {
596 p.coincident_calls += 1;
597 p.coincident_ms += classify_elapsed_ms(started);
598 });
599 result
600 }
601
602 fn coincident_on_normal_inner(&self, point: Vec3) -> Result<Option<Vec3>, String> {
603 let band = (self.tolerance * 10.0).max(self.bounds.diagonal() * 1e-7);
604 let band = self.capped_band(point, band);
608 if !self.bounds.expanded(band).contains(point) {
609 return Ok(None);
610 }
611 let mut candidates = Vec::new();
612 self.bvh.containing_point(point, band, &mut candidates);
613 let mut interior_normals: Vec<Vec3> = Vec::new();
614 for &index in &candidates {
615 let face = self.faces[index];
616 let projection = project_point_to_surface(&face.surface, point)?;
617 if projection.distance > band {
618 continue;
619 }
620 let uv_tolerance = face_uv_tolerance(face, projection.u, projection.v, band);
621 if let PolygonClass::Inside = parameter_point_in_face(
622 face,
623 Vec2 {
624 x: projection.u,
625 y: projection.v,
626 },
627 uv_tolerance,
628 )? {
629 interior_normals.push(face_normal(face, projection.u, projection.v)?);
630 }
631 }
632 if interior_normals.is_empty() {
633 return Ok(None);
634 }
635 let mut sum = Vec3::default();
636 for normal in &interior_normals {
637 sum = sum.add(*normal);
638 }
639 if sum.length() <= 1e-3 {
640 return Ok(None);
641 }
642 Ok(Some(sum.normalized()?))
643 }
644}
645
646pub fn classify_point(
647 point: Vec3,
648 solid: &BrepSolid,
649 tolerance: f64,
650) -> Result<PointClassification, String> {
651 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::CLASSIFY);
652 classify_profile_begin();
653 let result = SolidClassifier::new(solid, tolerance)?.classify(point);
654 classify_profile_report("classify_point");
655 result
656}