diff --git a/crates/geom/src/brep/form.rs b/crates/geom/src/brep/form.rs index 2995e6267..caff2ea7b 100644 --- a/crates/geom/src/brep/form.rs +++ b/crates/geom/src/brep/form.rs @@ -195,3 +195,29 @@ pub fn on_frame(c: &Curve, [t0, t1]: [f64; 2], frame: &Frame, tol: f64) -> Optio let relabel = Frame { origin: [o.x, o.y, o.z], x_axis: [nx.x, nx.y, nx.z], y_axis: [ny.x, ny.y, ny.z] }; Some((Curve::Circle { frame: relabel, radius: *radius }, [t0 + shift, t1 + shift])) } + +/// The frame of a cylinder, cone, sphere or torus (`None` for another surface). +pub fn frame_of(s: &Surface) -> Option<&Frame> { + match s { + Surface::Cylinder { frame, .. } | Surface::Cone { frame, .. } | Surface::Sphere { frame, .. } | Surface::Torus { frame, .. } => Some(frame), + _ => None, + } +} + +/// An edge's label and NURBS form: a circle about the axis of one of `frames` (the cylinder, +/// cone, sphere and torus faces it bounds) is labelled on that frame ([`on_frame`]), so its form +/// lies on that face's quarter grid; a circle or ellipse then has its form ([`curve`]). The label +/// with its interval, and the form with its own; `None` for an arc of more than one turn. +pub fn edge<'a>( + c: &Curve, + interval: [f64; 2], + frames: impl IntoIterator, + tol: f64, +) -> Option<(Curve, [f64; 2], Option<(Curve, [f64; 2])>)> { + let (label, iv) = frames.into_iter().find_map(|f| on_frame(c, interval, f, tol)).unwrap_or_else(|| (c.clone(), interval)); + let form = match label { + Curve::Circle { .. } | Curve::Ellipse { .. } => Some(curve(&label, iv)?), + _ => None, + }; + Some((label, iv, form)) +} diff --git a/crates/kernel/src/sew.rs b/crates/kernel/src/sew.rs index ec6903a5c..f4e62e469 100644 --- a/crates/kernel/src/sew.rs +++ b/crates/kernel/src/sew.rs @@ -359,6 +359,216 @@ fn chain(e: &EdgeSpec, a: Vec3, b: Vec3) -> Result<(Vec, Vec<[f64; 3]>)> { Ok((knots, pts)) } +/// Most Hermite pieces of a folded pcurve. +const FOLD_PIECES: usize = 1024; +/// How close, against the edge's size, a folded pcurve lifts onto its edge: as close as the +/// folded edge's own chain is to the fold (sheet metal's `BEND_CHAIN_TOL`). +const FOLD_TOL: f64 = 1e-7; + +/// The point and first three derivatives at `t` of a B-spline or NURBS curve (homogeneous +/// `[x·w, y·w, z·w, w]` points; weight 1 for a B-spline): the homogeneous derivatives `A⁽ᵏ⁾`, +/// `w⁽ᵏ⁾`, then `C⁽ᵏ⁾ = (A⁽ᵏ⁾ − Σⱼ₌₁ᵏ C(k, j) w⁽ʲ⁾ C⁽ᵏ⁻ʲ⁾) / w`. +fn curve_derivs(knots: &[f64], points: &[[f64; 4]], t: f64) -> Option<[Vec3; 4]> { + let degree = knots.len().checked_sub(points.len() + 1)?; + let (first, ders) = solidcraft_geom::bspline::basis_derivatives(knots, degree, points.len(), t, 3)?; + let (mut a, mut w) = ([Vec3::ZERO; 4], [0.0f64; 4]); + for (i, d) in ders.iter().enumerate() { + let h = points.get(first + i)?; + for k in 0..4 { + let n = d.get(k).copied().unwrap_or(0.0); + a[k] = a[k] + Vec3::new(h[0], h[1], h[2]) * n; + w[k] += h[3] * n; + } + } + if !(w[0].abs() > 0.0) { + return None; + } + let mut c = [Vec3::ZERO; 4]; + for k in 0..4 { + let mut num = a[k]; + for j in 1..=k { + let binom = [[1.0, 0.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0], [1.0, 2.0, 1.0, 0.0], [1.0, 3.0, 3.0, 1.0]][k][j]; + num = num - c[k - j] * (binom * w[j]); + } + c[k] = num * (1.0 / w[0]); + } + Some(c) +} + +/// A complex number as `(re, im)`. +type Cx = (f64, f64); + +fn cmul(p: Cx, q: Cx) -> Cx { + (p.0 * q.0 - p.1 * q.1, p.0 * q.1 + p.1 * q.0) +} + +fn cdiv(p: Cx, q: Cx) -> Cx { + let n = q.0 * q.0 + q.1 * q.1; + ((p.0 * q.0 + p.1 * q.1) / n, (p.1 * q.0 - p.0 * q.1) / n) +} + +/// The Bézier control points of the degree-7 Hermite piece on `[s0, s1]` with the values and +/// first three derivatives `p` at its start and `r` at its end (the k-th derivative of a Bézier of +/// degree 7 at an end is 7!/(7 − k)! times the k-th difference of the control points there, +/// scaled by `(s1 − s0)^k`). +fn hermite7(p: [[f64; 2]; 4], r: [[f64; 2]; 4], h: f64) -> [[f64; 2]; 8] { + let (k1, k2, k3) = (h / 7.0, h * h / 42.0, h * h * h / 210.0); + let at = |d: [[f64; 2]; 4], m: [f64; 4]| [0, 1].map(|i| d[0][i] * m[0] + d[1][i] * m[1] + d[2][i] * m[2] + d[3][i] * m[3]); + [ + p[0], + at(p, [1.0, k1, 0.0, 0.0]), + at(p, [1.0, 2.0 * k1, k2, 0.0]), + at(p, [1.0, 3.0 * k1, 3.0 * k2, k3]), + at(r, [1.0, -3.0 * k1, 3.0 * k2, -k3]), + at(r, [1.0, -2.0 * k1, k2, 0.0]), + at(r, [1.0, -k1, 0.0, 0.0]), + r[0], + ] +} + +/// The pcurve on a cylinder or cone face of a B-spline edge with no closed form there: a +/// flat-pattern edge folded across a bend, a helix, which no NURBS is (its 3D curve is already +/// degree-7 Hermite pieces of the fold). The same construction in (u, v): degree-7 Hermite pieces +/// on the edge's own parameter, matching the point and first three derivatives of its angle about +/// the axis (through the form's quarter parameter when `form` is given) and of its height along +/// the axis at each piece's ends. The pieces break where the angle crosses a quarter (the form's +/// parameter is only once differentiable there) and are halved until they lift onto the edge +/// within [`FOLD_TOL`]. An approximation by construction from exact derivatives, like the edge +/// itself; nothing is fitted. `None` for another face or curve, or past the piece budget. +fn folded_pcurve(label: &b::Surface, form: Option<&b::Surface>, curve: &b::Curve, [t0, t1]: [f64; 2]) -> Option { + use solidcraft_geom::bspline::{HPoint, bezier_point}; + use std::f64::consts::{FRAC_PI_2, FRAC_PI_8, TAU}; + let (b::Surface::Cylinder { frame, .. } | b::Surface::Cone { frame, .. }) = label else { return None }; + let (knots, points): (&[f64], Vec<[f64; 4]>) = match curve { + b::Curve::Spline { knots, points } => (knots, points.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect()), + b::Curve::RationalSpline { knots, homogeneous } => (knots, homogeneous.clone()), + _ => return None, + }; + let points = points.as_slice(); + let (o, x, y) = (v3(frame.origin), v3(frame.x_axis).normalized()?, v3(frame.y_axis).normalized()?); + let z = x.cross(y).normalized()?; + let on = SurfaceEval::new(form.unwrap_or(label)).ok()?; + let edge = solidcraft_geom::brep::eval::CurveEval::new(curve).ok()?; + let raw_angle = |t: f64| -> Option { + let d = curve_derivs(knots, points, t)?[0] - o; + Some(d.dot(y).atan2(d.dot(x))) + }; + let angle_near = |t: f64, near: f64| raw_angle(t).map(|a| a + ((near - a) / TAU).round() * TAU); + // The angle's branch at the start: inside the form's u range when there is one. + let mut start = raw_angle(t0)?; + if let Some(b::Surface::RationalSpline { u_knots, .. }) = form { + let (lo, hi) = (*u_knots.first()?, *u_knots.last()?); + let inside = |a: f64| (lo - 1e-9..=hi + 1e-9).contains(&solidcraft_geom::brep::form::param(a)); + start = (-2..=2).map(|k| start + f64::from(k) * TAU).find(|a| inside(*a))?; + } + // The angle along the edge, unwrapped from its start, on a grid fine against the edge's spans. + let grid = 64 * knots.len().max(1); + let ts: Vec = (0..=grid).map(|i| t0 + (t1 - t0) * i as f64 / grid as f64).collect(); + let mut angles = Vec::with_capacity(ts.len()); + let mut prev = start; + for &t in &ts { + prev = angle_near(t, prev)?; + angles.push(prev); + } + // Breaks: the ends, and on a form each crossing of a quarter, found by bisection. + let mut breaks = vec![(t0, *angles.first()?)]; + if form.is_some() { + for i in 1..ts.len() { + let (a0, a1) = (*angles.get(i - 1)?, *angles.get(i)?); + let (q0, q1) = ((a0 / FRAC_PI_2).floor(), (a1 / FRAC_PI_2).floor()); + if q0 == q1 { + continue; + } + let target = q0.max(q1) * FRAC_PI_2; + let (mut lo, mut hi) = (*ts.get(i - 1)?, *ts.get(i)?); + for _ in 0..80 { + let mid = 0.5 * (lo + hi); + if (angle_near(mid, a0)? - target).signum() == (a0 - target).signum() { + lo = mid; + } else { + hi = mid; + } + } + breaks.push((0.5 * (lo + hi), target)); + } + } + breaks.push((t1, *angles.last()?)); + // A crossing within rounding of another break (or of an end) is that break. + let close = 1e-12 * (t1 - t0).abs().max(1.0); + let mut kept: Vec<(f64, f64)> = Vec::with_capacity(breaks.len()); + for (i, b) in breaks.iter().enumerate() { + let is_end = i + 1 == breaks.len(); + match kept.last_mut() { + Some(last) if (b.0 - last.0).abs() <= close => { + if is_end { + *last = *b; + } + } + _ => kept.push(*b), + } + } + let breaks = kept; + // u and v with their first three derivatives at `t`, angle `a`, in quarter `q` of the form. + let tq = FRAC_PI_8.tan(); + let uv = |t: f64, a: f64, q: f64| -> Option<[[f64; 2]; 4]> { + let c = curve_derivs(knots, points, t)?; + let w = |d: Vec3| (d.dot(x), d.dot(y)); + let (w0, r1, r2, r3) = (w(c[0] - o), w(c[1]), w(c[2]), w(c[3])); + let (r1, r2, r3) = (cdiv(r1, w0), cdiv(r2, w0), cdiv(r3, w0)); + // θ = Im log w: (log w)' = w'/w, (log w)'' = w''/w − (w'/w)², (log w)''' = w'''/w − + // 3 w''w'/w² + 2 (w'/w)³. + let a1 = r1.1; + let a2 = r2.1 - cmul(r1, r1).1; + let a3 = r3.1 - 3.0 * cmul(r2, r1).1 + 2.0 * cmul(cmul(r1, r1), r1).1; + let h = [(c[0] - o).dot(z), c[1].dot(z), c[2].dot(z), c[3].dot(z)]; + let u = if form.is_some() { + // The quarter parameter q + ½(1 + g/tan(π/8)), g = tan(ψ/2 − π/8), and its derivatives + // in θ, through to t by the chain rule. + let g = (0.5 * (a - q * FRAC_PI_2) - FRAC_PI_8).tan(); + let g1 = 0.5 * (1.0 + g * g); + let g2 = g * g1; + let g3 = g1 * g1 + g * g2; + let (f1, f2, f3) = (g1 / (2.0 * tq), g2 / (2.0 * tq), g3 / (2.0 * tq)); + [q + 0.5 * (1.0 + g / tq), f1 * a1, f2 * a1 * a1 + f1 * a2, f3 * a1 * a1 * a1 + 3.0 * f2 * a1 * a2 + f1 * a3] + } else { + [a, a1, a2, a3] + }; + Some([0, 1, 2, 3].map(|k| [u[k], h[k]])) + }; + let size = points.iter().fold(1.0f64, |m, h| [h[0], h[1], h[2]].iter().fold(m, |m, c| m.max((c / h[3]).abs()))); + let mut pieces = 1usize; + while pieces * breaks.len() <= FOLD_PIECES { + let mut knots2 = vec![t0; 8]; + let mut ctrl: Vec<[f64; 2]> = Vec::new(); + let mut worst = 0.0f64; + for w in breaks.windows(2) { + let (&(a, aa), &(e, ea)) = (w.first()?, w.get(1)?); + let q = (0.5 * (aa + ea) / FRAC_PI_2).floor(); + let mut last = aa; + for k in 0..pieces { + let (s0, s1) = (a + (e - a) * k as f64 / pieces as f64, a + (e - a) * (k + 1) as f64 / pieces as f64); + let (b0, b1) = (last, if k + 1 == pieces { ea } else { angle_near(s1, last)? }); + last = b1; + let piece = hermite7(uv(s0, b0, q)?, uv(s1, b1, q)?, s1 - s0); + ctrl.extend_from_slice(if ctrl.is_empty() { &piece[..] } else { &piece[1..] }); + knots2.extend(std::iter::repeat_n(s1, 7)); + let h = piece.map(|c| HPoint { x: c[0], y: c[1], z: 0.0, w: 1.0 }); + for j in 1..8 { + let f = f64::from(j) / 8.0; + let q2 = bezier_point(&h, f).project()?; + worst = worst.max(on.point([q2.x, q2.y])?.dist(edge.point(s0 + (s1 - s0) * f)?)); + } + } + } + knots2.push(t1); + if worst <= FOLD_TOL * size { + return Some(Curve2::Spline { knots: knots2, points: ctrl }); + } + pieces *= 2; + } + None +} + /// The exact pcurve of an edge of a ruled face `(1 − v)·A(u) + v·B(u)` (`rows` its chains A and /// B, of `degree` on `knots`): a chain lying on A or B either way round is `(u(t), 0 or 1)` with /// `u` affine in its parameter, and a line from a corner of A to the corner of B at the same `u` @@ -1152,38 +1362,31 @@ pub(crate) fn assemble(parts: Parts, solid: bool) -> Result { } g }; - // A circle on a cylinder, cone, sphere or torus about its axis is labelled on that face's - // frame, so its form lies on the face's quarter grid and its pcurve there is a straight line. - let mut frame_of: Vec> = vec![None; edges.len()]; + // Each edge's label and NURBS form (`form::edge`): a circle about a revolved face's axis on + // that face's frame, so its form lies on the face's quarter grid; an edge the caller gave a + // pcurve for keeps the parameter that pcurve is on. + let mut frames_of: Vec> = vec![Vec::new(); edges.len()]; for f in &faces { - let (b::Surface::Cylinder { frame, .. } - | b::Surface::Cone { frame, .. } - | b::Surface::Sphere { frame, .. } - | b::Surface::Torus { frame, .. }) = &f.surface - else { - continue; - }; + let Some(frame) = b::form::frame_of(&f.surface) else { continue }; for u in f.loops.iter().flatten() { - if let Some(slot) = frame_of.get_mut(u.edge as usize).filter(|s| s.is_none()) { - *slot = Some(frame); + if let Some(slot) = frames_of.get_mut(u.edge as usize) { + slot.push(frame); } } } - let labels: Vec<(b::Curve, [f64; 2])> = edges - .iter() - .zip(&frame_of) - .map(|(e, frame)| frame.and_then(|f| b::form::on_frame(&e.curve, e.interval, f, tol)).unwrap_or_else(|| (e.curve.clone(), e.interval))) - .collect(); - let forms: Vec> = labels - .iter() - .zip(&given_on) - .map(|((curve, interval), given)| match curve { - b::Curve::Circle { .. } | b::Curve::Ellipse { .. } if !given => { - b::form::curve(curve, *interval).ok_or_else(|| fail("an arc of more than one turn".into())).map(Some) - } - _ => Ok(None), - }) - .collect::>()?; + let mut labels: Vec<(b::Curve, [f64; 2])> = Vec::with_capacity(edges.len()); + let mut forms: Vec> = Vec::with_capacity(edges.len()); + for ((e, frames), given) in edges.iter().zip(&frames_of).zip(&given_on) { + if *given { + labels.push((e.curve.clone(), e.interval)); + forms.push(None); + continue; + } + let (label, interval, form) = + b::form::edge(&e.curve, e.interval, frames.iter().copied(), tol).ok_or_else(|| fail("an arc of more than one turn".into()))?; + labels.push((label, interval)); + forms.push(form); + } // Each face on its NURBS form: a cylinder, cone, sphere or torus over the extent its label's // pcurves give, then every pcurve again on the forms, exactly. let mut pcs: Vec>> = Vec::with_capacity(nf); @@ -1191,16 +1394,29 @@ pub(crate) fn assemble(parts: Parts, solid: bool) -> Result { let mut face_forms: Vec> = Vec::with_capacity(nf); for (fi, (f, ls)) in faces.iter().zip(&loops).enumerate() { let failed = |e: pcurve::Error| KernelError::Failed(format!("sew: face {fi}: {e}")); + // Edges folded across a bend: B-spline edges with no given pcurve on a cylinder or cone. + let folded_on = |form: Option<&b::Surface>| -> Vec<(u32, Curve2)> { + ls.iter() + .flatten() + .filter(|(_, _, given)| given.is_none()) + .filter_map(|&(e, _, _)| { + let edge = edges.get(e as usize)?; + Some((e, folded_pcurve(&f.surface, form, &edge.curve, edge.interval)?)) + }) + .collect() + }; + let folded_label = folded_on(None); let form = match f.surface { b::Surface::Cylinder { .. } | b::Surface::Cone { .. } | b::Surface::Sphere { .. } | b::Surface::Torus { .. } => { - let label = pcurve::pcurves(&f.surface, &uses_of(&edges, &forms, ls, false, tol)?, tol).map_err(failed)?; + let label = pcurve::pcurves(&f.surface, &uses_of(&edges, &forms, ls, false, &folded_label, tol)?, tol).map_err(failed)?; let extent = domain_of(&f.surface, &label).ok_or_else(|| fail(format!("face {fi} has no area in its parameters")))?; Some(b::form::surface(&f.surface, extent).ok_or_else(|| fail(format!("face {fi}: more than one turn")))?.0) } _ => None, }; let on = form.as_ref().unwrap_or(&f.surface); - let pc = pcurve::pcurves(on, &uses_of(&edges, &forms, ls, true, tol)?, tol).map_err(failed)?; + let folded_form = if form.is_some() { folded_on(form.as_ref()) } else { Vec::new() }; + let pc = pcurve::pcurves(on, &uses_of(&edges, &forms, ls, true, &folded_form, tol)?, tol).map_err(failed)?; domains.push(domain_of(on, &pc).ok_or_else(|| fail(format!("face {fi} has no area in its parameters")))?); pcs.push(pc); face_forms.push(form); @@ -1353,12 +1569,14 @@ pub(crate) fn assemble(parts: Parts, solid: bool) -> Result { /// held inside the surface's natural domain (one turn where periodic). None when it has no /// width in either direction. /// A face's edge uses for `pcurve::pcurves`: on each edge's NURBS form where it has one and -/// `formed`, else on its curve as given. +/// `formed`, else on its curve as given; `folded` gives the pcurves of edges folded across the +/// face (see [`folded_pcurve`]). fn uses_of<'a>( edges: &'a [PartEdge], forms: &'a [Option<(b::Curve, [f64; 2])>], ls: &[Vec<(u32, bool, Option<&'a Curve2>)>], formed: bool, + folded: &'a [(u32, Curve2)], tol: f64, ) -> Result>>> { ls.iter() @@ -1370,6 +1588,7 @@ fn uses_of<'a>( Some((c, i)) if formed => (c, *i), _ => (&edge.curve, edge.interval), }; + let given = given.or_else(|| folded.iter().find(|(f, _)| *f == e).map(|(_, c)| c)); Ok(pcurve::EdgeUse { edge: e, curve, interval, forward, tolerance: tol, given }) }) .collect() diff --git a/crates/smlib/SMLIB_REV b/crates/smlib/SMLIB_REV index b6bd9d907..8f227365b 100644 --- a/crates/smlib/SMLIB_REV +++ b/crates/smlib/SMLIB_REV @@ -1 +1 @@ -5af70704201c2abb23e6b5fa48ef6c9eea24566c +0c5868e2ed8639cf4eae119873145755c0d1c2e9 diff --git a/crates/smlib/src/export.rs b/crates/smlib/src/export.rs index 00727fd4e..e07dbb7ad 100644 --- a/crates/smlib/src/export.rs +++ b/crates/smlib/src/export.rs @@ -409,8 +409,9 @@ fn surfaces(flat: View, n_faces: usize) -> Res Res { let eval = b::eval::CurveEval::new(form).map_err(|e| invalid(format!("circle NURBS form: {e}")))?; let [t0, t1] = range; @@ -461,7 +462,7 @@ fn curves(flat: View, n_edges: usize) -> Res<(Vec<(b::Curve, Option, [ } let (mut nurbs, mut lines, mut circles, mut ellipses) = (0usize, 0usize, 0usize, 0usize); let (mut cv, mut kn) = (0usize, 0usize); - // The next NURBS block, in edge order: a NURBS edge's curve or a circle's NURBS form. + // The next NURBS block, in edge order: a NURBS edge's curve or a circle's or ellipse's form. let mut next_nurbs = || -> Res { let n = count(at(flat.i(EDGE_NURBS_VERTEX_COUNT), nurbs, "NURBS edge")?, "NURBS edge")?; let o = count(at(flat.i(EDGE_NURBS_ORDER), nurbs, "NURBS edge")?, "NURBS edge")?; @@ -512,7 +513,13 @@ fn curves(flat: View, n_edges: usize) -> Res<(Vec<(b::Curve, Option, [ ); let radii = [at(flat.f(EDGE_ELLIPSE_X_RADIUS), ellipses, "ellipse")?, at(flat.f(EDGE_ELLIPSE_Y_RADIUS), ellipses, "ellipse")?]; ellipses += 1; - (b::Curve::Ellipse { frame: f, radii }, None, r, None) + // Like a circle: on its NURBS form, the trims on it carry over as they are. + if forms.get(e) == Some(&1) { + let form = next_nurbs()?.record(); + (b::Curve::Ellipse { frame: along(f, &form, r)?, radii }, Some(form), r, Some([1.0, 0.0])) + } else { + (b::Curve::Ellipse { frame: f, radii }, None, r, None) + } } CURVE_NURBS => { let c = next_nurbs()?; diff --git a/crates/smlib/src/import.rs b/crates/smlib/src/import.rs index 779e7c592..e95697d8d 100644 --- a/crates/smlib/src/import.rs +++ b/crates/smlib/src/import.rs @@ -221,11 +221,11 @@ fn laid_out(brep: &b::Brep, trusted: bool, analytic: bool) -> R { let any_edge_form = brep.edges.iter().any(|e| e.nurbs.is_some()); for (e, (interval, _)) in brep.edges.iter().zip(&intervals) { - // A circle on its NURBS form: what it is (its circle entry), then the NURBS it is - // parameterised on (EDGE_NURBS_FORM). Another curve on a NURBS form is written as that + // A circle or ellipse on its NURBS form: what it is (its conic entry), then the NURBS it + // is parameterised on (EDGE_NURBS_FORM). Another curve on a NURBS form is written as that // NURBS, whose parameter the edge's interval and trims are in. let form = match (&e.curve, &e.nurbs) { - (b::Curve::Circle { .. }, Some(n)) => { + (b::Curve::Circle { .. } | b::Curve::Ellipse { .. }, Some(n)) => { curve(&mut a, &e.curve)?; edge_nurbs_block(&mut a, n)?; true diff --git a/crates/step/src/topology.rs b/crates/step/src/topology.rs index 886a79801..d5d3dbe78 100644 --- a/crates/step/src/topology.rs +++ b/crates/step/src/topology.rs @@ -322,6 +322,8 @@ struct EdgeB { interval: [f64; 2], vertices: [u32; 2], tolerance: f64, + /// The curve's NURBS form and its interval there (`form::edge`), set before the pcurves. + form: Option<(BCurve, [f64; 2])>, } enum LoopB { @@ -433,7 +435,7 @@ impl<'b, 'a> Builder<'b, 'a> { self.raise_vertex(v, gap, id)?; } let i = index(self.edges.len())?; - self.edges.push(EdgeB { curve: mapped.curve, interval: mapped.interval, vertices, tolerance: self.tol }); + self.edges.push(EdgeB { curve: mapped.curve, interval: mapped.interval, vertices, tolerance: self.tol, form: None }); self.edge_ids.insert(id, (i, mapped.with_step)); Ok((i, mapped.with_step)) } @@ -667,14 +669,36 @@ impl<'b, 'a> Builder<'b, 'a> { if self.sense_mismatches > 0 { notes.push(format!("{} edges run against their same_sense (read by their vertices)", self.sense_mismatches)); } + // Each edge's label and NURBS form: a circle about a revolved face's axis labelled on that + // face's frame, so its form lies on the face's quarter grid. + let mut frames: Vec> = vec![Vec::new(); self.edges.len()]; + for f in &self.faces { + let Some(frame) = brep::form::frame_of(&f.surface) else { continue }; + for l in &f.loops { + if let LoopB::Edges(es) = l { + for (e, _) in es { + if let Some(slot) = frames.get_mut(*e as usize) { + slot.push(frame.clone()); + } + } + } + } + } + for (edge, fr) in self.edges.iter_mut().zip(&frames) { + let (label, interval, form) = + brep::form::edge(&edge.curve, edge.interval, fr, self.tol).ok_or_else(|| unsupported("an arc of more than one turn"))?; + (edge.curve, edge.interval, edge.form) = (label, interval, form); + } // Each face's pcurves; a face whose loops disagree with its same_sense is turned over. let mut pcs: Vec>> = Vec::with_capacity(self.faces.len()); + let mut face_forms: Vec> = Vec::with_capacity(self.faces.len()); let mut domains = Vec::with_capacity(self.faces.len()); let mut turned = vec![false; self.faces.len()]; let (mut failed, mut first_failure, mut loosened) = (0usize, None, 0usize); for fi in 0..self.faces.len() { match self.face_pcurves(fi) { - Ok((pc, domain, flipped, tol)) => { + Ok((pc, domain, flipped, tol, form)) => { + face_forms.push(form); if flipped && let Some(t) = turned.get_mut(fi) { *t = true; } @@ -689,6 +713,7 @@ impl<'b, 'a> Builder<'b, 'a> { first_failure.get_or_insert_with(|| format!("face #{}: {m}", self.faces.get(fi).map_or(0, |f| f.step))); pcs.push(Vec::new()); domains.push([[0.0; 2]; 2]); + face_forms.push(None); } } } @@ -841,10 +866,14 @@ impl<'b, 'a> Builder<'b, 'a> { let mut edges = Vec::with_capacity(edge_order.len()); for &e in &edge_order { let edge = self.edges.get(e as usize).ok_or("edge reference")?; + let (nurbs, interval) = match &edge.form { + Some((c, i)) => (Some(c.clone()), *i), + None => (None, edge.interval), + }; edges.push(Edge { - nurbs: None, + nurbs, curve: edge.curve.clone(), - interval: edge.interval, + interval, vertices: [vmap(edge.vertices[0])?, vmap(edge.vertices[1])?], tolerance: edge.tolerance, uses: uses.get(e as usize).cloned().unwrap_or_default(), @@ -884,7 +913,8 @@ impl<'b, 'a> Builder<'b, 'a> { } } let domain = *domains.get(f as usize).ok_or("face reference")?; - faces.push(Face { nurbs: None, surface: face.surface.clone(), domain, loops }); + let nurbs = face_forms.get(f as usize).cloned().flatten(); + faces.push(Face { nurbs, surface: face.surface.clone(), domain, loops }); } let mut out_shells = Vec::with_capacity(shells.len()); for s in &shells { @@ -927,9 +957,9 @@ impl<'b, 'a> Builder<'b, 'a> { /// marks none (or marks one that another loop encloses), and turns the face over when its /// outer loop runs clockwise about the natural normal on a surface where that cannot be a /// face's outer boundary. - fn face_pcurves(&mut self, fi: usize) -> R<(Vec>, [[f64; 2]; 2], bool, f64)> { + fn face_pcurves(&mut self, fi: usize) -> R<(Vec>, [[f64; 2]; 2], bool, f64, Option)> { let face = self.faces.get(fi).ok_or("face reference")?; - let surface = face.surface.clone(); + let label = face.surface.clone(); let edge_loops: Vec> = face .loops .iter() @@ -941,24 +971,42 @@ impl<'b, 'a> Builder<'b, 'a> { // Which loop index in `face.loops` each edge loop is. let positions: Vec = face.loops.iter().enumerate().filter(|(_, l)| matches!(l, LoopB::Edges(_))).map(|(i, _)| i).collect(); let mut tol = self.tol; - let pcs = loop { - let mut uses = Vec::with_capacity(edge_loops.len()); - for l in &edge_loops { - let mut u = Vec::with_capacity(l.len()); - for &(e, forward) in l { - let edge = self.edges.get(e as usize).ok_or("edge reference")?; - u.push(EdgeUse { edge: e, curve: &edge.curve, interval: edge.interval, forward, tolerance: 0.0, given: None }); + // The face's pcurves on `on`, each edge on its NURBS form when `formed`. + let pcurves_on = |on: &BSurface, formed: bool, tol: &mut f64| -> R>> { + loop { + let mut uses = Vec::with_capacity(edge_loops.len()); + for l in &edge_loops { + let mut u = Vec::with_capacity(l.len()); + for &(e, forward) in l { + let edge = self.edges.get(e as usize).ok_or("edge reference")?; + let (curve, interval) = match &edge.form { + Some((c, i)) if formed => (c, *i), + _ => (&edge.curve, edge.interval), + }; + u.push(EdgeUse { edge: e, curve, interval, forward, tolerance: 0.0, given: None }); + } + uses.push(u); } - uses.push(u); - } - match pcurve::pcurves(&surface, &uses, tol) { - Ok(p) => break p, - Err(pcurve::Error::Failed(m)) if !m.contains("not supported") && tol * 10.0 <= MAX_FIT_TOLERANCE * (1.0 + 1e-9) => { - tol *= 10.0; + match pcurve::pcurves(on, &uses, *tol) { + Ok(p) => return Ok(p), + Err(pcurve::Error::Failed(m)) if !m.contains("not supported") && *tol * 10.0 <= MAX_FIT_TOLERANCE * (1.0 + 1e-9) => { + *tol *= 10.0; + } + Err(e) => return Err(e.to_string()), } - Err(e) => return Err(e.to_string()), } }; + // A cylinder, cone, sphere or torus on its NURBS form, over the extent its label's pcurves + // give; then every pcurve on the forms. + let form = match brep::form::frame_of(&label) { + Some(_) => { + let extent = face_domain(&label, &pcurves_on(&label, false, &mut tol)?)?; + Some(brep::form::surface(&label, extent).ok_or_else(|| unsupported("a face of more than one turn"))?.0) + } + None => None, + }; + let surface = form.clone().unwrap_or(label); + let pcs = pcurves_on(&surface, true, &mut tol)?; if tol > self.tol { for l in &edge_loops { for &(e, _) in l { @@ -1029,7 +1077,7 @@ impl<'b, 'a> Builder<'b, 'a> { } let pcs: Vec> = if flip { pcs.into_iter().map(|l| l.into_iter().rev().collect()).collect() } else { pcs }; let domain = face_domain(&surface, &pcs)?; - Ok((pcs, domain, flip, tol)) + Ok((pcs, domain, flip, tol, form)) } } diff --git a/crates/step/src/topology/seams.rs b/crates/step/src/topology/seams.rs index 6e69f9afe..6fac3d0bd 100644 --- a/crates/step/src/topology/seams.rs +++ b/crates/step/src/topology/seams.rs @@ -311,7 +311,7 @@ impl Builder<'_, '_> { } } let i = index(self.edges.len())?; - self.edges.push(EdgeB { curve, interval, vertices, tolerance: self.tol }); + self.edges.push(EdgeB { curve, interval, vertices, tolerance: self.tol, form: None }); Ok((i, along)) } @@ -546,7 +546,7 @@ impl Builder<'_, '_> { x.interval = [lo, t]; x.vertices = [a, v]; } - self.edges.push(EdgeB { curve, interval: [t, hi], vertices: [v, b], tolerance }); + self.edges.push(EdgeB { curve, interval: [t, hi], vertices: [v, b], tolerance, form: None }); for f in &mut self.faces { for l in &mut f.loops { let LoopB::Edges(es) = l else { continue };