Skip to main content

brep_direct_edit/edit/direct_edit/
face_deform.rs

1//! Deform one face of a solid by its carrier's control net (Golovanov 2020
2//! §3.16 deformable surface, §6.13 local deformation of a shell), keeping
3//! every edge, vertex, pcurve and neighbouring face exactly as they are.
4//!
5//! The face's carrier is deformed by [`crate::deform_surface_where`] with a
6//! locality region PROVEN to keep the face's boundary: each trim is covered by
7//! the boxes of its pcurve's control polygon span by span (a NURBS curve with
8//! positive weights lies in the convex hull of each span's poles), and a
9//! control point may move only when no such box enters the open interior of
10//! its support (the parameter box outside which its basis function is zero),
11//! every box that touches the support's boundary lies on sides where the basis
12//! vanishes to order 2 (its value and its first derivative across the side are
13//! zero there), and the support lies inside the face (a support whose interior
14//! meets no trim is wholly inside or wholly outside; one point decides). A
15//! surface point and its first partials depend only on the poles whose basis
16//! functions reach them to that order, so along every trim the carrier keeps
17//! its points and tangent planes exactly: the edges still lie on it, G1 with
18//! every neighbour is kept, and no other record of the body changes. The
19//! carrier's elevation and span splits are exact, so the pcurves keep their
20//! meaning.
21//!
22//! Before the deformed carrier is accepted the body is validated and scanned
23//! for self-intersection (a face pushed through another wall), and the scan's
24//! verdict is a refusal, never a repair.
25
26use 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/// One pick on the face: the surface point nearest `anchor` (which must lie
36/// on the face) is moved to `target`; with `normal`, the face's normal there
37/// is made parallel to it.
38#[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    /// Each knot span of the carrier that overlaps the face's parameter box is
49    /// split into this many (1 = none). More gives the deformation more room
50    /// and a tighter locality region.
51    pub resolution: usize,
52    /// The carrier is elevated to at least this degree first (2 ..= 9).
53    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/// What the deformation did, measured on the result.
63#[derive(Clone, Debug)]
64pub struct FaceDeformReport {
65    /// The deformed carrier's control net (rows, columns) and how many of its
66    /// control points could move.
67    pub net: (usize, usize),
68    pub free_poles: usize,
69    /// Largest pick distance and normal angle (radians), read back from the
70    /// deformed carrier.
71    pub max_pick_error: f64,
72    pub max_normal_error: f64,
73    /// Each pick's carrier parameters.
74    pub pick_parameters: Vec<(f64, f64)>,
75}
76
77/// Deform face `face_id` of `solid` as `spec` asks; every other record of the
78/// body is returned unchanged. Refuses by name: an unknown face, a pick whose
79/// anchor is off the face, a trim outside its carrier's domain, any refusal
80/// of the carrier deformation (no free control point under a pick, dependent
81/// picks, a fold, ...), a displacement larger than the face, and a result
82/// that does not validate or passes through itself.
83pub 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    // Inside / boundary tests take ONE uv tolerance, so it comes off the
99    // SMALLER span: off the larger, a patch reparameterised to a huge `v` span
100    // would put every point within tolerance of a `u` side.
101    let parameter_tolerance = 1e-9 * span_u.min(span_v);
102
103    // The trims, covered span by span.
104    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    // The picks, in the carrier's parameters, each on the face.
128    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    // A displacement in proportion to the face, not to its carrier.
151    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
228/// The carrier deformation's refusal, as the kernel's: caller errors and
229/// geometry the request cannot have are `InvalidInput`/`IllPosed`, limits
230/// `UnsupportedGeometry`; the slug is the deformation refusal's name.
231pub(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
277/// The locality rule: a control point with `support` may move when no trim box
278/// enters its support's open interior, every box touching the support lies on
279/// sides where its basis vanishes to order 2, and the support lies inside the
280/// face (one point decides: its interior meets no trim).
281pub(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    // Exact comparisons: a trim even a rounding error inside a support's
284    // side is inside it (holding the pole is the safe answer).
285    for b in trim_boxes {
286        // Clear of the closed support: no effect at all.
287        if b[1] < a0 || b[0] > a1 || b[3] < b0 || b[2] > b1 {
288            continue;
289        }
290        // Into the open interior: the pole reaches the trim.
291        if b[1] > a0 && b[0] < a1 && b[3] > b0 && b[2] < b1 {
292            return false;
293        }
294        // Only along the support's sides: each side the box lies on must
295        // have the basis vanish to order 2 there (value and the first
296        // derivative across it), so the edge and its tangent plane hold.
297        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
306/// Boxes `[u0, u1, v0, v1]` covering a pcurve: one per knot span, the box of
307/// the poles that span uses (convex hull property, weights positive).
308pub(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
326/// The face's size: the box diagonal of its carrier sampled over the face's
327/// parameter box.
328fn 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
344/// The face's deepest interior point: of a 25 x 25 grid over its parameter
345/// box, the point inside the face farthest (in space) from its boundary,
346/// sampled along every coedge. `None` when no grid point is inside.
347pub 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}