1use crate::{thicken_sheet_faces, BrepSolid, KernelRefusal, KernelStage, OffsetCorners, Vec3};
4use std::collections::BTreeSet;
5
6pub fn thicken_faces(solid: &BrepSolid, face_points: &[Vec3], thickness: f64) -> Result<BrepSolid, KernelRefusal> {
11 if face_points.is_empty() {
12 return Err(KernelRefusal::input(KernelStage::Collect, "thicken_faces_points", "thicken_faces: no face named".to_string()));
13 }
14 let mut faces = BTreeSet::new();
15 for &point in face_points {
16 faces.insert(crate::resolve_face_by_point(solid, point)?);
17 }
18 let sheet = crate::feature_pipeline::features::sew_to_solid::extract(solid, &faces);
19 thicken_sheet_faces(&[sheet], thickness, OffsetCorners::Sharp)
20}
21
22#[derive(Clone, Copy, Debug, PartialEq)]
25pub struct Interference {
26 pub volume: f64,
28 pub gap: f64,
31}
32
33pub fn solid_interference(a: &BrepSolid, b: &BrepSolid, tolerance: f64) -> Result<Interference, KernelRefusal> {
39 let [la, ha] = crate::solid_least_box(a, tolerance)?;
40 let [lb, hb] = crate::solid_least_box(b, tolerance)?;
41 let apart = la.x > hb.x || lb.x > ha.x || la.y > hb.y || lb.y > ha.y || la.z > hb.z || lb.z > ha.z;
42 if apart {
43 return Ok(Interference { volume: 0.0, gap: crate::solid_gap(a, b, tolerance)? });
44 }
45 let scale = crate::solid_model_scale(a).max(crate::solid_model_scale(b)).max(1.0);
46 let gap = crate::solid_gap(a, b, tolerance)?;
51 let meet = gap <= tolerance.max(1e-9 * scale);
52 if !meet && !any_shell_inside(a, b, tolerance)? && !any_shell_inside(b, a, tolerance)? {
53 return Ok(Interference { volume: 0.0, gap });
54 }
55 let common = crate::boolean_operation(a, b, crate::BooleanOperation::Intersect, &crate::BooleanOptions::default())?;
56 let volume = if common.shells.iter().all(|shell| shell.faces.is_empty()) {
57 0.0
58 } else {
59 crate::solid_signed_volume(&common)
60 .map_err(|e| KernelRefusal::internal(KernelStage::Validate, "interference_volume", format!("interference: {e}")))?
61 .max(0.0)
62 };
63 let side = |l: Vec3, h: Vec3| {
67 let mut e = [h.x - l.x, h.y - l.y, h.z - l.z];
68 e.sort_by(f64::total_cmp);
69 e[1] * e[2]
70 };
71 if volume > 0.0 && (!meet || volume > 1e-10 * scale * side(la, ha).min(side(lb, hb))) {
72 return Ok(Interference { volume, gap: 0.0 });
73 }
74 Ok(Interference { volume: 0.0, gap })
75}
76
77fn any_shell_inside(inner: &BrepSolid, outer: &BrepSolid, tolerance: f64) -> Result<bool, KernelRefusal> {
80 for shell in &inner.shells {
81 let Some(face) = shell.faces.first() else { continue };
82 let uv = match face.loops.iter().flat_map(|l| &l.coedges).next() {
83 Some(coedge) => coedge.pcurve.domain().and_then(|[t, _]| coedge.pcurve.evaluate(t)).map(|p| [p.x, p.y]),
84 None => face.surface.domain_u().and_then(|[u0, u1]| face.surface.domain_v().map(|[v0, v1]| [0.5 * (u0 + u1), 0.5 * (v0 + v1)])),
85 };
86 let point = uv.and_then(|[u, v]| face.surface.evaluate(u, v));
87 let point = point.map_err(|e| KernelRefusal::internal(KernelStage::Classify, "interference_inside", format!("interference: {e}")))?;
88 let class = crate::classify_point(point, outer, tolerance)
89 .map_err(|e| KernelRefusal::internal(KernelStage::Classify, "interference_inside", format!("interference: {e}")))?;
90 if class.class != crate::PointClass::Out {
91 return Ok(true);
92 }
93 }
94 Ok(false)
95}
96
97fn faces_named(solid: &BrepSolid, face_points: &[Vec3], what: &str) -> Result<Vec<u64>, KernelRefusal> {
102 if face_points.is_empty() {
103 return Err(KernelRefusal::input(KernelStage::Collect, format!("{what}_points"), format!("{what}: no face named")));
104 }
105 let tolerance = (crate::solid_model_scale(solid) * 1e-6).max(1e-9);
106 let mut seen = BTreeSet::new();
107 let mut faces = Vec::new();
108 for &point in face_points {
109 let foot = crate::nearest_boundary_point(solid, point, tolerance)?;
110 let face = match foot {
111 Some(crate::BoundaryFoot { distance, .. }) if !(distance <= tolerance) => {
113 return Err(KernelRefusal::input(KernelStage::Collect, "point_off_faces", format!("{what}: the point {point:?} is {distance:e} from the boundary, off every face")));
114 }
115 Some(crate::BoundaryFoot { place: crate::BoundaryPlace::Face { face, .. }, .. }) => face,
116 Some(foot) => {
119 let edges: Vec<u64> = match foot.place {
120 crate::BoundaryPlace::Edge { edge, .. } => vec![edge],
121 crate::BoundaryPlace::Vertex { vertex } => solid.edges.iter().filter(|e| e.start_vertex_id == vertex || e.end_vertex_id == vertex).map(|e| e.id).collect(),
122 crate::BoundaryPlace::Face { face, .. } => vec![face],
123 };
124 let round: BTreeSet<u64> = solid
125 .shells
126 .iter()
127 .flat_map(|shell| &shell.faces)
128 .filter(|face| face.loops.iter().flat_map(|lp| &lp.coedges).any(|coedge| edges.contains(&coedge.edge_id)))
129 .map(|face| face.id)
130 .collect();
131 match (round.len(), round.iter().next()) {
132 (1, Some(&face)) => face,
133 _ => {
134 return Err(KernelRefusal::input(KernelStage::Collect, "point_on_edge", format!("{what}: the point {point:?} lies on an edge or vertex between faces, naming none")));
135 }
136 }
137 }
138 None => return Err(KernelRefusal::input(KernelStage::Collect, "no_faces", format!("{what}: the solid has no faces"))),
139 };
140 if seen.insert(face) {
141 faces.push(face);
142 }
143 }
144 Ok(faces)
145}
146
147pub fn offset_faces(solid: &BrepSolid, face_points: &[Vec3], distance: f64) -> Result<BrepSolid, KernelRefusal> {
157 if !distance.is_finite() {
158 return Err(KernelRefusal::input(KernelStage::Collect, "offset_faces_distance", "offset_faces: the distance must be finite"));
159 }
160 let faces = faces_named(solid, face_points, "offset_faces")?;
161 if distance == 0.0 {
162 return Ok(solid.clone());
163 }
164 let resolution = (crate::solid_model_scale(solid) * 1e-7).max(1e-9);
167 if distance.abs() < resolution {
168 return Err(KernelRefusal::input(
169 KernelStage::Collect,
170 "motion_below_tolerance",
171 format!("offset_faces: the distance {distance:e} is below the {resolution:e} the push reads points to"),
172 ));
173 }
174 let mut notes = Vec::new();
175 crate::feature_pipeline::features::push_face::push_faces(solid.clone(), &faces, distance, &mut notes, false).map_err(|refusal| match refusal {
176 crate::feature_pipeline::FeatureRefusal::Typed(refusal) => refusal,
177 crate::feature_pipeline::FeatureRefusal::Text(message) => KernelRefusal::unsupported(KernelStage::Collect, "offset_faces", message),
178 })
179}
180
181fn rotation_turn(r: &[[f64; 3]; 3]) -> Option<(Vec3, f64)> {
186 let trace = r[0][0] + r[1][1] + r[2][2];
187 let skew = Vec3::new(r[2][1] - r[1][2], r[0][2] - r[2][0], r[1][0] - r[0][1]);
188 let big = skew.x.abs().max(skew.y.abs()).max(skew.z.abs());
190 let skew_length = if big > 0.0 { big * Vec3::new(skew.x / big, skew.y / big, skew.z / big).length() } else { 0.0 };
191 let sine = 0.5 * skew_length;
192 let cosine = (0.5 * (trace - 1.0)).clamp(-1.0, 1.0);
193 let angle = sine.atan2(cosine);
194 if !(angle > 0.0) {
195 return None;
196 }
197 if cosine > -0.5 {
198 return Some((Vec3::new(skew.x / big, skew.y / big, skew.z / big).normalized().ok()?, angle));
199 }
200 let k = 1.0 - cosine;
202 let column = (0..3).max_by(|&i, &j| r[i][i].total_cmp(&r[j][j])).unwrap_or(0);
203 let mut a = [0.0; 3];
204 a[column] = ((r[column][column] - cosine) / k).max(0.0).sqrt();
205 for i in 0..3 {
206 if i != column {
207 a[i] = (r[i][column] + r[column][i]) / (2.0 * k * a[column]);
208 }
209 }
210 let mut axis = Vec3::new(a[0], a[1], a[2]).normalized().ok()?;
211 if axis.dot(skew) < 0.0 {
213 axis = axis.scale(-1.0);
214 }
215 Some((axis, angle))
216}
217
218pub fn transform_faces(solid: &BrepSolid, face_points: &[Vec3], matrix: [[f64; 4]; 3]) -> Result<BrepSolid, KernelRefusal> {
231 if !matrix.iter().flatten().all(|x| x.is_finite()) {
232 return Err(KernelRefusal::input(KernelStage::Collect, "transform_faces_matrix", "transform_faces: the matrix must be finite"));
233 }
234 let r = [[matrix[0][0], matrix[0][1], matrix[0][2]], [matrix[1][0], matrix[1][1], matrix[1][2]], [matrix[2][0], matrix[2][1], matrix[2][2]]];
235 let t = Vec3::new(matrix[0][3], matrix[1][3], matrix[2][3]);
236 let mut off = 0.0f64;
237 for i in 0..3 {
238 for j in 0..3 {
239 let dot: f64 = (0..3).map(|k| r[k][i] * r[k][j]).sum();
240 off = off.max((dot - if i == j { 1.0 } else { 0.0 }).abs());
241 }
242 }
243 let det = r[0][0] * (r[1][1] * r[2][2] - r[1][2] * r[2][1]) - r[0][1] * (r[1][0] * r[2][2] - r[1][2] * r[2][0]) + r[0][2] * (r[1][0] * r[2][1] - r[1][1] * r[2][0]);
244 if !(off <= 1e-9 && det > 0.0) {
245 return Err(KernelRefusal::input(
246 KernelStage::Collect,
247 "transform_faces_rigid",
248 format!("transform_faces: the matrix's R is not a rotation (off orthonormal by {off:e}, determinant {det}): a face transform is a rigid motion"),
249 ));
250 }
251 let faces = faces_named(solid, face_points, "transform_faces")?;
252 let pivot = crate::feature_pipeline::features::transform_face::selection_centre(solid, &faces).unwrap_or(Vec3::new(0.0, 0.0, 0.0));
258 let turned = Vec3::new(
259 r[0][0] * pivot.x + r[0][1] * pivot.y + r[0][2] * pivot.z,
260 r[1][0] * pivot.x + r[1][1] * pivot.y + r[1][2] * pivot.z,
261 r[2][0] * pivot.x + r[2][1] * pivot.y + r[2][2] * pivot.z,
262 );
263 let slide = t.add(turned.sub(pivot));
264 let reach = solid
267 .vertices
268 .iter()
269 .map(|v| v.point)
270 .chain(solid.shells.iter().flat_map(|shell| &shell.faces).flat_map(|face| face.surface.control_points.iter().flatten()).filter_map(|p| p.point().ok()))
271 .map(|p| p.sub(pivot).length())
272 .fold(0.0f64, f64::max);
273 let scale = crate::solid_model_scale(solid).max(1e-300);
274 let read = rotation_turn(&r);
275 let swing = read.map_or(0.0, |(_, angle)| angle * reach);
276 let turn = read.filter(|_| swing > 1e-12 * scale).map(|(axis, angle)| (pivot, axis, angle));
277 let translates = slide.x != 0.0 || slide.y != 0.0 || slide.z != 0.0;
279 let rest = (0..3).all(|i| (0..3).all(|j| r[i][j] == if i == j { 1.0 } else { 0.0 })) && t.x == 0.0 && t.y == 0.0 && t.z == 0.0;
283 if rest {
284 return Ok(solid.clone());
285 }
286 let resolution = (scale * 1e-7).max(1e-9);
290 if slide.length() * 1e-9 > resolution {
294 return Err(KernelRefusal::input(
295 KernelStage::Collect,
296 "motion_out_of_envelope",
297 format!("transform_faces: the motion slides the faces {:e}, past what the re-solve reads to the model's resolution {resolution:e}", slide.length()),
298 ));
299 }
300 if turn.is_none() && slide.length() + swing < resolution {
301 return Err(KernelRefusal::input(
302 KernelStage::Collect,
303 "motion_below_tolerance",
304 format!("transform_faces: the motion moves the faces {:e}, below the {resolution:e} the re-solve reads points to", slide.length() + swing),
305 ));
306 }
307 crate::feature_pipeline::features::transform_face::move_faces_road(solid, &faces, turn, translates, slide)
312 .map(|(body, _notes)| body)
313 .map_err(|(refusal, _step)| past_a_neighbour_is_ill_posed(refusal))
314}
315
316fn past_a_neighbour_is_ill_posed(mut refusal: KernelRefusal) -> KernelRefusal {
319 use crate::face_refusal_slugs::{CURVED_EDGE_INVERSION, EDGE_INVERSION};
320 if matches!(&refusal.class, crate::RefusalClass::UnsupportedGeometry { what } if what == EDGE_INVERSION || what == CURVED_EDGE_INVERSION) {
321 refusal.class = crate::RefusalClass::IllPosed { what: "moved_past_a_neighbour".into() };
322 }
323 refusal
324}
325