Skip to main content

brep_geometry/geometry/deform/
tied.rs

1//! Several surfaces deformed together, tied along shared boundary sides.
2//!
3//! Each surface is prepared as for one ([`prepare_base`]); then every tie's
4//! two boundary rows are made comparable EXACTLY (elevation to one degree and
5//! the union of the knots along the edge, both directions mapped onto each
6//! other affinely, reversed when the tie says so) and must then coincide pole
7//! for pole. One quadratic programme over all the surfaces' free poles
8//! (block-diagonal thin-plate energy, [`solve_blocks`]) carries:
9//!
10//! - the picks of every surface;
11//! - **G0** tie rows: each pair of matching boundary poles moves together;
12//! - **G1** tie rows where the BASE edge is smooth: with `c_a = P0 − P1a` (into
13//!   the edge from surface a) and `c_b = P1b − P0` (out of it into b) collinear
14//!   with ONE ratio `λ = |c_b| / |c_a|` along the whole edge, the rows
15//!   `(D1b − D0) = λ (D0 − D1a)` keep them so (linear: λ is frozen). That is a
16//!   common tangent plane along the edge for polynomial rows; a smooth edge
17//!   whose ratio varies, or whose rows are rational, is refused
18//!   ([`DeformRefusal::EdgeNotUniformlyTangent`]) rather than creased;
19//! - at a surface corner where two of its tied sides meet, the 2×2 pole block
20//!   is held (G1 there would need twist compatibility the rows do not give).
21//!
22//! A sharp shared edge (not smooth in the base) takes G0 only; its dihedral
23//! must keep its sign along the edge, or the surfaces have swung through each
24//! other there ([`DeformRefusal::EdgeFoldedThrough`]).
25
26use super::*;
27
28/// One surface of a tied deformation: its picks, holds and room in `spec`
29/// (picks may be empty), and which of its control points may move.
30pub struct TiedSurface<'a> {
31    pub surface: &'a NurbsSurface,
32    pub spec: DeformSpec,
33    pub may_move: &'a dyn Fn(PoleSupport) -> bool,
34}
35
36/// Surfaces `a` and `b` share their boundary sides `side_a` and `side_b`;
37/// `reversed` when the two sides run opposite ways along the edge.
38#[derive(Clone, Copy, Debug, PartialEq)]
39pub struct SurfaceTie {
40    pub a: usize,
41    pub side_a: DeformSide,
42    pub b: usize,
43    pub side_b: DeformSide,
44    pub reversed: bool,
45}
46
47/// What a tie kept across its edge.
48#[derive(Clone, Copy, Debug, PartialEq)]
49pub enum TieContinuity {
50    /// Position only: the base edge is sharp, and its dihedral kept its sign.
51    Sharp,
52    /// Position and tangent plane, with the frozen cross ratio.
53    Tangent { ratio: f64 },
54}
55
56#[derive(Clone, Debug)]
57pub struct TiedResult {
58    /// One per input surface, in order.
59    pub results: Vec<DeformResult>,
60    /// One per tie, in order.
61    pub continuity: Vec<TieContinuity>,
62    /// Corner blocks held because two tied sides meet there.
63    pub held_corners: usize,
64}
65
66/// The direction along a side (the parameter that varies on it).
67fn along(side: DeformSide) -> KnotDirection {
68    match side {
69        DeformSide::UMin | DeformSide::UMax => KnotDirection::V,
70        DeformSide::VMin | DeformSide::VMax => KnotDirection::U,
71    }
72}
73
74/// The net index `(i, j)` of the pole `depth` rows in from `side`, `k` along it.
75fn index_on(surface: &NurbsSurface, side: DeformSide, depth: usize, k: usize) -> (usize, usize) {
76    let rows = surface.control_points.len();
77    let columns = surface.control_points[0].len();
78    match side {
79        DeformSide::UMin => (depth, k),
80        DeformSide::UMax => (rows - 1 - depth, k),
81        DeformSide::VMin => (k, depth),
82        DeformSide::VMax => (k, columns - 1 - depth),
83    }
84}
85
86fn side_len(surface: &NurbsSurface, side: DeformSide) -> usize {
87    match along(side) {
88        KnotDirection::V => surface.control_points[0].len(),
89        KnotDirection::U => surface.control_points.len(),
90    }
91}
92
93/// The edge parameter range of `side` (the domain of the along direction).
94fn along_domain(surface: &NurbsSurface, side: DeformSide) -> [f64; 2] {
95    let (degree, knots) = knots_of(surface, along(side));
96    [knots[degree], knots[knots.len() - 1 - degree]]
97}
98
99/// Interior knots (with multiplicity) of the along direction.
100fn interior_knots(surface: &NurbsSurface, direction: KnotDirection) -> Vec<f64> {
101    let (degree, knots) = knots_of(surface, direction);
102    knots[degree + 1..knots.len() - 1 - degree].to_vec()
103}
104
105/// Insert into `target` (along `direction`) every knot of `source` (mapped by
106/// `map`) that `target` lacks, with multiplicity. Returns whether it changed.
107fn merge_knots(
108    target: &mut NurbsSurface,
109    direction: KnotDirection,
110    source: &[f64],
111    map: impl Fn(f64) -> f64,
112) -> Result<bool, DeformRefusal> {
113    let mine = interior_knots(target, direction);
114    // One knot, relative to the domain: an absolute bar would merge distinct
115    // knots on a small domain (the rows then match while the curves do not).
116    let (degree, knots) = knots_of(target, direction);
117    let snap = KNOT_RELATIVE * (knots[knots.len() - 1 - degree] - knots[degree]);
118    let mut inserts = Vec::new();
119    let mut i = 0;
120    while i < source.len() {
121        let value = source[i];
122        let count = source[i..].iter().take_while(|&&k| k == value).count();
123        let mapped = map(value);
124        let have = mine.iter().filter(|&&k| (k - mapped).abs() <= snap).count();
125        for _ in have..count {
126            inserts.push(mapped);
127        }
128        i += count;
129    }
130    if inserts.is_empty() {
131        return Ok(false);
132    }
133    *target = target.refine_knots(direction, &inserts).map_err(DeformRefusal::Refinement)?;
134    Ok(true)
135}
136
137/// Knots this close, relative to the domain, are one.
138const KNOT_RELATIVE: f64 = 1e-12;
139/// The whole tied system's bounds: free control points over every surface,
140/// and constraint rows (the Schur complement and its columns are dense:
141/// rows × 3 × points doubles, about 300 MB at these bounds).
142pub const MAX_TIED_POLES: usize = 8192;
143pub const MAX_TIED_ROWS: usize = 1536;
144
145/// Deform `surfaces` together under `ties`. Every surface comes back on its
146/// prepared (elevated, split, merged) net; a tie's two boundary rows come back
147/// identical, and tangent-continuous where the base edge was.
148pub fn deform_surfaces_tied(surfaces: &[TiedSurface], ties: &[SurfaceTie]) -> Result<TiedResult, DeformRefusal> {
149    let count = surfaces.len();
150    for (index, tie) in ties.iter().enumerate() {
151        if tie.a >= count || tie.b >= count || (tie.a == tie.b && tie.side_a == tie.side_b) {
152            return Err(DeformRefusal::InvalidTie { tie: index, reason: format!("{tie:?} on {count} surfaces") });
153        }
154    }
155    let total_picks: usize = surfaces.iter().map(|s| s.spec.picks.len()).sum();
156    if total_picks == 0 {
157        return Err(DeformRefusal::NoPicks);
158    }
159    if total_picks > MAX_DEFORM_PICKS {
160        return Err(DeformRefusal::TooManyPicks { count: total_picks, limit: MAX_DEFORM_PICKS });
161    }
162    // Each surface's picks: finite, inside its domain, a usable normal, no two
163    // at one parameter pair (the single-surface checks, per surface).
164    let mut first = 0;
165    for surface in surfaces {
166        let [u0, u1] = surface.surface.domain_u().map_err(DeformRefusal::InvalidSurface)?;
167        let [v0, v1] = surface.surface.domain_v().map_err(DeformRefusal::InvalidSurface)?;
168        let picks = &surface.spec.picks;
169        for (k, pick) in picks.iter().enumerate() {
170            let index = first + k;
171            if ![pick.u, pick.v, pick.target.x, pick.target.y, pick.target.z].iter().all(|c| c.is_finite()) {
172                return Err(DeformRefusal::InvalidPick { index, reason: "non-finite parameter or target".into() });
173            }
174            if pick.u < u0 || pick.u > u1 || pick.v < v0 || pick.v > v1 {
175                return Err(DeformRefusal::InvalidPick {
176                    index,
177                    reason: format!("({}, {}) outside the domain [{u0}, {u1}] x [{v0}, {v1}]", pick.u, pick.v),
178                });
179            }
180            if let Some(normal) = pick.normal {
181                let length = normal.length();
182                if !length.is_finite() || length <= f64::MIN_POSITIVE.sqrt() {
183                    return Err(DeformRefusal::InvalidPick { index, reason: "zero or non-finite normal".into() });
184                }
185            }
186            for (other, earlier) in picks[..k].iter().enumerate() {
187                if ((earlier.u - pick.u) / (u1 - u0).max(f64::MIN_POSITIVE)).abs() <= 1e-9
188                    && ((earlier.v - pick.v) / (v1 - v0).max(f64::MIN_POSITIVE)).abs() <= 1e-9
189                {
190                    return Err(DeformRefusal::DuplicatePicks { first: first + other, second: index });
191                }
192            }
193        }
194        first += picks.len();
195    }
196    let mut bases = Vec::with_capacity(count);
197    for surface in surfaces {
198        bases.push(prepare_base(surface.surface, &surface.spec)?);
199    }
200
201    // Make every tie's rows comparable: one degree along the edge, then the
202    // union of the knots, until nothing changes.
203    // Each pass can carry a knot one tie further, so a chain of n ties needs
204    // up to n passes (plus one to see nothing change); a pass bound that is
205    // not reached is a refusal, never a silent stop.
206    let passes = 2 * ties.len() + 2;
207    let mut converged = false;
208    for _ in 0..passes {
209        let mut changed = false;
210        for tie in ties {
211            let (da, db) = (along(tie.side_a), along(tie.side_b));
212            let pa = knots_of(&bases[tie.a], da).0;
213            let pb = knots_of(&bases[tie.b], db).0;
214            if pa < pb {
215                bases[tie.a] = bases[tie.a].elevate_degree(da, pb).map_err(DeformRefusal::InvalidSurface)?;
216                changed = true;
217            } else if pb < pa {
218                bases[tie.b] = bases[tie.b].elevate_degree(db, pa).map_err(DeformRefusal::InvalidSurface)?;
219                changed = true;
220            }
221            let [a0, a1] = along_domain(&bases[tie.a], tie.side_a);
222            let [b0, b1] = along_domain(&bases[tie.b], tie.side_b);
223            let reversed = tie.reversed;
224            let to_a = move |t: f64| {
225                let s = (t - b0) / (b1 - b0);
226                a0 + (a1 - a0) * if reversed { 1.0 - s } else { s }
227            };
228            let to_b = move |t: f64| {
229                let s = (t - a0) / (a1 - a0);
230                b0 + (b1 - b0) * if reversed { 1.0 - s } else { s }
231            };
232            let from_b = interior_knots(&bases[tie.b], db);
233            if tie.a != tie.b || da != db {
234                let mut target = bases[tie.a].clone();
235                changed |= merge_knots(&mut target, da, &from_b, to_a)?;
236                bases[tie.a] = target;
237                let from_a = interior_knots(&bases[tie.a], da);
238                let mut target = bases[tie.b].clone();
239                changed |= merge_knots(&mut target, db, &from_a, to_b)?;
240                bases[tie.b] = target;
241            }
242        }
243        if !changed {
244            converged = true;
245            break;
246        }
247    }
248    if !converged {
249        return Err(DeformRefusal::InvalidTie { tie: 0, reason: format!("knot merging did not settle in {passes} passes") });
250    }
251    for base in &bases {
252        let poles = base.control_points.len() * base.control_points[0].len();
253        if poles > MAX_DEFORM_POLES {
254            return Err(DeformRefusal::NetTooLarge { poles, limit: MAX_DEFORM_POLES });
255        }
256    }
257
258    // The rows must now coincide pole for pole, with proportional weights.
259    let scale = bases.iter().map(net_diagonal).fold(0.0, f64::max).max(f64::MIN_POSITIVE);
260    for (index, tie) in ties.iter().enumerate() {
261        let (na, nb) = (side_len(&bases[tie.a], tie.side_a), side_len(&bases[tie.b], tie.side_b));
262        if na != nb {
263            return Err(DeformRefusal::EdgeRowsDisagree { tie: index, gap: f64::INFINITY });
264        }
265        // The along-edge knot vectors must be one (mapped onto each other),
266        // or equal rows would still be different curves.
267        let (da, db) = (along(tie.side_a), along(tie.side_b));
268        let (ka, kb) = (interior_knots(&bases[tie.a], da), interior_knots(&bases[tie.b], db));
269        let [a0, a1] = along_domain(&bases[tie.a], tie.side_a);
270        let [b0, b1] = along_domain(&bases[tie.b], tie.side_b);
271        let mapped: Vec<f64> = {
272            let mut m: Vec<f64> = kb
273                .iter()
274                .map(|&t| {
275                    let s = (t - b0) / (b1 - b0);
276                    a0 + (a1 - a0) * if tie.reversed { 1.0 - s } else { s }
277                })
278                .collect();
279            m.sort_by(f64::total_cmp);
280            m
281        };
282        if knots_of(&bases[tie.a], da).0 != knots_of(&bases[tie.b], db).0
283            || ka.len() != mapped.len()
284            || ka.iter().zip(&mapped).any(|(x, y)| (x - y).abs() > KNOT_RELATIVE * (a1 - a0))
285        {
286            return Err(DeformRefusal::EdgeRowsDisagree { tie: index, gap: f64::INFINITY });
287        }
288        let mut gap = 0.0f64;
289        let mut ratio: Option<f64> = None;
290        for k in 0..na {
291            let kb = if tie.reversed { na - 1 - k } else { k };
292            let (ia, ja) = index_on(&bases[tie.a], tie.side_a, 0, k);
293            let (ib, jb) = index_on(&bases[tie.b], tie.side_b, 0, kb);
294            let (pa, pb) = (bases[tie.a].control_points[ia][ja], bases[tie.b].control_points[ib][jb]);
295            gap = gap.max(cartesian(pa).sub(cartesian(pb)).length());
296            let r = pb.w / pa.w;
297            match ratio {
298                None => ratio = Some(r),
299                Some(first) if (r - first).abs() <= 1e-12 * first => {}
300                Some(_) => gap = f64::INFINITY,
301            }
302        }
303        if !(gap <= 1e-12 * scale) {
304            return Err(DeformRefusal::EdgeRowsDisagree { tie: index, gap });
305        }
306    }
307
308    // Free poles of every surface: its held sides, its own `may_move`, and the
309    // corner blocks where two of its tied sides meet.
310    let mut tied_sides: Vec<Vec<DeformSide>> = vec![Vec::new(); count];
311    for tie in ties {
312        tied_sides[tie.a].push(tie.side_a);
313        tied_sides[tie.b].push(tie.side_b);
314    }
315    let mut held_corners = 0;
316    let mut free_index: Vec<Vec<Vec<usize>>> = Vec::with_capacity(count);
317    let mut free: Vec<Vec<(usize, usize)>> = Vec::with_capacity(count);
318    let mut offsets = Vec::with_capacity(count);
319    let mut total = 0usize;
320    for (s, base) in bases.iter().enumerate() {
321        let rows = base.control_points.len();
322        let columns = base.control_points[0].len();
323        let depth = |hold: EdgeHold| match hold {
324            EdgeHold::Free => 0,
325            EdgeHold::Position => 1,
326            EdgeHold::Tangent => 2,
327        };
328        let spec = &surfaces[s].spec;
329        let (i_lo, i_hi) = (depth(spec.hold[0]), rows.saturating_sub(depth(spec.hold[1])));
330        let (j_lo, j_hi) = (depth(spec.hold[2]), columns.saturating_sub(depth(spec.hold[3])));
331        let sides = &tied_sides[s];
332        let corner_u = |side: DeformSide| sides.contains(&side);
333        let mut corners: Vec<(bool, bool)> = Vec::new(); // (u at max, v at max)
334        for (us, vs, key) in [
335            (DeformSide::UMin, DeformSide::VMin, (false, false)),
336            (DeformSide::UMin, DeformSide::VMax, (false, true)),
337            (DeformSide::UMax, DeformSide::VMin, (true, false)),
338            (DeformSide::UMax, DeformSide::VMax, (true, true)),
339        ] {
340            if corner_u(us) && corner_u(vs) {
341                corners.push(key);
342                held_corners += 1;
343            }
344        }
345        let in_corner = |i: usize, j: usize| {
346            corners.iter().any(|&(umax, vmax)| {
347                let iu = if umax { i + 2 >= rows } else { i < 2 };
348                let jv = if vmax { j + 2 >= columns } else { j < 2 };
349                iu && jv
350            })
351        };
352        let (pu, pv) = (base.degree_u, base.degree_v);
353        let mut index = vec![vec![usize::MAX; columns]; rows];
354        let mut list = Vec::new();
355        for i in i_lo..i_hi.max(i_lo) {
356            for j in j_lo..j_hi.max(j_lo) {
357                if in_corner(i, j) {
358                    continue;
359                }
360                let (ku, kv) = (&base.knots_u[i..=i + pu + 1], &base.knots_v[j..=j + pv + 1]);
361                let order =
362                    |local: &[f64], end: f64, degree: usize| (degree + 1).saturating_sub(local.iter().filter(|&&k| k == end).count());
363                let support = PoleSupport {
364                    bounds: [ku[0], ku[pu + 1], kv[0], kv[pv + 1]],
365                    vanishing: [order(ku, ku[0], pu), order(ku, ku[pu + 1], pu), order(kv, kv[0], pv), order(kv, kv[pv + 1], pv)],
366                };
367                if (surfaces[s].may_move)(support) {
368                    index[i][j] = list.len();
369                    list.push((i, j));
370                }
371            }
372        }
373        offsets.push(total);
374        total += list.len();
375        free_index.push(index);
376        free.push(list);
377    }
378
379    if total > MAX_TIED_POLES {
380        return Err(DeformRefusal::NetTooLarge { poles: total, limit: MAX_TIED_POLES });
381    }
382    // Constraints: every surface's picks, then the ties.
383    let mut constraints: Vec<Constraint> = Vec::new();
384    let mut requested = 0.0f64;
385    let mut first_pick = 0;
386    for (s, base) in bases.iter().enumerate() {
387        let limit = MAX_DEFORM_DISPLACEMENT_RATIO * net_diagonal(base);
388        pick_constraints(base, &surfaces[s].spec.picks, &free_index[s], offsets[s], first_pick, limit, &mut constraints, &mut requested)?;
389        first_pick += surfaces[s].spec.picks.len();
390    }
391    let mut continuity = Vec::with_capacity(ties.len());
392    for (t, tie) in ties.iter().enumerate() {
393        let n = side_len(&bases[tie.a], tie.side_a);
394        let global = |s: usize, (i, j): (usize, usize)| {
395            let f = free_index[s][i][j];
396            (f != usize::MAX).then(|| offsets[s] + f)
397        };
398        // G0 rows.
399        for k in 0..n {
400            let kb = if tie.reversed { n - 1 - k } else { k };
401            let a0 = global(tie.a, index_on(&bases[tie.a], tie.side_a, 0, k));
402            let b0 = global(tie.b, index_on(&bases[tie.b], tie.side_b, 0, kb));
403            for axis in 0..3 {
404                let mut terms = Vec::new();
405                if let Some(g) = a0 {
406                    terms.push((3 * g + axis, 1.0));
407                }
408                if let Some(g) = b0 {
409                    terms.push((3 * g + axis, -1.0));
410                }
411                push_tie(&mut constraints, t, terms, 0.0)?;
412            }
413        }
414        // Smooth in the base? Read the two carriers' normals along the edge.
415        let smooth = edge_is_smooth(&bases[tie.a], tie.side_a, &bases[tie.b], tie.side_b, tie.reversed)?;
416        if !smooth {
417            continuity.push(TieContinuity::Sharp);
418            continue;
419        }
420        // The cross pairs: collinear with ONE ratio, on polynomial rows.
421        let mut ratio: Option<f64> = None;
422        for k in 0..n {
423            let kb = if tie.reversed { n - 1 - k } else { k };
424            let pole = |s: usize, side: DeformSide, depth: usize, k: usize| {
425                let (i, j) = index_on(&bases[s], side, depth, k);
426                bases[s].control_points[i][j]
427            };
428            let (p0, p1a, p1b) = (pole(tie.a, tie.side_a, 0, k), pole(tie.a, tie.side_a, 1, k), pole(tie.b, tie.side_b, 1, kb));
429            if [p0.w, p1a.w, p1b.w].iter().any(|&w| w != 1.0) {
430                return Err(DeformRefusal::EdgeNotUniformlyTangent { tie: t, reason: "rational rows".into() });
431            }
432            let (c_a, c_b) = (cartesian(p0).sub(cartesian(p1a)), cartesian(p1b).sub(cartesian(p0)));
433            let (la, lb) = (c_a.length(), c_b.length());
434            if la <= 1e-12 * scale || lb <= 1e-12 * scale {
435                return Err(DeformRefusal::EdgeNotUniformlyTangent { tie: t, reason: format!("a collapsed cross pair at {k}") });
436            }
437            if c_a.cross(c_b).length() > 1e-9 * la * lb || c_a.dot(c_b) <= 0.0 {
438                return Err(DeformRefusal::EdgeNotUniformlyTangent { tie: t, reason: format!("cross pair {k} not collinear") });
439            }
440            let r = lb / la;
441            match ratio {
442                None => ratio = Some(r),
443                Some(first) if (r - first).abs() <= 1e-9 * first => {}
444                Some(first) => {
445                    return Err(DeformRefusal::EdgeNotUniformlyTangent {
446                        tie: t,
447                        reason: format!("cross ratio {r} at {k}, {first} at 0"),
448                    })
449                }
450            }
451        }
452        let lambda = ratio.unwrap_or(1.0);
453        for k in 0..n {
454            let kb = if tie.reversed { n - 1 - k } else { k };
455            let d0 = global(tie.a, index_on(&bases[tie.a], tie.side_a, 0, k));
456            let d1a = global(tie.a, index_on(&bases[tie.a], tie.side_a, 1, k));
457            let d1b = global(tie.b, index_on(&bases[tie.b], tie.side_b, 1, kb));
458            for axis in 0..3 {
459                let mut terms = Vec::new();
460                for (g, c) in [(d1b, 1.0), (d0, -(1.0 + lambda)), (d1a, lambda)] {
461                    if let Some(g) = g {
462                        terms.push((3 * g + axis, c));
463                    }
464                }
465                push_tie(&mut constraints, t, terms, 0.0)?;
466            }
467        }
468        continuity.push(TieContinuity::Tangent { ratio: lambda });
469    }
470
471    if constraints.len() > MAX_TIED_ROWS {
472        return Err(DeformRefusal::TooManyConstraints { rows: constraints.len(), limit: MAX_TIED_ROWS });
473    }
474    // One solve over every surface.
475    let changing = constraints.iter().any(|c| c.rhs != 0.0);
476    let mut energies = Vec::with_capacity(count);
477    for s in 0..count {
478        energies.push(BandedEnergy::build(&bases[s], &free[s], &free_index[s])?);
479    }
480    let (displacements, condition) = if changing {
481        let blocks: Vec<(&BandedEnergy, usize)> = energies.iter().zip(&offsets).map(|(e, &o)| (e, o)).collect();
482        solve_blocks(&blocks, total, &constraints)?
483    } else {
484        (vec![0.0; 3 * total], 1.0)
485    };
486
487    // The deformed nets.
488    let mut nets: Vec<Vec<Vec<Vec4>>> = Vec::with_capacity(count);
489    let mut max_pole_shift = 0.0f64;
490    let mut shifts = vec![0.0f64; count];
491    for (s, base) in bases.iter().enumerate() {
492        let mut net = base.control_points.clone();
493        for (f, &(i, j)) in free[s].iter().enumerate() {
494            let g = offsets[s] + f;
495            let d = Vec3::new(displacements[3 * g], displacements[3 * g + 1], displacements[3 * g + 2]);
496            if d.x == 0.0 && d.y == 0.0 && d.z == 0.0 {
497                continue;
498            }
499            let pole = net[i][j];
500            net[i][j] = Vec4 { x: pole.x + d.x * pole.w, y: pole.y + d.y * pole.w, z: pole.z + d.z * pole.w, w: pole.w };
501            shifts[s] = shifts[s].max(d.length());
502        }
503        max_pole_shift = max_pole_shift.max(shifts[s]);
504        nets.push(net);
505    }
506    // G0 exactly: the tie rows hold to the solve's precision (~1e-10); where
507    // either pole of a tied pair could move, b's pole is made a's (scaled by
508    // the pair's constant weight ratio), so the shared edge is one curve bit
509    // for bit. A pair held on both sides is left as it was.
510    for tie in ties {
511        let n = side_len(&bases[tie.a], tie.side_a);
512        for k in 0..n {
513            let kb = if tie.reversed { n - 1 - k } else { k };
514            let (ia, ja) = index_on(&bases[tie.a], tie.side_a, 0, k);
515            let (ib, jb) = index_on(&bases[tie.b], tie.side_b, 0, kb);
516            if free_index[tie.a][ia][ja] == usize::MAX && free_index[tie.b][ib][jb] == usize::MAX {
517                continue;
518            }
519            let pa = nets[tie.a][ia][ja];
520            let w = nets[tie.b][ib][jb].w;
521            let ratio = w / pa.w;
522            nets[tie.b][ib][jb] = Vec4 { x: pa.x * ratio, y: pa.y * ratio, z: pa.z * ratio, w };
523        }
524    }
525    // G1 exactly, likewise: on a tangent tie the inner pole of b is made
526    // P0 + λ (P0 − P1a) from the deformed a side (polynomial rows, checked
527    // above), wherever it could move. The rows hold that to ~1e-10 already;
528    // this makes the cross pairs collinear to round-off.
529    for (t, tie) in ties.iter().enumerate() {
530        let TieContinuity::Tangent { ratio: lambda } = continuity[t] else { continue };
531        let n = side_len(&bases[tie.a], tie.side_a);
532        for k in 0..n {
533            let kb = if tie.reversed { n - 1 - k } else { k };
534            let (i0, j0) = index_on(&bases[tie.a], tie.side_a, 0, k);
535            let (i1, j1) = index_on(&bases[tie.a], tie.side_a, 1, k);
536            let (ib, jb) = index_on(&bases[tie.b], tie.side_b, 1, kb);
537            if free_index[tie.b][ib][jb] == usize::MAX {
538                continue;
539            }
540            let (p0, p1a) = (cartesian(nets[tie.a][i0][j0]), cartesian(nets[tie.a][i1][j1]));
541            let p1b = p0.add(p0.sub(p1a).scale(lambda));
542            nets[tie.b][ib][jb] = Vec4 { x: p1b.x, y: p1b.y, z: p1b.z, w: 1.0 };
543        }
544    }
545    let mut deformed = Vec::with_capacity(count);
546    for (base, net) in bases.iter().zip(nets) {
547        deformed.push(
548            NurbsSurface::new(base.degree_u, base.degree_v, base.knots_u.clone(), base.knots_v.clone(), net)
549                .map_err(DeformRefusal::InvalidSurface)?,
550        );
551    }
552    if max_pole_shift > MAX_DEFORM_AMPLIFICATION * requested {
553        return Err(DeformRefusal::Amplified {
554            ratio: max_pole_shift / requested.max(f64::MIN_POSITIVE),
555            limit: MAX_DEFORM_AMPLIFICATION,
556        });
557    }
558    for s in 0..count {
559        check_fold(&bases[s], &deformed[s])?;
560    }
561    for (t, tie) in ties.iter().enumerate() {
562        if continuity[t] == TieContinuity::Sharp {
563            check_dihedral(t, tie, &bases, &deformed)?;
564        }
565    }
566
567    let mut results = Vec::with_capacity(count);
568    let mut pick_index = 0;
569    for s in 0..count {
570        let mut max_pick_error = 0.0f64;
571        let mut max_normal_error = 0.0f64;
572        for pick in &surfaces[s].spec.picks {
573            let point = deformed[s].evaluate(pick.u, pick.v).map_err(DeformRefusal::InvalidSurface)?;
574            max_pick_error = max_pick_error.max(point.sub(pick.target).length());
575            if let Some(normal) = pick.normal {
576                let (_, su, sv) = deformed[s].deriv1(pick.u, pick.v).map_err(DeformRefusal::InvalidSurface)?;
577                let n = su.cross(sv);
578                let sine = n.cross(normal).length() / (n.length() * normal.length()).max(f64::MIN_POSITIVE);
579                max_normal_error = max_normal_error.max(sine.min(1.0).asin());
580            }
581            pick_index += 1;
582        }
583        let rows = deformed[s].control_points.len();
584        let columns = deformed[s].control_points[0].len();
585        results.push(DeformResult {
586            surface: deformed[s].clone(),
587            net: (rows, columns),
588            free_poles: free[s].len(),
589            max_pick_error,
590            max_normal_error,
591            max_pole_shift: shifts[s],
592            condition,
593        });
594    }
595    let _ = pick_index;
596    Ok(TiedResult { results, continuity, held_corners })
597}
598
599/// A tie row: dropped when no free pole reaches it (both ends held), else
600/// pushed unit-normalised and named by its tie.
601fn push_tie(constraints: &mut Vec<Constraint>, tie: usize, terms: Vec<(usize, f64)>, rhs: f64) -> Result<(), DeformRefusal> {
602    if terms.is_empty() {
603        return Ok(());
604    }
605    let norm = terms.iter().map(|(_, c)| c * c).sum::<f64>().sqrt();
606    let terms = terms.into_iter().map(|(index, c)| (index, c / norm)).collect();
607    constraints.push(Constraint { pick: usize::MAX, tie: Some(tie), terms, rhs: rhs / norm });
608    Ok(())
609}
610
611/// Stations along a tie's edge: (parameter on a's side, on b's side).
612fn edge_stations(a: &NurbsSurface, side_a: DeformSide, b: &NurbsSurface, side_b: DeformSide, reversed: bool) -> Vec<(f64, f64)> {
613    let [a0, a1] = along_domain(a, side_a);
614    let [b0, b1] = along_domain(b, side_b);
615    (1..24)
616        .map(|k| {
617            let s = k as f64 / 24.0;
618            (a0 + (a1 - a0) * s, b0 + (b1 - b0) * if reversed { 1.0 - s } else { s })
619        })
620        .collect()
621}
622
623/// The `(u, v)` of edge parameter `t` on `side`.
624fn on_side(surface: &NurbsSurface, side: DeformSide, t: f64) -> (f64, f64) {
625    let [u0, u1] = surface.domain_u().unwrap_or([0.0, 1.0]);
626    let [v0, v1] = surface.domain_v().unwrap_or([0.0, 1.0]);
627    match side {
628        DeformSide::UMin => (u0, t),
629        DeformSide::UMax => (u1, t),
630        DeformSide::VMin => (t, v0),
631        DeformSide::VMax => (t, v1),
632    }
633}
634
635/// The unit normal (`S_u × S_v`) of `surface` on `side` at edge parameter `t`.
636fn side_normal(surface: &NurbsSurface, side: DeformSide, t: f64) -> Result<Vec3, DeformRefusal> {
637    let (u, v) = on_side(surface, side, t);
638    let basis = RationalBasis::at(surface, u, v).map_err(DeformRefusal::InvalidSurface)?;
639    let n = basis.du.cross(basis.dv);
640    let length = n.length();
641    Ok(if length > 0.0 { n.scale(1.0 / length) } else { n })
642}
643
644/// Whether the base edge is smooth: the two carriers' normals parallel (either
645/// sense: the orientations of two carriers need not agree) at every station.
646fn edge_is_smooth(
647    a: &NurbsSurface,
648    side_a: DeformSide,
649    b: &NurbsSurface,
650    side_b: DeformSide,
651    reversed: bool,
652) -> Result<bool, DeformRefusal> {
653    for (ta, tb) in edge_stations(a, side_a, b, side_b, reversed) {
654        let (na, nb) = (side_normal(a, side_a, ta)?, side_normal(b, side_b, tb)?);
655        if na.cross(nb).length() > 1e-7 {
656            return Ok(false);
657        }
658    }
659    Ok(true)
660}
661
662/// The dihedral of a sharp edge keeps its sign: `(n_a × n_b) · T` (T the edge
663/// tangent along a's side) at every station, deformed against base.
664fn check_dihedral(t: usize, tie: &SurfaceTie, bases: &[NurbsSurface], deformed: &[NurbsSurface]) -> Result<(), DeformRefusal> {
665    let turn = |surfaces: &[NurbsSurface], ta: f64, tb: f64| -> Result<f64, DeformRefusal> {
666        let (a, b) = (&surfaces[tie.a], &surfaces[tie.b]);
667        let (na, nb) = (side_normal(a, tie.side_a, ta)?, side_normal(b, tie.side_b, tb)?);
668        let (u, v) = on_side(a, tie.side_a, ta);
669        let basis = RationalBasis::at(a, u, v).map_err(DeformRefusal::InvalidSurface)?;
670        let tangent = match along(tie.side_a) {
671            KnotDirection::U => basis.du,
672            KnotDirection::V => basis.dv,
673        };
674        let length = tangent.length().max(f64::MIN_POSITIVE);
675        Ok(na.cross(nb).dot(tangent.scale(1.0 / length)))
676    };
677    for (ta, tb) in edge_stations(&bases[tie.a], tie.side_a, &bases[tie.b], tie.side_b, tie.reversed) {
678        let before = turn(bases, ta, tb)?;
679        let after = turn(deformed, ta, tb)?;
680        if !(before * after > 0.0) {
681            return Err(DeformRefusal::EdgeFoldedThrough { tie: t, t: ta });
682        }
683    }
684    Ok(())
685}