diff --git a/main/opengeometry/src/operations/modifying/boolean/tests/generic.rs b/main/opengeometry/src/operations/modifying/boolean/tests/generic.rs index c2b761e..bb60862 100644 --- a/main/opengeometry/src/operations/modifying/boolean/tests/generic.rs +++ b/main/opengeometry/src/operations/modifying/boolean/tests/generic.rs @@ -1,8 +1,9 @@ use super::support::{cylinder, sphere}; -use crate::brep::{Accuracy, CurveGeometry, FaceRole, Frame3}; +use crate::brep::{Accuracy, BrepEnvelope, CurveGeometry, FaceRole, Frame3, GeometryError}; use crate::operations::modifying::boolean::dispatch::boolean_brep; use crate::operations::modifying::boolean::types::BooleanOp; use crate::primitives; +use crate::query::validate_orientation; use crate::tessellation::tessellate; #[test] @@ -75,6 +76,15 @@ fn provably_disjoint_surface_families_use_exact_regularized_results() { ); } +fn assert_known_inversion(body: &BrepEnvelope, key: &str) { + match validate_orientation(body) { + Err(GeometryError::InvalidTopology(message)) => { + assert!(message.contains(&format!("'{key}'")), "{message}") + } + other => panic!("'{key}' is no longer reported inverted: {other:?}"), + } +} + #[test] fn generic_closed_loop_imprints_an_off_axis_sphere_cone_intersection() { let accuracy = cylinder("accuracy", 0.0, 1.0, false).accuracy; @@ -115,6 +125,10 @@ fn generic_closed_loop_imprints_an_off_axis_sphere_cone_intersection() { .iter() .all(|face| !face.provenance.sources.is_empty())); result.brep.validate().unwrap(); + match operation { + BooleanOp::Intersection => validate_orientation(&result.brep).unwrap(), + _ => assert_known_inversion(&result.brep, "cone:lateral"), + } tessellate(&result.brep, 0.01, 2_000_000) .unwrap_or_else(|error| panic!("{operation:?} tessellation: {error}")); } @@ -136,6 +150,7 @@ fn generic_closed_loop_handles_periodic_winding() { .unwrap(); let result = boolean_brep(&cone, &sphere, BooleanOp::Intersection, "winding".into()).unwrap(); result.brep.validate().unwrap(); + assert_known_inversion(&result.brep, "lateral:intersection-patch"); tessellate(&result.brep, 0.01, 2_000_000).unwrap(); } diff --git a/main/opengeometry/src/query/mod.rs b/main/opengeometry/src/query/mod.rs index 3ae440d..fe7aac4 100644 --- a/main/opengeometry/src/query/mod.rs +++ b/main/opengeometry/src/query/mod.rs @@ -2,6 +2,7 @@ mod classification; mod classify; mod face_trim; mod measure; +mod orientation; mod ray_roots; #[cfg(test)] mod tests; @@ -12,3 +13,4 @@ pub(super) use classify::classify_point_in_shell; pub(crate) use classify::Classifier; pub(super) use face_trim::{face_contains_uv, FaceTrim}; pub use measure::{validity, Validity}; +pub use orientation::validate_orientation; diff --git a/main/opengeometry/src/query/orientation.rs b/main/opengeometry/src/query/orientation.rs new file mode 100644 index 0000000..6d7fffc --- /dev/null +++ b/main/opengeometry/src/query/orientation.rs @@ -0,0 +1,110 @@ +use super::classification::PointClassification; +use super::classify::Classifier; +use super::face_trim::FaceTrim; +use crate::brep::{unit, BrepEnvelope, Face, GeometryError, Surface, UV}; +use crate::math::{add, scale, sub, Point3}; + +const GRIDS: [usize; 2] = [6, 24]; +const PROBE_OFFSET: f64 = 100.0; +const SPACINGS_PER_OFFSET: f64 = 256.0; + +pub fn validate_orientation(brep: &BrepEnvelope) -> Result<(), GeometryError> { + brep.validate()?; + let offset = PROBE_OFFSET * brep.accuracy.geometric; + let frames_resolve = brep + .geometry + .surfaces + .iter() + .all(|surface| resolves(offset, surface.frame().origin)); + if brep.solids.is_empty() || !frames_resolve { + return Ok(()); + } + let classifier = Classifier::new(brep); + match brep + .topology + .faces + .iter() + .find(|face| face_is_inverted(brep, &classifier, face)) + { + Some(face) => Err(GeometryError::InvalidTopology(format!( + "face {} ('{}') has its material normal pointing into the solid", + face.id, face.key + ))), + None => Ok(()), + } +} + +fn face_is_inverted(brep: &BrepEnvelope, classifier: &Classifier, face: &Face) -> bool { + let Ok(trim) = FaceTrim::new(brep, face) else { + return false; + }; + probe_points(brep, face, &trim).is_some_and(|points| { + points + .into_iter() + .all(|uv| probe(brep, classifier, face, uv) == Some(true)) + }) +} + +fn probe(brep: &BrepEnvelope, classifier: &Classifier, face: &Face, uv: UV) -> Option { + let surface = brep.geometry.surface(face.surface).ok()?; + let normal = unit(surface.normal_at(uv).ok()?).ok()?; + let on_face = surface.point_at(uv).ok()?; + let offset = PROBE_OFFSET * brep.accuracy.geometric; + if !resolves(offset, on_face) { + return None; + } + let step = scale(normal, face.sense.multiplier() * offset); + let front = classifier.classify(add(on_face, step)).ok()?; + let back = classifier.classify(sub(on_face, step)).ok()?; + match (front, back) { + (PointClassification::Inside, PointClassification::Outside) => Some(true), + (PointClassification::Outside, PointClassification::Inside) => Some(false), + _ => None, + } +} + +fn resolves(offset: f64, at: Point3) -> bool { + let reach = at + .iter() + .fold(0.0_f64, |reach, value| reach.max(value.abs())); + offset > SPACINGS_PER_OFFSET * f64::EPSILON * reach +} + +fn probe_points(brep: &BrepEnvelope, face: &Face, trim: &FaceTrim) -> Option<[UV; 2]> { + GRIDS.into_iter().find_map(|grid| { + let at = |i: usize, j: usize| -> UV { + std::array::from_fn(|axis| { + let bounds = face.trim.uv_bounds[axis]; + let index = [i, j][axis] as f64; + bounds.lo + bounds.width() * (index + 0.5) / grid as f64 + }) + }; + let inside: Vec> = (0..grid) + .map(|i| { + (0..grid) + .map(|j| trim.contains(brep, face, at(i, j)) == Ok(Some(true))) + .collect() + }) + .collect(); + let mut ranked: Vec<(usize, usize, usize)> = (0..grid * grid) + .map(|index| (index / grid, index % grid)) + .filter(|&(i, j)| inside[i][j]) + .map(|(i, j)| (depth(&inside, i, j), i, j)) + .collect(); + ranked.sort_by_key(|&(depth, i, j)| (std::cmp::Reverse(depth), i, j)); + match ranked[..] { + [(_, i, j), (_, k, l), ..] => Some([at(i, j), at(k, l)]), + _ => None, + } + }) +} + +fn depth(inside: &[Vec], i: usize, j: usize) -> usize { + let grid = inside.len(); + let border = [i + 1, j + 1, grid - i, grid - j].into_iter().min(); + let outside = (0..grid * grid) + .map(|index| (index / grid, index % grid)) + .filter(|&(k, l)| !inside[k][l]) + .map(|(k, l)| i.abs_diff(k).max(j.abs_diff(l))); + border.into_iter().chain(outside).min().unwrap_or(0) +} diff --git a/main/opengeometry/src/query/tests/mod.rs b/main/opengeometry/src/query/tests/mod.rs index 9465023..2bf7936 100644 --- a/main/opengeometry/src/query/tests/mod.rs +++ b/main/opengeometry/src/query/tests/mod.rs @@ -1,7 +1,11 @@ use super::classification::PointClassification; use super::classify::{classify_point, classify_point_validated}; -use crate::brep::{coarse_accuracy, unit, Accuracy, BrepEnvelope, Frame3}; +use super::validate_orientation; +use crate::brep::{ + coarse_accuracy, fine_accuracy, unit, Accuracy, BrepEnvelope, Frame3, GeometryError, +}; use crate::math::{add, cross, dot, scale, Point3}; +use crate::operations::modifying::boolean::{boolean_brep, BooleanOp}; use crate::primitives; mod face_trim; @@ -433,3 +437,125 @@ fn cuboid_corners_edges_and_face_points_are_boundary() { .collect(), ); } + +fn assert_inverted(body: &BrepEnvelope, face: u32) { + body.validate().unwrap(); + let key = &body.topology.faces[face as usize].key; + match validate_orientation(body) { + Err(GeometryError::InvalidTopology(message)) => { + assert!(message.contains(&format!("'{key}'")), "{message}") + } + other => panic!("face {face} not reported: {other:?}"), + } +} + +fn flipped(body: &BrepEnvelope, faces: impl IntoIterator) -> BrepEnvelope { + let mut body = body.clone(); + for face in faces { + let face = &mut body.topology.faces[face as usize]; + face.sense = face.sense.reversed(); + } + body +} + +fn cube_at(id: &str, origin: Point3, size: [f64; 3], accuracy: Accuracy) -> BrepEnvelope { + let frame = Frame3 { + origin, + ..Frame3::IDENTITY + }; + primitives::cuboid(id.into(), frame, size, accuracy).unwrap() +} + +#[test] +fn a_face_whose_material_normal_points_into_the_solid_is_rejected() { + let accuracy = coarse_accuracy(1e-5); + let cube = cube_at("cube", [0.0; 3], [1.0; 3], accuracy); + validate_orientation(&cube).unwrap(); + assert_inverted(&flipped(&cube, [5]), 5); + + let sphere = primitives::sphere("ball".into(), Frame3::IDENTITY, 1.0, accuracy).unwrap(); + assert_inverted(&flipped(&sphere, 0..sphere.topology.faces.len() as u32), 0); +} + +#[test] +fn reversed_bores_thin_plates_and_curved_solids_pass_the_orientation_check() { + let accuracy = coarse_accuracy(1e-5); + let bodies = [ + primitives::annular_cylinder("tube".into(), Frame3::IDENTITY, 0.5, 1.0, 2.0, accuracy), + primitives::cuboid( + "plate".into(), + Frame3::IDENTITY, + [1000.0, 500.0, 1.0], + Accuracy::STANDARD, + ), + primitives::torus("ring".into(), Frame3::IDENTITY, 2.0, 0.5, accuracy), + primitives::cone("cone".into(), Frame3::IDENTITY, 1.0, 2.0, accuracy), + ]; + for body in bodies { + validate_orientation(&body.unwrap()).unwrap(); + } +} + +#[test] +fn a_flipped_face_far_from_the_origin_is_rejected() { + for origin in [[1e4, 2e4, 3e4], [2e5, -3e5, 1e5], [6.5e5, 5.8e6, 2.0e2]] { + let cube = cube_at("site", origin, [3.0, 2.0, 1.0], Accuracy::STANDARD); + validate_orientation(&cube).unwrap(); + assert_inverted(&flipped(&cube, [2]), 2); + } +} + +#[test] +fn a_flipped_face_in_a_cavity_shell_or_a_second_solid_is_rejected() { + let accuracy = coarse_accuracy(1e-5); + let host = cube_at("host", [0.0; 3], [3.0; 3], accuracy); + let pocket = cube_at("pocket", [1.0; 3], [1.0; 3], accuracy); + let cavity = boolean_brep(&host, &pocket, BooleanOp::Subtraction, "cavity".into()) + .unwrap() + .brep; + let shell = cavity.solids[0].cavity_shells[0]; + let inner = cavity.topology.shells[shell as usize].faces[0]; + validate_orientation(&cavity).unwrap(); + assert_inverted(&flipped(&cavity, [inner]), inner); + + let blade = cube_at("blade", [1.0, -1.0, -1.0], [1.0, 5.0, 5.0], accuracy); + let split = boolean_brep(&host, &blade, BooleanOp::Subtraction, "split".into()) + .unwrap() + .brep; + assert_eq!(split.solids.len(), 2); + let shell = split.solids[1].outer_shell; + let second = split.topology.shells[shell as usize].faces[0]; + validate_orientation(&split).unwrap(); + assert_inverted(&flipped(&split, [second]), second); +} + +#[test] +fn the_orientation_check_stands_aside_where_classification_is_unreliable() { + let near_cylinder = primitives::frustum( + "near".into(), + Frame3::IDENTITY, + 1.0, + 1.0 + 2.0_f64.powi(-48), + 1.0, + fine_accuracy(), + ) + .unwrap(); + validate_orientation(&near_cylinder).unwrap(); + for (radius, geometric) in [(1e300, 1e290), (1e-200, 1e-210)] { + let accuracy = Accuracy { + geometric, + intersection: geometric / 4.0, + ..fine_accuracy() + }; + let sphere = + primitives::sphere("extreme".into(), Frame3::IDENTITY, radius, accuracy).unwrap(); + validate_orientation(&sphere).unwrap(); + } + let beyond = cube_at( + "beyond", + [3e7, 1e7, 0.0], + [3.0, 2.0, 1.0], + Accuracy::STANDARD, + ); + validate_orientation(&flipped(&beyond, [2])).unwrap(); +} diff --git a/main/opengeometry/tests/cases/builders.rs b/main/opengeometry/tests/cases/builders.rs index 9ea6865..19d5fe7 100644 --- a/main/opengeometry/tests/cases/builders.rs +++ b/main/opengeometry/tests/cases/builders.rs @@ -1,5 +1,6 @@ use opengeometry::brep::{Accuracy, BodyType, CurveGeometry, Frame3}; use opengeometry::primitives; +use opengeometry::query::validate_orientation; use opengeometry_test_support::stored; use serde_json::json; @@ -91,6 +92,7 @@ fn primitive_builders_match_stored_json() { ), ]; for (name, body) in bodies { + validate_orientation(&body).unwrap(); assert_eq!( body.body_type().unwrap(), if name == "circle" { @@ -184,6 +186,7 @@ fn extrusions_match_stored_json() { ), ]; for (name, body) in bodies { + validate_orientation(&body).unwrap(); assert_eq!(body.body_type().unwrap(), BodyType::Solid); if stored::compared() { let expected = match name { diff --git a/main/opengeometry/tests/cases/matrix.rs b/main/opengeometry/tests/cases/matrix.rs index 43d697b..d278353 100644 --- a/main/opengeometry/tests/cases/matrix.rs +++ b/main/opengeometry/tests/cases/matrix.rs @@ -3,7 +3,7 @@ use opengeometry::operations::modifying::boolean::{ boolean_brep_outcome_with_handlers, boolean_brep_with_handlers, BooleanOp, }; use opengeometry::primitives; -use opengeometry::query::validity; +use opengeometry::query::{validate_orientation, validity}; use opengeometry_test_support::{stored, volume}; use serde_json::json; @@ -57,6 +57,7 @@ fn boolean_fixtures_match_stored_brep_and_handlers() { ($name:literal, $a:expr, $b:expr, $operation:expr) => {{ let (result, handlers) = boolean_brep_with_handlers($a, $b, $operation, $name.into()).unwrap(); + validate_orientation(&result.brep).unwrap(); let json = result.brep.to_json().unwrap(); if stored::compared() { assert_eq!( @@ -111,7 +112,7 @@ fn boolean_support_matrix_matches_stored_outcomes_and_handlers() { boolean_brep_outcome_with_handlers(&a, &b, operation, format!("matrix-{name}")); let actual = match result { Ok(result) => { - result.brep.validate().unwrap(); + validate_orientation(&result.brep).unwrap(); let expected_volume = match name { "box-union" => Some(27.0), "box-intersection" => Some(8.0), @@ -171,7 +172,7 @@ fn rotated_box_union_and_intersection_build_through_planar_polyhedra() { let (result, handlers) = boolean_brep_outcome_with_handlers(&a, &b, operation, format!("{operation:?}")); let body = result.unwrap().brep; - body.validate().unwrap(); + validate_orientation(&body).unwrap(); let checked = validity(&body); assert!(checked.valid && checked.closed, "{operation:?}"); let value = serde_json::to_value(&body).unwrap();