1use crate::topology::FaceRecord;
27use crate::{
28 deform_surface_where, parameter_point_in_face, PoleSupport, project_point_to_surface, solid_self_intersections,
29 BrepSolid, DeformPick, DeformRefusal, DeformSpec, KernelRefusal, KernelStage, NurbsCurve, NurbsSurface,
30 PolygonClass, SelfIntersectionOptions, Vec2, Vec3,
31};
32
33const OP: &str = "deformFace";
34
35#[derive(Clone, Copy, Debug)]
39pub struct FaceDeformPick {
40 pub anchor: Vec3,
41 pub target: Vec3,
42 pub normal: Option<Vec3>,
43}
44
45#[derive(Clone, Debug)]
46pub struct FaceDeformSpec {
47 pub picks: Vec<FaceDeformPick>,
48 pub resolution: usize,
52 pub min_degree: usize,
54}
55
56impl Default for FaceDeformSpec {
57 fn default() -> Self {
58 Self { picks: Vec::new(), resolution: 4, min_degree: 3 }
59 }
60}
61
62#[derive(Clone, Debug)]
64pub struct FaceDeformReport {
65 pub net: (usize, usize),
68 pub free_poles: usize,
69 pub max_pick_error: f64,
72 pub max_normal_error: f64,
73 pub pick_parameters: Vec<(f64, f64)>,
75}
76
77pub fn deform_face(
84 solid: &BrepSolid,
85 face_id: u64,
86 spec: &FaceDeformSpec,
87) -> Result<(BrepSolid, FaceDeformReport), KernelRefusal> {
88 let face = solid
89 .shells
90 .iter()
91 .flat_map(|shell| &shell.faces)
92 .find(|face| face.id == face_id)
93 .ok_or_else(|| KernelRefusal::input(KernelStage::Collect, "face_not_found", format!("{OP}: no face {face_id} in the body")))?;
94 let surface = &face.surface;
95 let [u0, u1] = surface.domain_u().map_err(|e| internal(&e))?;
96 let [v0, v1] = surface.domain_v().map_err(|e| internal(&e))?;
97 let (span_u, span_v) = (u1 - u0, v1 - v0);
98 let parameter_tolerance = 1e-9 * span_u.min(span_v);
102
103 let mut trim_boxes: Vec<[f64; 4]> = Vec::new();
105 for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
106 trim_boxes.extend(span_boxes(&coedge.pcurve));
107 }
108 if trim_boxes.is_empty() {
109 return Err(KernelRefusal::unsupported(KernelStage::Collect, "face_without_trims", format!(
110 "{OP}: face {face_id} has no boundary loops to keep"
111 )));
112 }
113 let slack = 1e-6 * span_u.max(span_v);
114 if let Some(outside) = trim_boxes
115 .iter()
116 .find(|b| b[0] < u0 - slack || b[1] > u1 + slack || b[2] < v0 - slack || b[3] > v1 + slack)
117 {
118 return Err(KernelRefusal::unsupported(KernelStage::Collect, "trim_outside_domain", format!(
119 "{OP}: a trim of face {face_id} runs outside its carrier's domain (pcurve box {outside:?}, domain \
120 [{u0}, {u1}] x [{v0}, {v1}]); the locality region cannot be proven"
121 )));
122 }
123 let face_box = trim_boxes.iter().fold([f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY], |a, b| {
124 [a[0].min(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].max(b[3])]
125 });
126
127 let scale = crate::solid_model_scale(solid).max(f64::MIN_POSITIVE);
129 let mut picks = Vec::with_capacity(spec.picks.len());
130 let mut pick_parameters = Vec::with_capacity(spec.picks.len());
131 for (index, pick) in spec.picks.iter().enumerate() {
132 let foot = project_point_to_surface(surface, pick.anchor).map_err(|e| internal(&e))?;
133 if !(foot.distance <= 1e-6 * scale) {
134 return Err(KernelRefusal::input(KernelStage::Collect, "anchor_off_face", format!(
135 "{OP}: pick {index}'s anchor {:?} is {:e} from face {face_id}'s surface",
136 pick.anchor, foot.distance
137 )));
138 }
139 let class = parameter_point_in_face(face, Vec2 { x: foot.u, y: foot.v }, parameter_tolerance).map_err(|e| internal(&e))?;
140 if class != PolygonClass::Inside {
141 return Err(KernelRefusal::input(KernelStage::Collect, "anchor_off_face", format!(
142 "{OP}: pick {index}'s anchor {:?} lies on face {face_id}'s carrier but not inside the face ({class:?})",
143 pick.anchor
144 )));
145 }
146 picks.push(DeformPick { u: foot.u, v: foot.v, target: pick.target, normal: pick.normal });
147 pick_parameters.push((foot.u, foot.v));
148 }
149
150 let face_size = face_extent(face, &face_box)?;
152 for (index, pick) in spec.picks.iter().enumerate() {
153 let moved = pick.target.sub(pick.anchor).length();
154 if !(moved <= face_size) {
155 return Err(KernelRefusal::input(KernelStage::Collect, "displacement_too_large", format!(
156 "{OP}: pick {index} moves {moved:e}, more than face {face_id}'s size {face_size:e}"
157 )));
158 }
159 }
160
161 let deform_spec = DeformSpec {
162 picks,
163 min_degree: spec.min_degree,
164 split_spans: [spec.resolution.max(1), spec.resolution.max(1)],
165 split_window: Some(face_box),
166 ..DeformSpec::default()
167 };
168 let may_move = |support: PoleSupport| support_may_move(face, &trim_boxes, parameter_tolerance, support);
169 let deformed = deform_surface_where(surface, &deform_spec, &may_move).map_err(|refusal| deform_refusal(face_id, refusal))?;
170
171 let mut result = solid.clone();
172 result.mass_properties_cache = Default::default();
173 for record in result.shells.iter_mut().flat_map(|shell| shell.faces.iter_mut()) {
174 if record.id == face_id {
175 record.surface = deformed.surface.clone();
176 }
177 }
178 let issues = result.validate();
179 if !issues.is_empty() {
180 return Err(KernelRefusal::new(
181 crate::RefusalClass::InvalidResultTopology { issues: issues.len() as u32 },
182 KernelStage::Validate,
183 format!("{OP}: the deformed body does not validate: {issues:?}"),
184 ));
185 }
186 let report = solid_self_intersections(&result, SelfIntersectionOptions::for_solid(&result)).map_err(|e| internal(&e))?;
187 if report.truncated {
188 return Err(KernelRefusal::unsupported(KernelStage::Validate, "deform_scan_incomplete", format!(
189 "{OP}: the self-intersection scan of the deformed body stopped at its size bound, so a face passing \
190 through the body cannot be ruled out"
191 )));
192 }
193 if report.is_flagged() {
194 let mut faces: Vec<u64> = Vec::new();
195 for crossing in &report.confirmed {
196 for id in [crossing.face_a, crossing.face_b] {
197 if !faces.contains(&id) {
198 faces.push(id);
199 }
200 }
201 }
202 return Err(KernelRefusal::ill_posed(KernelStage::Validate, "deform_self_intersection", format!(
203 "{OP}: the deformed face {face_id} passes through the body (faces {faces:?})"
204 )));
205 }
206 let volume = crate::solid_signed_volume(&result).map_err(|e| internal(&e))?;
207 if !(volume > 0.0) {
208 return Err(KernelRefusal::new(crate::RefusalClass::NonPositiveVolume, KernelStage::Validate, format!(
209 "{OP}: the deformed body turned inside out"
210 )));
211 }
212 Ok((
213 result,
214 FaceDeformReport {
215 net: deformed.net,
216 free_poles: deformed.free_poles,
217 max_pick_error: deformed.max_pick_error,
218 max_normal_error: deformed.max_normal_error,
219 pick_parameters,
220 },
221 ))
222}
223
224pub(super) fn internal(message: &str) -> KernelRefusal {
225 KernelRefusal::internal(KernelStage::Collect, "deform_face", format!("{OP}: {message}"))
226}
227
228pub(super) fn deform_refusal(face_id: u64, refusal: DeformRefusal) -> KernelRefusal {
232 let message = format!("{OP}: face {face_id}: {refusal:?}");
233 let slug = match &refusal {
234 DeformRefusal::NoPicks => "no_picks",
235 DeformRefusal::TooManyPicks { .. } => "too_many_picks",
236 DeformRefusal::InvalidSpec(_) => "invalid_spec",
237 DeformRefusal::InvalidPick { .. } => "invalid_pick",
238 DeformRefusal::DuplicatePicks { .. } => "duplicate_picks",
239 DeformRefusal::PickOnHeldRegion { .. } => "pick_on_held_region",
240 DeformRefusal::DependentConstraints { .. } => "dependent_constraints",
241 DeformRefusal::DisplacementTooLarge { .. } => "displacement_too_large",
242 DeformRefusal::Folded { .. } => "folded",
243 DeformRefusal::Amplified { .. } => "amplified",
244 DeformRefusal::InvalidTie { .. } => "invalid_tie",
245 DeformRefusal::EdgeRowsDisagree { .. } => "edge_rows_disagree",
246 DeformRefusal::EdgeNotUniformlyTangent { .. } => "edge_not_uniformly_tangent",
247 DeformRefusal::DependentTie { .. } => "dependent_tie",
248 DeformRefusal::TooManyConstraints { .. } => "too_many_constraints",
249 DeformRefusal::EdgeFoldedThrough { .. } => "edge_folded_through",
250 DeformRefusal::InvalidWeights { .. } => "invalid_weights",
251 DeformRefusal::InvalidSurface(_) => "invalid_surface",
252 DeformRefusal::UnclampedKnots { .. } => "unclamped_knots",
253 DeformRefusal::NetTooLarge { .. } => "net_too_large",
254 DeformRefusal::IllConditioned { .. } => "ill_conditioned",
255 DeformRefusal::ClosedDirectionNotHeld { .. } => "seam_not_held",
256 DeformRefusal::CollapsedSideNotHeld { .. } => "pole_not_held",
257 DeformRefusal::Refinement(_) => "refinement",
258 };
259 match &refusal {
260 DeformRefusal::NoPicks
261 | DeformRefusal::TooManyPicks { .. }
262 | DeformRefusal::InvalidSpec(_)
263 | DeformRefusal::InvalidPick { .. }
264 | DeformRefusal::DuplicatePicks { .. } => KernelRefusal::input(KernelStage::Collect, slug, message),
265 DeformRefusal::PickOnHeldRegion { .. }
266 | DeformRefusal::DependentConstraints { .. }
267 | DeformRefusal::DisplacementTooLarge { .. }
268 | DeformRefusal::Folded { .. }
269 | DeformRefusal::Amplified { .. }
270 | DeformRefusal::DependentTie { .. }
271 | DeformRefusal::EdgeFoldedThrough { .. }
272 | DeformRefusal::EdgeNotUniformlyTangent { .. } => KernelRefusal::ill_posed(KernelStage::Refine, slug, message),
273 _ => KernelRefusal::unsupported(KernelStage::Refine, slug, message),
274 }
275}
276
277pub(super) fn support_may_move(face: &FaceRecord, trim_boxes: &[[f64; 4]], parameter_tolerance: f64, support: PoleSupport) -> bool {
282 let [a0, a1, b0, b1] = support.bounds;
283 for b in trim_boxes {
286 if b[1] < a0 || b[0] > a1 || b[3] < b0 || b[2] > b1 {
288 continue;
289 }
290 if b[1] > a0 && b[0] < a1 && b[3] > b0 && b[2] < b1 {
292 return false;
293 }
294 let on = [b[1] <= a0, b[0] >= a1, b[3] <= b0, b[2] >= b1];
298 if on.iter().zip(support.vanishing).any(|(&touch, order)| touch && order < 2) {
299 return false;
300 }
301 }
302 let centre = Vec2 { x: 0.5 * (a0 + a1), y: 0.5 * (b0 + b1) };
303 matches!(parameter_point_in_face(face, centre, parameter_tolerance), Ok(PolygonClass::Inside))
304}
305
306pub(super) fn span_boxes(pcurve: &NurbsCurve) -> Vec<[f64; 4]> {
309 let p = pcurve.degree;
310 let count = pcurve.control_points.len();
311 let mut boxes = Vec::new();
312 for span in p..count {
313 if pcurve.knots[span + 1] <= pcurve.knots[span] {
314 continue;
315 }
316 let mut b = [f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY];
317 for pole in &pcurve.control_points[span - p..=span] {
318 let (u, v) = (pole.x / pole.w, pole.y / pole.w);
319 b = [b[0].min(u), b[1].max(u), b[2].min(v), b[3].max(v)];
320 }
321 boxes.push(b);
322 }
323 boxes
324}
325
326fn face_extent(face: &FaceRecord, face_box: &[f64; 4]) -> Result<f64, KernelRefusal> {
329 let surface: &NurbsSurface = &face.surface;
330 let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
331 let mut hi = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
332 for a in 0..=8 {
333 for b in 0..=8 {
334 let u = face_box[0] + (face_box[1] - face_box[0]) * a as f64 / 8.0;
335 let v = face_box[2] + (face_box[3] - face_box[2]) * b as f64 / 8.0;
336 let p = surface.evaluate(u, v).map_err(|e| internal(&e))?;
337 lo = Vec3::new(lo.x.min(p.x), lo.y.min(p.y), lo.z.min(p.z));
338 hi = Vec3::new(hi.x.max(p.x), hi.y.max(p.y), hi.z.max(p.z));
339 }
340 }
341 Ok(hi.sub(lo).length())
342}
343
344pub fn face_deform_default_anchor(face: &FaceRecord) -> Option<Vec3> {
348 let surface = &face.surface;
349 let boxes: Vec<[f64; 4]> = face.loops.iter().flat_map(|lp| &lp.coedges).flat_map(|c| span_boxes(&c.pcurve)).collect();
350 let face_box = boxes.iter().fold([f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY], |a, b| {
351 [a[0].min(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].max(b[3])]
352 });
353 if !face_box.iter().all(|x| x.is_finite()) {
354 return None;
355 }
356 let mut boundary = Vec::new();
357 for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
358 let Ok([s0, s1]) = coedge.pcurve.domain() else { continue };
359 for k in 0..=32 {
360 let Ok(uv) = coedge.pcurve.evaluate(s0 + (s1 - s0) * k as f64 / 32.0) else { continue };
361 if let Ok(p) = surface.evaluate(uv.x, uv.y) {
362 boundary.push(p);
363 }
364 }
365 }
366 let tolerance = 1e-9 * (face_box[1] - face_box[0]).min(face_box[3] - face_box[2]);
367 let mut best: Option<(f64, Vec3)> = None;
368 for a in 1..25 {
369 for b in 1..25 {
370 let u = face_box[0] + (face_box[1] - face_box[0]) * a as f64 / 25.0;
371 let v = face_box[2] + (face_box[3] - face_box[2]) * b as f64 / 25.0;
372 if !matches!(parameter_point_in_face(face, Vec2 { x: u, y: v }, tolerance), Ok(PolygonClass::Inside)) {
373 continue;
374 }
375 let Ok(p) = surface.evaluate(u, v) else { continue };
376 let depth = boundary.iter().map(|q| q.sub(p).length()).fold(f64::INFINITY, f64::min);
377 if best.is_none_or(|(d, _)| depth > d) {
378 best = Some((depth, p));
379 }
380 }
381 }
382 best.map(|(_, p)| p)
383}