smlib: Split Face and Split Body on solidcore (smlib_split_faces, smlib_split_body), routed by Op::Split
A port of the fork capi's smlib_split.cpp: faces cut where tool surfaces meet them (CreatePlanarSectionCurves for a plane reaching over the face, GlobalSurfaceIntersect otherwise, then MergeCurvesOnSurface with the tool), and a solid sliced (SM_BO_SLICE) by a one-face sheet on the tool, once turned over. A tool Surface keeps its constructor's description, from which solidcore makes its own surface as smlib_ssi.cpp makes SMLib's. Closed-form, C++ parity, hostile-argument and history tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk
This commit is contained in:
1 parent
58ed3002c4
commit
cdddae8a17
6 files changed
+787
-15
No files matched your search
@@ -32,6 +32,9 @@ mod measure_tests;
|
||||
pub(crate) mod offset;
|
||||
#[cfg(test)]
|
||||
mod offset_tests;
|
||||
pub(crate) mod split;
|
||||
#[cfg(test)]
|
||||
mod split_tests;
|
||||
pub(crate) mod sweep;
|
||||
#[cfg(test)]
|
||||
mod sweep_tests;
|
||||
|
||||
@@ -0,0 +1,424 @@
|
||||
//! Split Face and Split Body on solidcore: the C API's composition, ported from the fork's
|
||||
//! `capi/src/smlib_split.cpp` (`smlib_split_faces`, `smlib_split_body`, `cut_face`,
|
||||
//! `plane_covers`, `copy_of`) and the tool surfaces of `capi/src/smlib_ssi.cpp`
|
||||
//! (`smlib_surface_plane`, `_cylinder`, `_cone`, `_sphere`, `_torus`, `_nurbs`).
|
||||
//!
|
||||
//! As there, every operation works on copies of its body (`SmApiBrepCopy`). A face is cut where
|
||||
//! a tool meets it the way SMLib's plane cutter cuts a subset of faces: the face's surface is
|
||||
//! intersected with the tool over the face's UV domain (`CreatePlanarSectionCurves` for a plane
|
||||
//! reaching over the face, `GlobalSurfaceIntersect` otherwise) and the untrimmed curves go to
|
||||
//! `SmBrep::MergeCurvesOnSurface` with the tool as the intersecting surface. Unlike the plane
|
||||
//! cutter, a failed merge fails the call. A body is split by slicing (`SM_BO_SLICE`) copies of it
|
||||
//! with a one-face sheet on the tool surface, once with the surface turned over.
|
||||
//!
|
||||
//! A tool is a [`crate::ssi::Surface`]; solidcore's own surface is made from its description
|
||||
//! ([`Spec`]), as `smlib_ssi.cpp` makes SMLib's, over the surface's natural UV domain.
|
||||
|
||||
use std::sync::PoisonError;
|
||||
|
||||
use solidcore::EntityRef;
|
||||
use solidcore::boolean::api_brep::boolean_with_options;
|
||||
use solidcore::boolean::merge::MergeOptions;
|
||||
use solidcore::geom::a_object::BooleanOperation;
|
||||
use solidcore::geom::axis2_placement::Axis2Placement;
|
||||
use solidcore::geom::extent2d::Extent2d;
|
||||
use solidcore::geom::object::ObjectRef;
|
||||
use solidcore::geom::tol::{USE_DEFAULT, approx_tol3d};
|
||||
use solidcore::geom::vector2d::Vec2;
|
||||
use solidcore::geom::vector3d::{Point3, Vec3};
|
||||
use solidcore::kernel::Kernel;
|
||||
use solidcore::nurbs::b_spline_curve::p1::KnotType;
|
||||
use solidcore::nurbs::b_spline_surface::p1::{BSplineSurface, BSplineSurfaceForm, CanonicalSurfaceData};
|
||||
use solidcore::nurbs::math::CPoint;
|
||||
use solidcore::query::face::p1::calculate_bounding_box;
|
||||
use solidcore::surface::cone::p1::Cone;
|
||||
use solidcore::surface::plane::p1::Plane;
|
||||
use solidcore::surface::sphere::{Sphere, SphereOptions};
|
||||
use solidcore::surface::surface::Surface;
|
||||
use solidcore::surface::surface::p2::TsectCurveType;
|
||||
use solidcore::surface::torus::{Torus, TorusOptions};
|
||||
use solidcore::topology::brep::p1 as brep_p1;
|
||||
use solidcore::topology::brep::p2::is_manifold_solid;
|
||||
use solidcore::topology::brep::p3::{new_brep, with_kernel_callbacks};
|
||||
use solidcore::topology::brep::p8::create_face_from_surface;
|
||||
use solidcore::topology::brep::p10::merge_curves_on_surface_through_surface;
|
||||
use solidcore::topology::brep::planar_section::face_planar_section_curves;
|
||||
use solidcore::topology::edge::NotifyEnv;
|
||||
use solidcore::topology::face::p2 as face_p2;
|
||||
use solidcore::topology::{Brep, EdgeId, FaceId};
|
||||
|
||||
use super::blend::status;
|
||||
use super::boolean::copy_of;
|
||||
use super::sweep::build_faces;
|
||||
use super::{Body, run};
|
||||
use crate::ssi::Spec;
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// `SMLIB_SPLIT_MAX_FACES`, `SMLIB_SPLIT_MAX_TOOLS`.
|
||||
pub(crate) const MAX_FACES: usize = crate::ffi::split::MAX_FACES;
|
||||
pub(crate) const MAX_TOOLS: usize = crate::ffi::split::MAX_TOOLS;
|
||||
|
||||
/// `SM_ERR`.
|
||||
const SM_ERR: i32 = 1001;
|
||||
|
||||
/// The capi's statuses as SolidCraft errors: an operation's own result.
|
||||
type Out<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// A tool surface as solidcore holds it: the surface over its natural UV domain (`smlib_surface`'s
|
||||
/// `s` and `domain`), and for a plane its point and unit normal (`IsPlanar`).
|
||||
struct Tool {
|
||||
surface: Surface,
|
||||
domain: Extent2d,
|
||||
plane: Option<(Point3, Vec3)>,
|
||||
}
|
||||
|
||||
fn v3(p: [f64; 3]) -> Vec3 {
|
||||
Vec3::new(p[0], p[1], p[2])
|
||||
}
|
||||
|
||||
/// The runner's `unit_cross`.
|
||||
fn unit_cross(a: Vec3, b: Vec3) -> Vec3 {
|
||||
let c = a.cross(b);
|
||||
let l = c.length();
|
||||
Vec3::new(c.x / l, c.y / l, c.z / l)
|
||||
}
|
||||
|
||||
/// `[k0, k0, k1, ...]` as unique values and their multiplicities (`unique_knots`).
|
||||
fn unique_knots(k: &[f64]) -> (Vec<f64>, Vec<usize>) {
|
||||
let (mut values, mut mults): (Vec<f64>, Vec<usize>) = (Vec::new(), Vec::new());
|
||||
for &x in k {
|
||||
match (values.last(), mults.last_mut()) {
|
||||
(Some(&last), Some(m)) if last == x => *m += 1,
|
||||
_ => {
|
||||
values.push(x);
|
||||
mults.push(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
(values, mults)
|
||||
}
|
||||
|
||||
/// `clamped`: the first and the last knot each p + 1 times.
|
||||
fn clamped(k: &[f64], p: usize) -> bool {
|
||||
match (k.first(), k.get(p), k.last(), k.len().checked_sub(1 + p).and_then(|i| k.get(i))) {
|
||||
(Some(a), Some(b), Some(c), Some(d)) => a == b && c == d,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The tool's surface as `smlib_ssi.cpp`'s constructors make it, then its natural UV domain
|
||||
/// (`construct`: finite and not empty, else `SM_ERR_INVALID_INPUT`).
|
||||
fn tool(k: &Kernel, spec: &Spec) -> solidcore::Result<Out<Tool>> {
|
||||
let mut plane = None;
|
||||
let surface = match spec {
|
||||
Spec::Plane { origin, xaxis, yaxis, u, v } => {
|
||||
let dom = Extent2d::from_bounds(u[0], v[0], u[1], v[1]);
|
||||
plane = Some((v3(*origin), unit_cross(v3(*xaxis), v3(*yaxis))));
|
||||
Surface::from(Plane::new(v3(*origin), v3(*xaxis), v3(*yaxis), Vec2::new(1.0, 1.0), &dom))
|
||||
}
|
||||
Spec::Cylinder { origin, xaxis, yaxis, radius, angle_deg, height } => {
|
||||
let (x, y) = (v3(*xaxis), v3(*yaxis));
|
||||
let o = v3(*origin) + unit_cross(x, y) * height[0];
|
||||
Surface::from(Cone::new_cylinder_bounded(o, x, y, *radius, angle_deg[0], angle_deg[1], height[1] - height[0], false, false, false))
|
||||
}
|
||||
Spec::Cone { apex, xaxis, yaxis, half_angle_deg, height } => {
|
||||
let (x, y) = (v3(*xaxis), v3(*yaxis));
|
||||
let (h0, h1) = (height[0], height[1]);
|
||||
let t = half_angle_deg.to_radians().tan();
|
||||
let o = v3(*apex) + unit_cross(x, y) * h0;
|
||||
let pl = Axis2Placement::new(o, x, y);
|
||||
Surface::from(Cone::create_canonical(k, &pl, h0 * t, h1 * t, h1 - h0, false, false)?)
|
||||
}
|
||||
Spec::Sphere { center, xaxis, yaxis, radius, lon_deg, lat_deg } => {
|
||||
let anal = Extent2d::from_bounds(lon_deg[0], lat_deg[0], lon_deg[1], lat_deg[1]);
|
||||
let opts = SphereOptions { swap_uv: false, inside_out: false, circle_nurb: None };
|
||||
Surface::from(Sphere::new(k, v3(*center), v3(*xaxis), v3(*yaxis), anal, *radius, opts)?)
|
||||
}
|
||||
Spec::Torus { center, xaxis, yaxis, major_radius, minor_radius, major_deg, minor_deg } => {
|
||||
let anal = Extent2d::from_bounds(major_deg[0], minor_deg[0], major_deg[1], minor_deg[1]);
|
||||
Surface::from(Torus::new(k, v3(*center), v3(*xaxis), v3(*yaxis), anal, *major_radius, *minor_radius, TorusOptions::default())?)
|
||||
}
|
||||
Spec::Nurbs { degree, nu, nv, knots_u, knots_v, points, weights } => {
|
||||
let [p, q] = *degree;
|
||||
let w = |i: usize| weights.as_ref().and_then(|w| w.get(i).copied()).unwrap_or(1.0);
|
||||
if !clamped(knots_u, p) || !clamped(knots_v, q) {
|
||||
// SMLib's component constructor clamps the surface to its domain.
|
||||
let (ku, mu) = unique_knots(knots_u);
|
||||
let (kv, mv) = unique_knots(knots_v);
|
||||
let wts: Vec<f64> = (0..points.len()).map(w).collect();
|
||||
let pts: Vec<Point3> = points.iter().map(|p| v3(*p)).collect();
|
||||
let data = CanonicalSurfaceData {
|
||||
u_degree: p,
|
||||
v_degree: q,
|
||||
control_points: &pts,
|
||||
form: BSplineSurfaceForm::Unspecified,
|
||||
u_multiplicities: &mu,
|
||||
v_multiplicities: &mv,
|
||||
u_knots: &ku,
|
||||
v_knots: &kv,
|
||||
knot_type: KnotType::Unspecified,
|
||||
weights: Some(&wts),
|
||||
uv_domain: None,
|
||||
};
|
||||
Surface::from(BSplineSurface::create_canonical(&data)?)
|
||||
} else {
|
||||
// The runner's way: the homogeneous net filled directly.
|
||||
let mut pw = Vec::with_capacity(*nu);
|
||||
for i in 0..*nu {
|
||||
let mut row = Vec::with_capacity(*nv);
|
||||
for j in 0..*nv {
|
||||
let at = i * nv + j;
|
||||
let (Some(pt), wt) = (points.get(at), w(at)) else {
|
||||
return Ok(Err(Error::Argument));
|
||||
};
|
||||
row.push(CPoint::new(pt[0] * wt, pt[1] * wt, pt[2] * wt, wt));
|
||||
}
|
||||
pw.push(row);
|
||||
}
|
||||
let (n, m) = (nu.saturating_sub(1), nv.saturating_sub(1));
|
||||
let (r, s) = (knots_u.len().saturating_sub(1), knots_v.len().saturating_sub(1));
|
||||
Surface::from(BSplineSurface::from_data(n, m, p, q, r, s, &pw, knots_u, knots_v)?)
|
||||
}
|
||||
}
|
||||
};
|
||||
let domain = surface.natural_uv_domain_with_nurb(k)?;
|
||||
let (lo, hi) = (domain.min(), domain.max());
|
||||
if !(lo.x.is_finite() && lo.y.is_finite() && hi.x.is_finite() && hi.y.is_finite() && lo.x < hi.x && lo.y < hi.y) {
|
||||
return Ok(Err(Error::Status(1007)));
|
||||
}
|
||||
Ok(Ok(Tool { surface, domain, plane }))
|
||||
}
|
||||
|
||||
/// `plane_covers`: whether the plane `tool` reaches over all of `bx` (each corner's foot on the
|
||||
/// plane lies in the tool's parameter box): then its section with a face in the box is the
|
||||
/// infinite plane's.
|
||||
fn plane_covers(k: &Kernel, tool: &Tool, bx: &solidcore::geom::extent3d::Extent3d, tol: f64) -> bool {
|
||||
let (lo, hi) = (tool.domain.min(), tool.domain.max());
|
||||
let at = |u: f64, v: f64| tool.surface.evaluate_point(k, Vec2::new(u, v)).ok();
|
||||
let (Some(o), Some(pu), Some(pv)) = (at(lo.x, lo.y), at(hi.x, lo.y), at(lo.x, hi.y)) else {
|
||||
return false;
|
||||
};
|
||||
// The plane is affine in (u, v): P = o + (u - u0) X + (v - v0) Y.
|
||||
let x = (pu - o) / (hi.x - lo.x);
|
||||
let y = (pv - o) / (hi.y - lo.y);
|
||||
let (a, b, c) = (x.dot(x), x.dot(y), y.dot(y));
|
||||
let det = a * c - b * b;
|
||||
if !(det.abs() > 0.0) {
|
||||
return false;
|
||||
}
|
||||
let (m, mm) = (bx.min(), bx.max());
|
||||
(0..8).all(|kk| {
|
||||
let q = Vec3::new(if kk & 1 != 0 { mm.x } else { m.x }, if kk & 2 != 0 { mm.y } else { m.y }, if kk & 4 != 0 { mm.z } else { m.z });
|
||||
let r = q - o;
|
||||
let (g0, g1) = (x.dot(r), y.dot(r));
|
||||
let u = lo.x + (c * g0 - b * g1) / det;
|
||||
let v = lo.y + (a * g1 - b * g0) / det;
|
||||
let (su, sv) = (tol / a.sqrt(), tol / c.sqrt());
|
||||
u >= lo.x - su && u <= hi.x + su && v >= lo.y - sv && v <= hi.y + sv
|
||||
})
|
||||
}
|
||||
|
||||
/// The name of each edge curve a merge makes (`SmApiCut`'s).
|
||||
fn curve_ref(e: EdgeId, _type_code: i64) -> ObjectRef {
|
||||
solidcore::topology::loopuse::notify_ref(EntityRef::Edge(e))
|
||||
}
|
||||
|
||||
/// `cut_face`: cuts `face` where `tool` meets it; the faces it was split into besides itself.
|
||||
fn cut_face(k: &mut Kernel, b: &mut Brep, env: &mut NotifyEnv<'_>, face: FaceId, tool: &Tool, tol: f64) -> solidcore::Result<Out<Vec<FaceId>>> {
|
||||
let Some(surface) = face_p2::surface(b, face)? else {
|
||||
return Ok(Err(Error::Status(SM_ERR)));
|
||||
};
|
||||
let surface = surface.clone_for_evaluation()?;
|
||||
let domain = face_p2::uv_domain(b, face)?;
|
||||
let approx = approx_tol3d(k, approx_tol3d(k, tol) / 4.0);
|
||||
let bx = match calculate_bounding_box(k, &mut *b, face, false) {
|
||||
Ok(bx) => bx,
|
||||
Err(e) => return Ok(Err(status(e))),
|
||||
};
|
||||
let merge =
|
||||
|k: &mut Kernel, b: &mut Brep, env: &mut NotifyEnv<'_>, mut c3: Vec<_>, uv: Option<Vec<_>>| match merge_curves_on_surface_through_surface(
|
||||
k,
|
||||
b,
|
||||
env,
|
||||
&curve_ref,
|
||||
face,
|
||||
tol,
|
||||
&mut c3,
|
||||
uv.as_deref(),
|
||||
Some(tool.surface.clone()),
|
||||
) {
|
||||
Ok((made, _)) => Ok(Ok(made)),
|
||||
Err(e) => Ok(Err(status(e))),
|
||||
};
|
||||
// A plane reaching over the face sections it exactly (SmPlaneCutter's way); a plane strip,
|
||||
// like any other tool, is intersected over its own domain.
|
||||
if let Some((at, normal)) = tool.plane
|
||||
&& plane_covers(k, tool, &bx, tol)
|
||||
{
|
||||
// As SmPlaneCutter: a face far from the plane is not sectioned.
|
||||
if bx.distance_to_plane(at, normal).abs() > tol {
|
||||
return Ok(Ok(Vec::new()));
|
||||
}
|
||||
let section = match face_planar_section_curves(k, b, face, &surface, &domain, at, normal, Some(approx), None) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return Ok(Err(status(e))),
|
||||
};
|
||||
if section.curves_3d.is_empty() {
|
||||
return Ok(Ok(Vec::new()));
|
||||
}
|
||||
let uv = (section.uv_curves.len() == section.curves_3d.len()).then_some(section.uv_curves);
|
||||
return merge(k, b, env, section.curves_3d, uv);
|
||||
}
|
||||
let found = match surface.global_surface_intersect(k, &domain, &tool.surface, &tool.domain, [true, true], Some(approx), None) {
|
||||
Ok(f) => f,
|
||||
Err(e) => return Ok(Err(status(e))),
|
||||
};
|
||||
// A single point of contact cuts nothing.
|
||||
let (mut c3, mut uv1) = (Vec::new(), Vec::new());
|
||||
for (i, c) in found.curves_3d.into_iter().enumerate() {
|
||||
if found.curve_types.get(i) == Some(&TsectCurveType::Touching) {
|
||||
continue;
|
||||
}
|
||||
c3.push(c);
|
||||
uv1.push(found.surface1_uv_curves.get(i).cloned().flatten());
|
||||
}
|
||||
if c3.is_empty() {
|
||||
return Ok(Ok(Vec::new()));
|
||||
}
|
||||
let all_uv = uv1.iter().all(Option::is_some);
|
||||
merge(k, b, env, c3, all_uv.then_some(uv1))
|
||||
}
|
||||
|
||||
/// `smlib_split_faces`: a copy of `body` with faces `faces` (indices in its face order, distinct)
|
||||
/// cut where each tool meets them, the tools in turn, each cutting the pieces the earlier ones
|
||||
/// left; and for each face how many faces it became besides itself. `None` when no face is split
|
||||
/// (`SMLIB_ERR_NO_CUT`).
|
||||
pub(crate) fn split_faces(body: &Body, faces: &[usize], tools: &[&Spec]) -> Result<Option<(Body, Vec<usize>)>> {
|
||||
if faces.is_empty() || faces.len() > MAX_FACES || tools.is_empty() || tools.len() > MAX_TOOLS {
|
||||
return Err(Error::Argument);
|
||||
}
|
||||
if body.0.is_poisoned() {
|
||||
return Err(Error::Internal("smlib_split_faces: the body was left unfinished by an earlier panic".to_owned()));
|
||||
}
|
||||
let r = run("smlib_split_faces", |k| {
|
||||
let mut a = {
|
||||
let g = body.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let count = brep_p1::faces(&g, None)?.len();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
if faces.iter().any(|&f| f >= count || !seen.insert(f)) {
|
||||
return Ok(Err(Error::Argument));
|
||||
}
|
||||
copy_of(k, &g, 1)?
|
||||
};
|
||||
let all = brep_p1::faces(&a, None)?;
|
||||
// Each chosen face and, as tools cut it, its pieces.
|
||||
let mut pieces: Vec<Vec<FaceId>> = Vec::with_capacity(faces.len());
|
||||
for &f in faces {
|
||||
let Some(&face) = all.get(f) else { return Ok(Err(Error::Status(SM_ERR))) };
|
||||
pieces.push(vec![face]);
|
||||
}
|
||||
let mut made = vec![0usize; faces.len()];
|
||||
let mut built = Vec::with_capacity(tools.len());
|
||||
for spec in tools {
|
||||
match tool(k, spec)? {
|
||||
Ok(t) => built.push(t),
|
||||
Err(e) => return Ok(Err(e)),
|
||||
}
|
||||
}
|
||||
let editing = a.editing_enabled();
|
||||
let doing = k.context.doing_boolean();
|
||||
a.set_editing_enabled(true);
|
||||
k.context.set_doing_boolean(true);
|
||||
let tol = a.tolerance();
|
||||
// The edits notify through the kernel's callbacks with the body's own attributes, so
|
||||
// the history tags follow each cut (as SMLib's objects notify their attributes).
|
||||
let cut = with_kernel_callbacks(k, &mut a, |k, a, env| {
|
||||
let mut total = 0usize;
|
||||
for t in &built {
|
||||
for (i, list) in pieces.iter_mut().enumerate() {
|
||||
let now = list.clone();
|
||||
for f in now {
|
||||
let split = match cut_face(k, a, env, f, t, tol)? {
|
||||
Ok(s) => s,
|
||||
Err(e) => return Ok(Err(e)),
|
||||
};
|
||||
if let Some(m) = made.get_mut(i) {
|
||||
*m += split.len();
|
||||
}
|
||||
total += split.len();
|
||||
list.extend(split);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Ok(total))
|
||||
});
|
||||
a.set_editing_enabled(editing);
|
||||
k.context.set_doing_boolean(doing);
|
||||
a.refresh_cached_topology();
|
||||
Ok(match cut? {
|
||||
Err(e) => Err(e),
|
||||
Ok(0) => Ok(None),
|
||||
Ok(_) => Ok(Some((a, made))),
|
||||
})
|
||||
})??;
|
||||
Ok(r.map(|(b, made)| (Body::new(b), made)))
|
||||
}
|
||||
|
||||
/// One side of `smlib_split_body`: a copy of `body` sliced by a one-face sheet on the tool's
|
||||
/// surface (turned over with `flip`: SMLib's slice reads the side from the surface, not the
|
||||
/// face's use). `None` when the side is empty.
|
||||
fn side(k: &mut Kernel, body: &Body, spec: &Spec, flip: bool) -> solidcore::Result<Out<Option<Brep>>> {
|
||||
let a = {
|
||||
let g = body.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
copy_of(k, &g, 1)?
|
||||
};
|
||||
let t = match tool(k, spec)? {
|
||||
Ok(t) => t,
|
||||
Err(e) => return Ok(Err(e)),
|
||||
};
|
||||
let mut surface = t.surface.copy(k)?;
|
||||
if flip && let Err(e) = surface.swap_uv(k) {
|
||||
return Ok(Err(status(e)));
|
||||
}
|
||||
let mut sheet = new_brep(k, USE_DEFAULT, USE_DEFAULT)?;
|
||||
sheet.set_tolerance(a.tolerance());
|
||||
let natural = surface.natural_uv_domain_with_nurb(k)?;
|
||||
if let Err(e) = build_faces(&mut sheet, |s, fenv| create_face_from_surface(k, s, Some(surface), &natural, fenv)) {
|
||||
return Ok(Err(status(e)));
|
||||
}
|
||||
sheet.refresh_cached_topology();
|
||||
let options = MergeOptions::new(false, false, false, false, false);
|
||||
let r = match boolean_with_options(k, a, sheet, BooleanOperation::Slice, options) {
|
||||
Ok(r) => r.result,
|
||||
Err(e) => return Ok(Err(status(e))),
|
||||
};
|
||||
Ok(Ok((!r.face_list().is_empty()).then_some(r)))
|
||||
}
|
||||
|
||||
/// `smlib_split_body`: the manifold solid `body` cut in two by the tool: the part behind the
|
||||
/// surface (its normal points away) and the part in front. A side left empty is `None`
|
||||
/// (`SMLIB_ERR_NO_CUT`); a body that is no manifold solid is [`Error::NotSolid`].
|
||||
pub(crate) fn split_body(body: &Body, spec: &Spec) -> Result<Option<(Body, Body)>> {
|
||||
if body.0.is_poisoned() {
|
||||
return Err(Error::Internal("smlib_split_body: the body was left unfinished by an earlier panic".to_owned()));
|
||||
}
|
||||
let r = run("smlib_split_body", |k| {
|
||||
let solid = {
|
||||
let g = body.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
is_manifold_solid(&g)?
|
||||
};
|
||||
if !solid {
|
||||
return Ok(Err(Error::NotSolid));
|
||||
}
|
||||
let back = match side(k, body, spec, true)? {
|
||||
Ok(b) => b,
|
||||
Err(e) => return Ok(Err(e)),
|
||||
};
|
||||
let front = match side(k, body, spec, false)? {
|
||||
Ok(f) => f,
|
||||
Err(e) => return Ok(Err(e)),
|
||||
};
|
||||
Ok(Ok(back.zip(front)))
|
||||
})??;
|
||||
Ok(r.map(|(b, f)| (Body::new(b), Body::new(f))))
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
//! Split Face and Split Body on solidcore, against closed forms: face, edge and vertex counts,
|
||||
//! volumes, how many faces each chosen face became, and every result exports to a record that
|
||||
//! validates. With SMLib built, the same input converted to the C++ kernel and the same tools
|
||||
//! give the same result or the same error (parity only: the expected values are the analytic
|
||||
//! ones).
|
||||
//!
|
||||
//! The body is a 10 mm cube [0, 10]^3 on solidcore; the tools are described as
|
||||
//! [`crate::ssi::Surface`] describes them.
|
||||
|
||||
use super::split::{split_body, split_faces};
|
||||
use super::{Body, area, counts, make_box, to_arrays, volume};
|
||||
use crate::Error;
|
||||
use crate::export::native;
|
||||
use crate::ssi::Spec;
|
||||
|
||||
const X: [f64; 3] = [1.0, 0.0, 0.0];
|
||||
const Y: [f64; 3] = [0.0, 1.0, 0.0];
|
||||
const Z: [f64; 3] = [0.0, 0.0, 1.0];
|
||||
|
||||
fn cube() -> Body {
|
||||
make_box([0.0; 3], [10.0; 3]).unwrap()
|
||||
}
|
||||
|
||||
/// The plane x = `at` over u (along y) and v (along z) in `[-1, 11]`: it reaches over the cube.
|
||||
fn plane_x(at: f64) -> Spec {
|
||||
Spec::Plane { origin: [at, 0.0, 0.0], xaxis: Y, yaxis: Z, u: [-1.0, 11.0], v: [-1.0, 11.0] }
|
||||
}
|
||||
|
||||
/// The cylinder of radius 3 about the vertical line through (5, 5), from z = -1 to 11.
|
||||
fn cylinder() -> Spec {
|
||||
Spec::Cylinder { origin: [5.0, 5.0, 0.0], xaxis: X, yaxis: Y, radius: 3.0, angle_deg: [0.0, 360.0], height: [-1.0, 11.0] }
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Op {
|
||||
/// Split the faces (all six when empty) by the tools.
|
||||
Faces(Vec<usize>, Vec<Spec>),
|
||||
Body(Spec),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Expect {
|
||||
/// Volume, counts, and the total of faces made.
|
||||
Split(f64, [usize; 3], usize),
|
||||
/// The two sides' volumes and counts.
|
||||
Halves(f64, [usize; 3], f64, [usize; 3]),
|
||||
NoCut,
|
||||
}
|
||||
|
||||
fn case(name: &str) -> (Op, Expect) {
|
||||
let all: Vec<usize> = (0..6).collect();
|
||||
match name {
|
||||
// Four faces cross x = 5, each cut in two; the four edges along x are cut at it.
|
||||
"split_faces_by_a_plane" => (Op::Faces(all, vec![plane_x(5.0)]), Expect::Split(1000.0, [10, 20, 12], 4)),
|
||||
// The cylinder meets the top and the bottom in a circle each: a disc and a holed face.
|
||||
"split_faces_by_a_cylinder" => (Op::Faces(all, vec![cylinder()]), Expect::Split(1000.0, [8, 14, 10], 2)),
|
||||
// Two planes in turn, the second cutting the first's pieces.
|
||||
"split_faces_by_two_planes" => (Op::Faces(all, vec![plane_x(3.0), plane_x(7.0)]), Expect::Split(1000.0, [14, 28, 16], 8)),
|
||||
"split_faces_missed_by_the_tool" => (Op::Faces(all, vec![plane_x(20.0)]), Expect::NoCut),
|
||||
"split_body_by_a_plane" => (Op::Body(plane_x(3.0)), Expect::Halves(300.0, [6, 12, 8], 700.0, [6, 12, 8])),
|
||||
// A tool that misses leaves both parts the whole body.
|
||||
"split_body_missed_by_the_tool" => (Op::Body(plane_x(20.0)), Expect::Halves(1000.0, [6, 12, 8], 1000.0, [6, 12, 8])),
|
||||
_ => panic!("no case {name}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum Measured {
|
||||
Split { volume: f64, counts: [usize; 3], made: Vec<usize> },
|
||||
Halves { volumes: [f64; 2], counts: [[usize; 3]; 2] },
|
||||
NoCut,
|
||||
}
|
||||
|
||||
type Got = std::result::Result<Measured, Error>;
|
||||
|
||||
fn rel(a: f64, b: f64) -> f64 {
|
||||
(a - b).abs() / b.abs()
|
||||
}
|
||||
|
||||
fn valid(name: &str, b: &Body) {
|
||||
let (rec, _) = native(&to_arrays(b).unwrap()).unwrap_or_else(|e| panic!("{name}: record: {e:?}"));
|
||||
rec.validate().unwrap_or_else(|e| panic!("{name}: record: {e}"));
|
||||
}
|
||||
|
||||
fn judge(name: &str, who: &str, got: Got) -> Got {
|
||||
let (_, expect) = case(name);
|
||||
match (&expect, &got) {
|
||||
(_, Err(g)) => panic!("{name}: {who} failed: {g}"),
|
||||
(Expect::NoCut, Ok(m)) => assert_eq!(*m, Measured::NoCut, "{name}: {who}"),
|
||||
(Expect::Split(v, n, total), Ok(Measured::Split { volume, counts, made })) => {
|
||||
assert!(rel(*volume, *v) < 1e-9, "{name}: {who} volume {volume} vs analytic {v}");
|
||||
assert_eq!(counts, n, "{name}: {who} counts");
|
||||
assert_eq!(made.iter().sum::<usize>(), *total, "{name}: {who} faces made {made:?}");
|
||||
}
|
||||
(Expect::Halves(v0, n0, v1, n1), Ok(Measured::Halves { volumes, counts })) => {
|
||||
assert!(rel(volumes[0], *v0) < 1e-9 && rel(volumes[1], *v1) < 1e-9, "{name}: {who} volumes {volumes:?} vs {v0} {v1}");
|
||||
assert_eq!(counts, &[*n0, *n1], "{name}: {who} counts");
|
||||
}
|
||||
(e, Ok(m)) => panic!("{name}: {who} gave {m:?}, expected {e:?}"),
|
||||
}
|
||||
got
|
||||
}
|
||||
|
||||
fn solidcore_case(name: &str) -> Got {
|
||||
let (op, _) = case(name);
|
||||
let got = match &op {
|
||||
Op::Faces(faces, tools) => {
|
||||
let tools: Vec<&Spec> = tools.iter().collect();
|
||||
split_faces(&cube(), faces, &tools).map(|r| match r {
|
||||
None => Measured::NoCut,
|
||||
Some((b, made)) => {
|
||||
valid(name, &b);
|
||||
Measured::Split { volume: volume(&b, 1e-8).unwrap(), counts: counts(&b).unwrap(), made }
|
||||
}
|
||||
})
|
||||
}
|
||||
Op::Body(tool) => split_body(&cube(), tool).map(|r| match r {
|
||||
None => Measured::NoCut,
|
||||
Some((b, f)) => {
|
||||
valid(name, &b);
|
||||
valid(name, &f);
|
||||
Measured::Halves {
|
||||
volumes: [volume(&b, 1e-8).unwrap(), volume(&f, 1e-8).unwrap()],
|
||||
counts: [counts(&b).unwrap(), counts(&f).unwrap()],
|
||||
}
|
||||
}
|
||||
}),
|
||||
};
|
||||
judge(name, "solidcore", got)
|
||||
}
|
||||
|
||||
/// The C++ kernel's surface for `spec`.
|
||||
#[cfg(feature = "native")]
|
||||
fn surface(spec: &Spec) -> crate::ssi::Surface {
|
||||
use crate::ssi::Surface;
|
||||
match spec {
|
||||
Spec::Plane { origin, xaxis, yaxis, u, v } => Surface::plane(*origin, *xaxis, *yaxis, *u, *v),
|
||||
Spec::Cylinder { origin, xaxis, yaxis, radius, angle_deg, height } => {
|
||||
Surface::cylinder(*origin, *xaxis, *yaxis, *radius, *angle_deg, *height)
|
||||
}
|
||||
_ => panic!("no such tool in these cases"),
|
||||
}
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The case on the C++ kernel, called directly (whatever the routing), on the cube converted
|
||||
/// from solidcore's.
|
||||
#[cfg(feature = "native")]
|
||||
fn cpp_case(name: &str) -> Got {
|
||||
use crate::{Brep, error, ffi};
|
||||
crate::init().unwrap();
|
||||
let (op, _) = case(name);
|
||||
let body = Brep::made_core(cube());
|
||||
let measure = |h: &ffi::Handle| {
|
||||
let (rec, _) = native(&Brep::made(ffi::copy(h).unwrap()).cpp_arrays().unwrap()).unwrap();
|
||||
rec.validate().unwrap();
|
||||
(ffi::volume(h, 1e-8).unwrap(), ffi::counts(h).unwrap().map(|x| usize::try_from(x).unwrap()))
|
||||
};
|
||||
let got = match &op {
|
||||
Op::Faces(faces, tools) => {
|
||||
let made: Vec<crate::ssi::Surface> = tools.iter().map(surface).collect();
|
||||
let handles: Vec<&ffi::ssi::SurfaceHandle> = made.iter().map(|s| s.handle()).collect();
|
||||
let faces: Vec<i64> = faces.iter().map(|&f| f as i64).collect();
|
||||
match ffi::split::split_faces(body.cpp().unwrap(), &faces, &handles) {
|
||||
Ok((h, made)) => {
|
||||
let (volume, counts) = measure(&h);
|
||||
Ok(Measured::Split { volume, counts, made: made.into_iter().map(|m| usize::try_from(m).unwrap()).collect() })
|
||||
}
|
||||
Err(ffi::ops::ERR_NO_CUT) => Ok(Measured::NoCut),
|
||||
Err(s) => Err(error(s)),
|
||||
}
|
||||
}
|
||||
Op::Body(tool) => match ffi::split::split_body(body.cpp().unwrap(), surface(tool).handle()) {
|
||||
Ok((b, f)) => {
|
||||
let (vb, nb) = measure(&b);
|
||||
let (vf, nf) = measure(&f);
|
||||
Ok(Measured::Halves { volumes: [vb, vf], counts: [nb, nf] })
|
||||
}
|
||||
Err(ffi::ops::ERR_NO_CUT) => Ok(Measured::NoCut),
|
||||
Err(s) => Err(error(s)),
|
||||
},
|
||||
};
|
||||
judge(name, "C++", got)
|
||||
}
|
||||
|
||||
#[cfg(feature = "native")]
|
||||
fn parity(name: &str) {
|
||||
match (solidcore_case(name), cpp_case(name)) {
|
||||
(Ok(Measured::Split { volume: a, counts: na, made: ma }), Ok(Measured::Split { volume: b, counts: nb, made: mb })) => {
|
||||
assert!(rel(a, b) < 1e-9, "{name}: solidcore {a} vs C++ {b}");
|
||||
assert_eq!(na, nb, "{name}: counts (solidcore vs C++)");
|
||||
assert_eq!(ma, mb, "{name}: faces made per face (solidcore vs C++)");
|
||||
}
|
||||
(Ok(Measured::Halves { volumes: a, counts: na }), Ok(Measured::Halves { volumes: b, counts: nb })) => {
|
||||
assert!(rel(a[0], b[0]) < 1e-9 && rel(a[1], b[1]) < 1e-9, "{name}: solidcore {a:?} vs C++ {b:?}");
|
||||
assert_eq!(na, nb, "{name}: counts (solidcore vs C++)");
|
||||
}
|
||||
(a, b) => assert_eq!(a, b, "{name}: solidcore vs C++"),
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! cases {
|
||||
($($m:ident $(: $ign:meta)?),* $(,)?) => {$(
|
||||
mod $m {
|
||||
#[test]
|
||||
$(#[$ign])?
|
||||
fn solidcore_matches_the_closed_form() {
|
||||
let _ = super::solidcore_case(stringify!($m));
|
||||
}
|
||||
#[cfg(feature = "native")]
|
||||
#[test]
|
||||
$(#[$ign])?
|
||||
fn solidcore_matches_the_cpp_kernel() {
|
||||
super::parity(stringify!($m));
|
||||
}
|
||||
#[cfg(feature = "native")]
|
||||
#[test]
|
||||
fn the_cpp_kernel_matches_the_closed_form() {
|
||||
let _ = super::cpp_case(stringify!($m));
|
||||
}
|
||||
}
|
||||
)*};
|
||||
}
|
||||
|
||||
cases!(
|
||||
split_faces_by_a_plane,
|
||||
split_faces_by_a_cylinder,
|
||||
split_faces_by_two_planes,
|
||||
split_faces_missed_by_the_tool,
|
||||
split_body_by_a_plane,
|
||||
split_body_missed_by_the_tool,
|
||||
);
|
||||
|
||||
/// The capi's argument checks, before any kernel call.
|
||||
#[test]
|
||||
fn hostile_arguments_are_refused() {
|
||||
let b = cube();
|
||||
let p = plane_x(5.0);
|
||||
assert_eq!(split_faces(&b, &[], &[&p]).err(), Some(Error::Argument), "no face");
|
||||
assert_eq!(split_faces(&b, &[0], &[]).err(), Some(Error::Argument), "no tool");
|
||||
assert_eq!(split_faces(&b, &[0, 0], &[&p]).err(), Some(Error::Argument), "a face twice");
|
||||
assert_eq!(split_faces(&b, &[6], &[&p]).err(), Some(Error::Argument), "no face 6");
|
||||
assert_eq!(split_faces(&b, &[usize::MAX], &[&p]).err(), Some(Error::Argument), "no face usize::MAX");
|
||||
let many = vec![&p; super::split::MAX_TOOLS + 1];
|
||||
assert_eq!(split_faces(&b, &[0], &many).err(), Some(Error::Argument), "too many tools");
|
||||
let faces: Vec<usize> = (0..=super::split::MAX_FACES).collect();
|
||||
assert_eq!(split_faces(&b, &faces, &[&p]).err(), Some(Error::Argument), "too many faces");
|
||||
}
|
||||
|
||||
/// A sheet is no solid to split in two (`SMLIB_ERR_NOT_SOLID`).
|
||||
#[test]
|
||||
fn a_sheet_is_not_split_into_two_bodies() {
|
||||
use solidcore::curve::curve::Curve;
|
||||
use solidcore::geom::vector3d::Vec3;
|
||||
use solidcore::primitive::api_curves::create_line_segment;
|
||||
use solidcore::sweep::api_brep::create_linear_sweep;
|
||||
let sheet = super::run("sheet", |k| {
|
||||
let c = Curve::from(create_line_segment(Vec3::new(0.0, 0.0, 0.0), Vec3::new(10.0, 0.0, 0.0))?);
|
||||
create_linear_sweep(k, &[Some(&c)], Vec3::new(0.0, 1.0, 0.0), 10.0, false)
|
||||
})
|
||||
.map(Body::new)
|
||||
.unwrap();
|
||||
assert!(rel(area(&sheet, 1e-8).unwrap(), 100.0) < 1e-9);
|
||||
assert_eq!(split_body(&sheet, &plane_x(5.0)).err(), Some(Error::NotSolid));
|
||||
}
|
||||
|
||||
/// The body split is never changed.
|
||||
#[test]
|
||||
fn the_body_stays_as_it_was() {
|
||||
let b = cube();
|
||||
let _ = split_faces(&b, &[0, 1, 2, 3, 4, 5], &[&plane_x(5.0)]).unwrap();
|
||||
let _ = split_body(&b, &plane_x(5.0)).unwrap();
|
||||
assert_eq!(counts(&b).unwrap(), [6, 12, 8]);
|
||||
assert!(rel(volume(&b, 1e-8).unwrap(), 1000.0) < 1e-12);
|
||||
}
|
||||
|
||||
/// Face and edge tags (`Brep::tagged`) through a face split routed to solidcore, as on C++.
|
||||
#[cfg(feature = "native")]
|
||||
mod history {
|
||||
use crate::{Brep, ffi};
|
||||
|
||||
#[test]
|
||||
fn tags_cross_a_face_split() {
|
||||
crate::init().unwrap();
|
||||
let a = Brep::made_core(super::cube()).tagged(0).unwrap();
|
||||
let p = super::plane_x(5.0);
|
||||
let s = super::surface(&p);
|
||||
let faces = [0i64, 1, 2, 3, 4, 5];
|
||||
let cpp = Brep::made(ffi::split::split_faces(a.cpp().unwrap(), &faces, &[s.handle()]).unwrap().0).history().unwrap();
|
||||
let core = super::split_faces(a.core().unwrap(), &[0, 1, 2, 3, 4, 5], &[&p]).unwrap().unwrap().0;
|
||||
let core = Brep::made_core(core).history().unwrap();
|
||||
assert_eq!(core.canonical(), cpp.canonical());
|
||||
}
|
||||
}
|
||||
@@ -939,7 +939,7 @@ pub(crate) fn loft(sections: &[Vec<Profile>], degree: u32, cap: bool) -> Result<
|
||||
}
|
||||
|
||||
/// Each face's identity, for the face builders: their arena identity.
|
||||
fn build_faces<T>(b: &mut Brep, f: impl FnOnce(&mut Brep, &mut FaceBuildEnv<'_, '_>) -> T) -> T {
|
||||
pub(super) fn build_faces<T>(b: &mut Brep, f: impl FnOnce(&mut Brep, &mut FaceBuildEnv<'_, '_>) -> T) -> T {
|
||||
let mut state = ArenaNotifyState::new(b);
|
||||
let mut env = state.env(None);
|
||||
let key_of = env.key_of;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! taken over its whole domain.
|
||||
|
||||
use crate::ssi::Surface;
|
||||
use crate::{Brep, Error, Result, error, ffi, init};
|
||||
use crate::{Brep, Error, Result, core, error, ffi, init, route};
|
||||
|
||||
impl Brep {
|
||||
/// `self` with faces `faces` (indices in SMLib's face order, distinct) cut where each of
|
||||
@@ -11,10 +11,14 @@ impl Brep {
|
||||
/// for each face how many faces it became besides itself (0: no tool split it). `None` when
|
||||
/// no face is split. Tagged operands ([`Brep::tagged`]) give the pieces' history.
|
||||
pub fn split_faces(&self, faces: &[usize], tools: &[&Surface]) -> Result<Option<(Brep, Vec<usize>)>> {
|
||||
init()?;
|
||||
if faces.is_empty() || faces.len() > ffi::split::MAX_FACES || tools.is_empty() || tools.len() > ffi::split::MAX_TOOLS {
|
||||
return Err(Error::Argument);
|
||||
}
|
||||
if route::Op::Split.backend() == route::Backend::Solidcore {
|
||||
let specs: Vec<&crate::ssi::Spec> = tools.iter().map(|t| t.spec()).collect();
|
||||
return core::split::split_faces(self.core()?, faces, &specs).map(|r| r.map(|(b, made)| (Brep::made_core(b), made)));
|
||||
}
|
||||
init()?;
|
||||
let faces: Vec<i64> = faces.iter().map(|f| i64::try_from(*f).map_err(|_| Error::Argument)).collect::<Result<_>>()?;
|
||||
let handles: Vec<&ffi::ssi::SurfaceHandle> = tools.iter().map(|t| t.handle()).collect();
|
||||
match ffi::split::split_faces(self.cpp()?, &faces, &handles) {
|
||||
@@ -30,6 +34,9 @@ impl Brep {
|
||||
/// leaves both parts the whole body, with no face from the tool (tag `self` to tell); `None`
|
||||
/// when a side is left empty.
|
||||
pub fn split_body(&self, tool: &Surface) -> Result<Option<(Brep, Brep)>> {
|
||||
if route::Op::Split.backend() == route::Backend::Solidcore {
|
||||
return core::split::split_body(self.core()?, tool.spec()).map(|r| r.map(|(b, f)| (Brep::made_core(b), Brep::made_core(f))));
|
||||
}
|
||||
init()?;
|
||||
match ffi::split::split_body(self.cpp()?, tool.handle()) {
|
||||
Ok((b, f)) => Ok(Some((Brep::made(b), Brep::made(f)))),
|
||||
|
||||
+56
-12
@@ -10,8 +10,23 @@ use solidcraft_geom::brep as b;
|
||||
|
||||
use crate::{Error, Result, error, ffi, init};
|
||||
|
||||
/// A surface with its UV domain, owned on the C side.
|
||||
pub struct Surface(ffi::ssi::SurfaceHandle);
|
||||
/// A surface with its UV domain, owned on the C side; with the description it was made from, from
|
||||
/// which solidcore makes its own ([`crate::core::split`]).
|
||||
pub struct Surface {
|
||||
handle: ffi::ssi::SurfaceHandle,
|
||||
spec: Spec,
|
||||
}
|
||||
|
||||
/// What a [`Surface`] was made from: its constructor's arguments, which the C API has checked.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) enum Spec {
|
||||
Plane { origin: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], u: [f64; 2], v: [f64; 2] },
|
||||
Cylinder { origin: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], radius: f64, angle_deg: [f64; 2], height: [f64; 2] },
|
||||
Cone { apex: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], half_angle_deg: f64, height: [f64; 2] },
|
||||
Sphere { center: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], radius: f64, lon_deg: [f64; 2], lat_deg: [f64; 2] },
|
||||
Torus { center: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], major_radius: f64, minor_radius: f64, major_deg: [f64; 2], minor_deg: [f64; 2] },
|
||||
Nurbs { degree: [usize; 2], nu: usize, nv: usize, knots_u: Vec<f64>, knots_v: Vec<f64>, points: Vec<[f64; 3]>, weights: Option<Vec<f64>> },
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Surface {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
@@ -25,33 +40,47 @@ fn int(n: usize) -> Result<i32> {
|
||||
|
||||
impl Surface {
|
||||
pub(crate) fn handle(&self) -> &ffi::ssi::SurfaceHandle {
|
||||
&self.0
|
||||
&self.handle
|
||||
}
|
||||
|
||||
pub(crate) fn spec(&self) -> &Spec {
|
||||
&self.spec
|
||||
}
|
||||
|
||||
fn made(handle: ffi::ssi::SurfaceHandle, spec: Spec) -> Surface {
|
||||
Surface { handle, spec }
|
||||
}
|
||||
|
||||
/// `origin + u*x + v*y` (x, y the axes made unit), for u in `u`, v in `v`.
|
||||
pub fn plane(origin: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], u: [f64; 2], v: [f64; 2]) -> Result<Surface> {
|
||||
init()?;
|
||||
ffi::ssi::plane(&origin, &xaxis, &yaxis, &u, &v).map(Surface).map_err(error)
|
||||
ffi::ssi::plane(&origin, &xaxis, &yaxis, &u, &v).map(|h| Surface::made(h, Spec::Plane { origin, xaxis, yaxis, u, v })).map_err(error)
|
||||
}
|
||||
|
||||
/// A cylinder of `radius` about the axis through `origin` along `xaxis × yaxis`, angle
|
||||
/// `angle_deg` from `xaxis` towards `yaxis`, for heights `height` measured from `origin`.
|
||||
pub fn cylinder(origin: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], radius: f64, angle_deg: [f64; 2], height: [f64; 2]) -> Result<Surface> {
|
||||
init()?;
|
||||
ffi::ssi::cylinder(&origin, &xaxis, &yaxis, radius, &angle_deg, &height).map(Surface).map_err(error)
|
||||
ffi::ssi::cylinder(&origin, &xaxis, &yaxis, radius, &angle_deg, &height)
|
||||
.map(|h| Surface::made(h, Spec::Cylinder { origin, xaxis, yaxis, radius, angle_deg, height }))
|
||||
.map_err(error)
|
||||
}
|
||||
|
||||
/// A full cone with its apex at `apex` along `xaxis × yaxis`, radius `h * tan(half_angle_deg)`
|
||||
/// at distance h along the axis, for h in `height` (from 0: through the apex).
|
||||
pub fn cone(apex: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], half_angle_deg: f64, height: [f64; 2]) -> Result<Surface> {
|
||||
init()?;
|
||||
ffi::ssi::cone(&apex, &xaxis, &yaxis, half_angle_deg, &height).map(Surface).map_err(error)
|
||||
ffi::ssi::cone(&apex, &xaxis, &yaxis, half_angle_deg, &height)
|
||||
.map(|h| Surface::made(h, Spec::Cone { apex, xaxis, yaxis, half_angle_deg, height }))
|
||||
.map_err(error)
|
||||
}
|
||||
|
||||
/// A sphere of `radius` at `center`, over longitudes `lon_deg` and latitudes `lat_deg`.
|
||||
pub fn sphere(center: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], radius: f64, lon_deg: [f64; 2], lat_deg: [f64; 2]) -> Result<Surface> {
|
||||
init()?;
|
||||
ffi::ssi::sphere(¢er, &xaxis, &yaxis, radius, &lon_deg, &lat_deg).map(Surface).map_err(error)
|
||||
ffi::ssi::sphere(¢er, &xaxis, &yaxis, radius, &lon_deg, &lat_deg)
|
||||
.map(|h| Surface::made(h, Spec::Sphere { center, xaxis, yaxis, radius, lon_deg, lat_deg }))
|
||||
.map_err(error)
|
||||
}
|
||||
|
||||
/// A ring torus at `center` about `xaxis × yaxis`, `major_deg` round the axis and `minor_deg`
|
||||
@@ -66,7 +95,9 @@ impl Surface {
|
||||
minor_deg: [f64; 2],
|
||||
) -> Result<Surface> {
|
||||
init()?;
|
||||
ffi::ssi::torus(¢er, &xaxis, &yaxis, major_radius, minor_radius, &major_deg, &minor_deg).map(Surface).map_err(error)
|
||||
ffi::ssi::torus(¢er, &xaxis, &yaxis, major_radius, minor_radius, &major_deg, &minor_deg)
|
||||
.map(|h| Surface::made(h, Spec::Torus { center, xaxis, yaxis, major_radius, minor_radius, major_deg, minor_deg }))
|
||||
.map_err(error)
|
||||
}
|
||||
|
||||
/// A (rational) B-spline surface: `nu × nv` control points, point (i, j) (i along u) at
|
||||
@@ -82,7 +113,20 @@ impl Surface {
|
||||
) -> Result<Surface> {
|
||||
init()?;
|
||||
let flat: Vec<f64> = points.iter().flatten().copied().collect();
|
||||
ffi::ssi::nurbs([int(degree[0])?, int(degree[1])?], int(nu)?, int(nv)?, knots_u, knots_v, &flat, weights).map(Surface).map_err(error)
|
||||
ffi::ssi::nurbs([int(degree[0])?, int(degree[1])?], int(nu)?, int(nv)?, knots_u, knots_v, &flat, weights)
|
||||
.map(|h| {
|
||||
let spec = Spec::Nurbs {
|
||||
degree,
|
||||
nu,
|
||||
nv,
|
||||
knots_u: knots_u.to_vec(),
|
||||
knots_v: knots_v.to_vec(),
|
||||
points: points.to_vec(),
|
||||
weights: weights.map(<[f64]>::to_vec),
|
||||
};
|
||||
Surface::made(h, spec)
|
||||
})
|
||||
.map_err(error)
|
||||
}
|
||||
|
||||
/// A schema 4 record surface over the parameter box `domain` (`[[u0, u1], [v0, v1]]`, the
|
||||
@@ -141,12 +185,12 @@ impl Surface {
|
||||
|
||||
/// The UV domain the intersection runs within, as `[u0, u1, v0, v1]`.
|
||||
pub fn domain(&self) -> Result<[f64; 4]> {
|
||||
ffi::ssi::domain(&self.0).map_err(error)
|
||||
ffi::ssi::domain(&self.handle).map_err(error)
|
||||
}
|
||||
|
||||
/// The surface's point at (u, v).
|
||||
pub fn evaluate(&self, u: f64, v: f64) -> Result<[f64; 3]> {
|
||||
ffi::ssi::evaluate(&self.0, u, v).map_err(error)
|
||||
ffi::ssi::evaluate(&self.handle, u, v).map_err(error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -278,7 +322,7 @@ fn uv(r: &ffi::ssi::ResultHandle, i: i32, which: i32) -> Result<Option<b::Curve2
|
||||
/// `approx_tol` (<= 0: SMLib's default, 1/1000 of the surfaces' size). An intersector failure is
|
||||
/// SMLib's status; a curve SMLib does not hold as a B-spline is [`Error::Unsupported`].
|
||||
pub fn intersect(a: &Surface, b: &Surface, method: Method, approx_tol: f64) -> Result<SsiResult> {
|
||||
let r = ffi::ssi::ssi(&a.0, &b.0, method.code(), approx_tol).map_err(error)?;
|
||||
let r = ffi::ssi::ssi(&a.handle, &b.handle, method.code(), approx_tol).map_err(error)?;
|
||||
let n = ffi::ssi::curve_count(&r).map_err(error)?;
|
||||
let mut curves = Vec::new();
|
||||
for i in 0..n {
|
||||
|
||||
Reference in new issue
Block a user