Wave 205/509: kernel: union_all, one SMLib union of many bodies checked once, history over every operand (and 3 more)
4 commits, squashed; the originals stay reachable from tag archive/merge-main-develop. -2ffbbc74djyviko: step: a cone within the file's uncertainty of its limit plane over the face is read as that plane -0185ccc1ejyviko: solidcraft-smlib: Brep::union_all, the union of many bodies in one SMLib call -0213c3dfajyviko: kernel: union_all, one SMLib union of many bodies checked once, history over every operand -83d965f30jyviko: doc: a join into one target and an intersection's tools are one union_all call Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ
This commit is contained in:
1 parent
0a014857ab
commit
3557e3c563
11 files changed
+185
-78
No files matched your search
+15
-34
@@ -2699,29 +2699,22 @@ fn sheet_boolean_changes(body: &Body, tools: &[Body], op: Operation) -> Result<b
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Selected profiles form one machining tool, including disconnected tool material.
|
||||
/// Balanced unions avoid repeatedly rebuilding a growing aggregate boundary.
|
||||
/// Selected profiles form one machining tool, including disconnected tool material: their
|
||||
/// union in one kernel call.
|
||||
fn intersection_tool_union(tools: Vec<Traced>) -> Result<Vec<Traced>> {
|
||||
if tools.len() > 1000 || tools.iter().fold(0usize, |n, t| n.saturating_add(t.body.face_count())) > 16_384 {
|
||||
return Err(DocError::Invalid("intersection tools exceed the bounded geometry budget".into()));
|
||||
}
|
||||
let mut groups = tools;
|
||||
while groups.len() > 1 {
|
||||
let mut next = Vec::new();
|
||||
let mut iter = groups.into_iter();
|
||||
while let Some(a) = iter.next() {
|
||||
match iter.next() {
|
||||
Some(b) => {
|
||||
let u = kernel::boolean(&a.body, &b.body, BoolOp::Union)?
|
||||
.ok_or_else(|| DocError::Invalid("intersection tool union is empty".into()))?;
|
||||
next.push(Traced::step(u, &[&a, &b]));
|
||||
}
|
||||
None => next.push(a),
|
||||
}
|
||||
}
|
||||
groups = next;
|
||||
if tools.len() < 2 {
|
||||
return Ok(tools);
|
||||
}
|
||||
Ok(groups)
|
||||
Ok(vec![union_all(&tools.iter().collect::<Vec<_>>())?])
|
||||
}
|
||||
|
||||
/// The union of `operands` (traced bodies) in one kernel call, keeping their lineage.
|
||||
fn union_all(operands: &[&Traced]) -> Result<Traced> {
|
||||
let bodies: Vec<&Body> = operands.iter().map(|t| &t.body).collect();
|
||||
Ok(Traced::step(kernel::union_all(&bodies)?, operands))
|
||||
}
|
||||
|
||||
/// After a cut handled some sheet bodies as flat machining, apply it to the other targets.
|
||||
@@ -2923,26 +2916,14 @@ fn apply_traced_with(
|
||||
Ok(Traced::step(u, &[a, b]))
|
||||
};
|
||||
// One target takes every tool, whichever it meets: the result is the union of all of
|
||||
// them, made in a balanced tree of unions so that each body is in about log2(n) of
|
||||
// them, instead of the target growing by one tool at a time and taking part, ever
|
||||
// larger, in every one (n tools cost n²).
|
||||
// them in one kernel call, checked once.
|
||||
if let [keep] = live.as_slice()
|
||||
&& tools.len() > 1
|
||||
{
|
||||
let Some(base) = state.body(keep).map(ModelBody::traced) else { return Ok(()) };
|
||||
let mut level: Vec<Traced> = std::iter::once(base).chain(tools).collect();
|
||||
while level.len() > 1 {
|
||||
let mut next = Vec::with_capacity(level.len().div_ceil(2));
|
||||
let mut it = level.into_iter();
|
||||
while let Some(a) = it.next() {
|
||||
next.push(match it.next() {
|
||||
Some(b) => union(&a, &b)?,
|
||||
None => a,
|
||||
});
|
||||
}
|
||||
level = next;
|
||||
}
|
||||
if let (Some(acc), Some(mb)) = (level.pop(), state.bodies.iter_mut().find(|b| b.name == *keep)) {
|
||||
let operands: Vec<&Traced> = std::iter::once(&base).chain(&tools).collect();
|
||||
let acc = union_all(&operands)?;
|
||||
if let Some(mb) = state.bodies.iter_mut().find(|b| b.name == *keep) {
|
||||
*mb = ModelBody::traced_new(mb.name.clone(), acc, mb.feature);
|
||||
}
|
||||
return Ok(());
|
||||
|
||||
@@ -188,7 +188,7 @@ pub use meshbody::{MAX_TRIANGLES, mesh_body};
|
||||
pub use native::{body_from_smlib, smlib_body};
|
||||
pub use native::{brep_record, decode_native_body, encode_native_body, native_preview_mesh};
|
||||
pub use offset::with_same_surface;
|
||||
pub use ops::{BoolOp, boolean, half_space, join_apart, place_matrix, split_by_plane, transform, transform_matrix, union_apart};
|
||||
pub use ops::{BoolOp, boolean, half_space, join_apart, place_matrix, split_by_plane, transform, transform_matrix, union_all, union_apart};
|
||||
pub use point_path::{
|
||||
PathPiece, PointPath, SpaceBezier, curve_path, edge_path, face_section_along, iso_curves, project_onto_face, sketch_record_curve,
|
||||
sweep_point_path_with,
|
||||
|
||||
@@ -29,16 +29,31 @@ pub fn boolean(a: &Body, b: &Body, op: BoolOp) -> Result<Option<Body>> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The union of `bodies` (at least one) in one SMLib call, each body taking part in about
|
||||
/// log2(n) of its unions, the result checked once. A result SMLib's check refuses is an error.
|
||||
///
|
||||
/// The result carries its exact history over `bodies` in order, as [`boolean`]'s does, and
|
||||
/// what the operands' faces stood for (their regularization protection and the planar roles on
|
||||
/// supports it kept).
|
||||
pub fn union_all(bodies: &[&Body]) -> Result<Body> {
|
||||
crate::profile::timed(crate::profile::Kind::Boolean, || {
|
||||
if bodies.is_empty() {
|
||||
return Err(KernelError::Invalid("a union of no bodies".into()));
|
||||
}
|
||||
guard("SMLib union", || crate::smlib_boolean::smlib_union_all(bodies))?.with_preserved_union_planar_sources(bodies)
|
||||
})
|
||||
}
|
||||
|
||||
/// A boolean's result with what its operands' faces stood for carried over: regularization
|
||||
/// protection and the planar construction and shell roles on supports it kept.
|
||||
fn with_operand_roles(a: &Body, b: &Body, op: BoolOp, r: Result<Option<Body>>) -> Result<Option<Body>> {
|
||||
let r = r.map(|result| result.map(|body| body.inherit_regularization_protection(a).inherit_regularization_protection(b)));
|
||||
match op {
|
||||
BoolOp::Cut => r.and_then(|result| result.map(|body| body.with_preserved_boolean_planar_sources(a, b, true)).transpose()),
|
||||
BoolOp::Union => r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(a, b)).transpose()),
|
||||
BoolOp::Union => r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(&[a, b])).transpose()),
|
||||
// Every face of an intersection lies on one operand's face, as a union's does: the same
|
||||
// roles carry over (#565).
|
||||
BoolOp::Intersect => r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(a, b)).transpose()),
|
||||
BoolOp::Intersect => r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(&[a, b])).transpose()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -151,15 +151,15 @@ impl Body {
|
||||
self_.map_planar_sources(&[input], None, Some(tool), &[], constructed)
|
||||
}
|
||||
|
||||
/// Retain exact construction and shell roles through a Union from both operands, only on
|
||||
/// unchanged supports. Coplanar supports of the two operands carry distinct identities, so
|
||||
/// a face merged from both stays without a role.
|
||||
pub(crate) fn with_preserved_union_planar_sources(self, a: &Body, b: &Body) -> Result<Self> {
|
||||
let self_ = self.inherit_regularization_protection(a).inherit_regularization_protection(b);
|
||||
if ![a, b].iter().any(|input| input.face_sources().is_some_and(|sources| sources.iter().flatten().any(|s| boolean_source(s, true)))) {
|
||||
/// Retain exact construction and shell roles through a Union from every operand, only on
|
||||
/// unchanged supports. Coplanar supports of different operands carry distinct identities, so
|
||||
/// a face merged from several stays without a role.
|
||||
pub(crate) fn with_preserved_union_planar_sources(self, operands: &[&Body]) -> Result<Self> {
|
||||
let self_ = operands.iter().fold(self, |body, operand| body.inherit_regularization_protection(operand));
|
||||
if !operands.iter().any(|input| input.face_sources().is_some_and(|sources| sources.iter().flatten().any(|s| boolean_source(s, true)))) {
|
||||
return Ok(self_);
|
||||
}
|
||||
self_.map_planar_sources(&[a, b], None, None, &[], true)
|
||||
self_.map_planar_sources(operands, None, None, &[], true)
|
||||
}
|
||||
|
||||
fn map_planar_sources(mut self, inputs: &[&Body], shell: Option<f64>, blocker: Option<&Body>, open: &[Vec3], constructed: bool) -> Result<Self> {
|
||||
@@ -172,7 +172,8 @@ impl Body {
|
||||
if inputs.iter().all(|input| input.face_sources().is_none()) {
|
||||
return Ok(self);
|
||||
}
|
||||
if inputs.len() > 2
|
||||
// Each body at most 16 384 faces, and the inputs together at most two such bodies' worth.
|
||||
if inputs.iter().fold(0usize, |n, input| n.saturating_add(input.face_count())) > 2 * 16_384
|
||||
|| inputs.iter().any(|input| input.face_count() > 16_384)
|
||||
|| self.face_count() > 16_384
|
||||
|| blocker.is_some_and(|b| b.face_count() > 16_384)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! ([`crate::history::History`]'s contract). A result SMLib's own check or the record's geometry
|
||||
//! check refuses is an error, never a body.
|
||||
|
||||
pub(crate) use smlib::boolean as smlib_boolean;
|
||||
pub(crate) use smlib::{boolean as smlib_boolean, union_all as smlib_union_all};
|
||||
|
||||
mod smlib {
|
||||
use solidcraft_smlib::{BooleanOp, CheckLevel};
|
||||
@@ -34,6 +34,54 @@ mod smlib {
|
||||
BoolOp::Intersect => BooleanOp::Intersect,
|
||||
};
|
||||
let Some(r) = ta.boolean(&tb, kind).map_err(|e| failed("operation", e))? else { return Ok(None) };
|
||||
checked(&r, &[&sa, &sb])?;
|
||||
let (body, or) = body_from_smlib_ordered(&r)?;
|
||||
let history = match (oa, ob, or) {
|
||||
(Some(oa), Some(ob), Some(or)) => r.history().map_err(|e| failed("history", e))?.history(&[oa, ob], &or).map(Some).unwrap_or_else(|e| {
|
||||
log::debug!(target: "smlib", "boolean history: {e}");
|
||||
None
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
Ok(Some(with_history(body, history, a, b)))
|
||||
}
|
||||
|
||||
/// The union of `bodies` in one SMLib call, each tagged as its own operand, checked once:
|
||||
/// the result's history is over `bodies` in order. At least one body.
|
||||
pub(crate) fn union_all(bodies: &[&Body]) -> Result<Body> {
|
||||
if bodies.len() > solidcraft_smlib::MAX_UNION_BREPS {
|
||||
return Err(KernelError::Invalid(format!("a union takes at most {} bodies", solidcraft_smlib::MAX_UNION_BREPS)));
|
||||
}
|
||||
let mut operands = Vec::with_capacity(bodies.len());
|
||||
let mut tagged = Vec::with_capacity(bodies.len());
|
||||
let mut orders = Some(Vec::with_capacity(bodies.len()));
|
||||
for (i, body) in bodies.iter().enumerate() {
|
||||
body.require_brep("a union")?;
|
||||
let (s, order) = smlib_body_ordered(body)?;
|
||||
tagged.push(s.tagged(i).map_err(|e| failed("tag", e))?);
|
||||
operands.push(s);
|
||||
orders = orders.zip(order).map(|(mut v, o)| {
|
||||
v.push(o);
|
||||
v
|
||||
});
|
||||
}
|
||||
let refs: Vec<&solidcraft_smlib::Brep> = tagged.iter().collect();
|
||||
let r = solidcraft_smlib::Brep::union_all(&refs).map_err(|e| failed("operation", e))?;
|
||||
let operand_refs: Vec<&solidcraft_smlib::Brep> = operands.iter().collect();
|
||||
checked(&r, &operand_refs)?;
|
||||
let (body, or) = body_from_smlib_ordered(&r)?;
|
||||
let history = match (orders, or) {
|
||||
(Some(orders), Some(or)) => r.history().map_err(|e| failed("history", e))?.history(&orders, &or).map(Some).unwrap_or_else(|e| {
|
||||
log::debug!(target: "smlib", "union history: {e}");
|
||||
None
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
Ok(body.with_checked_history(history, &record::counts(bodies)))
|
||||
}
|
||||
|
||||
/// An error unless SMLib's check accepts `r`, the result of combining `operands`.
|
||||
fn checked(r: &solidcraft_smlib::Brep, operands: &[&solidcraft_smlib::Brep]) -> Result<()> {
|
||||
// Solids touching each other along an edge or at a vertex come back as one non-manifold
|
||||
// body, which the export splits into separate solids: SMLib's check is of those, imported
|
||||
// as given (its check of the touching arrangement itself refuses the radial order of
|
||||
@@ -46,29 +94,26 @@ mod smlib {
|
||||
let split = solidcraft_smlib::Brep::from_record(&record, true).map_err(|e| failed("the separate solids", e))?;
|
||||
split.check(CheckLevel::All).map_err(|e| failed("check", e))?
|
||||
};
|
||||
if !check.is_valid() {
|
||||
// Whether an operand failed it already says whose the fault is.
|
||||
let operands: Vec<&str> = [("the first operand", &sa), ("the second operand", &sb)]
|
||||
.into_iter()
|
||||
.filter(|(_, s)| s.check(CheckLevel::All).is_ok_and(|c| !c.is_valid()))
|
||||
.map(|(name, _)| name)
|
||||
.collect();
|
||||
let what = if operands.is_empty() {
|
||||
"SMLib's check refuses the result".to_string()
|
||||
} else {
|
||||
format!("SMLib's check refuses the result ({} already fails it)", operands.join(" and "))
|
||||
};
|
||||
return Err(failed(&what, check));
|
||||
if check.is_valid() {
|
||||
return Ok(());
|
||||
}
|
||||
let (body, or) = body_from_smlib_ordered(&r)?;
|
||||
let history = match (oa, ob, or) {
|
||||
(Some(oa), Some(ob), Some(or)) => r.history().map_err(|e| failed("history", e))?.history(&[oa, ob], &or).map(Some).unwrap_or_else(|e| {
|
||||
log::debug!(target: "smlib", "boolean history: {e}");
|
||||
None
|
||||
}),
|
||||
_ => None,
|
||||
// Whether an operand failed it already says whose the fault is.
|
||||
let failing: Vec<String> = operands
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, s)| s.check(CheckLevel::All).is_ok_and(|c| !c.is_valid()))
|
||||
.map(|(i, _)| match (operands.len(), i) {
|
||||
(2, 0) => "the first operand".to_string(),
|
||||
(2, _) => "the second operand".to_string(),
|
||||
_ => format!("operand {i}"),
|
||||
})
|
||||
.collect();
|
||||
let what = if failing.is_empty() {
|
||||
"SMLib's check refuses the result".to_string()
|
||||
} else {
|
||||
format!("SMLib's check refuses the result ({} already fails it)", failing.join(" and "))
|
||||
};
|
||||
Ok(Some(with_history(body, history, a, b)))
|
||||
Err(failed(&what, check))
|
||||
}
|
||||
|
||||
/// `body` with `history` where it describes `body` made from `a` and `b`.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! The operations block of `capi/include/smlib.h` (`smlib_boolean`, `smlib_boolean2d`, `smlib_fillet`,
|
||||
//! The operations block of `capi/include/smlib.h` (`smlib_boolean`, `smlib_boolean_union_all`, `smlib_boolean2d`, `smlib_fillet`,
|
||||
//! `smlib_chamfer`, `smlib_blend`, `smlib_fillet_variable`, `smlib_chamfer_sides`, `smlib_shell`, `smlib_offset_faces`,
|
||||
//! `smlib_thicken`, `smlib_draft`, `smlib_merge_faces`, `smlib_brep_solid_count`, `smlib_imprint`; the fork's `capi/src/smlib_ops.cpp`), declared by
|
||||
//! hand. Part of the FFI boundary, like its parent: called only through
|
||||
@@ -48,6 +48,7 @@ type PickFn = unsafe extern "C" fn(*const RawBrep, *const f64, i64, f64, f64, *m
|
||||
#[cfg(feature = "native")]
|
||||
unsafe extern "C" {
|
||||
fn smlib_boolean(a: *const RawBrep, b: *const RawBrep, op: i32, out: *mut *mut RawBrep) -> i32;
|
||||
fn smlib_boolean_union_all(breps: *const *const RawBrep, n: i64, out: *mut *mut RawBrep) -> i32;
|
||||
fn smlib_boolean2d(a: *const RawBrep, b: *const RawBrep, op: i32, out: *mut *mut RawBrep) -> i32;
|
||||
fn smlib_brep_solid_count(brep: *const RawBrep, out: *mut i64) -> i32;
|
||||
fn smlib_imprint(body: *const RawBrep, tool: *const RawBrep, out: *mut *mut RawBrep) -> i32;
|
||||
@@ -149,6 +150,13 @@ pub fn boolean(a: &Handle, b: &Handle, op: i32) -> Result<Handle, i32> {
|
||||
new_brep(|out| unsafe { smlib_boolean(a.raw(), b.raw(), op, out) })
|
||||
}
|
||||
|
||||
#[cfg(feature = "native")]
|
||||
pub fn boolean_union_all(breps: &[&Handle]) -> Result<Handle, i32> {
|
||||
let raw: Vec<*const RawBrep> = breps.iter().map(|h| h.raw()).collect();
|
||||
let n = i64::try_from(raw.len()).map_err(|_| ERR_ARG)?;
|
||||
new_brep(|out| unsafe { smlib_boolean_union_all(raw.as_ptr(), n, out) })
|
||||
}
|
||||
|
||||
#[cfg(feature = "native")]
|
||||
pub fn boolean2d(a: &Handle, b: &Handle, op: i32) -> Result<Handle, i32> {
|
||||
new_brep(|out| unsafe { smlib_boolean2d(a.raw(), b.raw(), op, out) })
|
||||
@@ -315,6 +323,11 @@ pub fn boolean(_: &Handle, _: &Handle, _: i32) -> Result<Handle, i32> {
|
||||
Err(NOT_BUILT)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "native"))]
|
||||
pub fn boolean_union_all(_: &[&Handle]) -> Result<Handle, i32> {
|
||||
Err(NOT_BUILT)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "native"))]
|
||||
pub fn boolean2d(_: &Handle, _: &Handle, _: i32) -> Result<Handle, i32> {
|
||||
Err(NOT_BUILT)
|
||||
|
||||
@@ -31,7 +31,7 @@ pub mod trim;
|
||||
|
||||
pub use check::{CheckLevel, CheckReport};
|
||||
pub use measure::{MEASURE_ACCURACY, MassProperties};
|
||||
pub use ops::{Blend, BooleanOp, ChamferSecond, MAX_POINTS};
|
||||
pub use ops::{Blend, BooleanOp, ChamferSecond, MAX_POINTS, MAX_UNION_BREPS};
|
||||
|
||||
/// Why an SMLib call failed.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
|
||||
@@ -41,6 +41,9 @@ pub enum ChamferSecond {
|
||||
Angle(f64),
|
||||
}
|
||||
|
||||
/// Most bodies [`Brep::union_all`] takes (the C API's limit).
|
||||
pub const MAX_UNION_BREPS: usize = 100_000;
|
||||
|
||||
/// Most points one selection may hold (the C API's limit).
|
||||
pub const MAX_POINTS: usize = 4096;
|
||||
|
||||
@@ -71,6 +74,19 @@ impl Brep {
|
||||
}
|
||||
}
|
||||
|
||||
/// The union of `breps` in one call: they are unioned pairwise, level by level, so none takes
|
||||
/// part in more than about log2(n) unions. The result is as [`Brep::boolean`]'s; operands
|
||||
/// tagged each with its own number ([`Brep::tagged`]) give a result whose [`Brep::history`]
|
||||
/// names them. At least one body and at most [`MAX_UNION_BREPS`].
|
||||
pub fn union_all(breps: &[&Brep]) -> Result<Brep> {
|
||||
init()?;
|
||||
if breps.is_empty() || breps.len() > MAX_UNION_BREPS {
|
||||
return Err(error(ffi::ERR_ARG));
|
||||
}
|
||||
let handles: Vec<&ffi::Handle> = breps.iter().map(|b| &b.0).collect();
|
||||
ffi::ops::boolean_union_all(&handles).map(Brep).map_err(error)
|
||||
}
|
||||
|
||||
/// `self` and `other`, sheets of planar faces on one plane ([`Brep::planar_faces`]), combined
|
||||
/// as regions of that plane by `op`: `None` when the result is empty. The result's edges are
|
||||
/// the inputs' own curves, split where they cross.
|
||||
|
||||
@@ -580,7 +580,7 @@ impl<'b, 'a> Builder<'b, 'a> {
|
||||
return Err(format!("face #{id}: {}", unsupported("a face without an edge loop")));
|
||||
}
|
||||
let extent = self.extent(&loops)?;
|
||||
let (surface, reversed) = swept::map_surface(&step_surface, &extent).map_err(|m| format!("face #{id}: {m}"))?;
|
||||
let (surface, reversed) = swept::map_surface(&step_surface, &extent, self.tol).map_err(|m| format!("face #{id}: {m}"))?;
|
||||
// Loops relative to the record's natural normal: the face's normal is STEP's surface
|
||||
// normal when same_sense, and the record's is STEP's unless `reversed`.
|
||||
let sense = same_sense != reversed;
|
||||
|
||||
@@ -482,10 +482,12 @@ fn offset(s: BSurface, d: f64) -> R<BSurface> {
|
||||
|
||||
/// A face's surface as a schema surface, and whether the record's natural normal is opposite
|
||||
/// STEP's surface normal (an extruded circle or revolved circle read as a cylinder or torus,
|
||||
/// whose natural normals point away from their axes); `ext` bounds swept surfaces' profiles.
|
||||
pub(super) fn map_surface(s: &Surface, ext: &Extent) -> R<(BSurface, bool)> {
|
||||
/// whose natural normals point away from their axes); `ext` bounds swept surfaces' profiles,
|
||||
/// and a cone that stays within `tol` (the file's distance uncertainty) of its limit plane
|
||||
/// over `ext` is read as that plane.
|
||||
pub(super) fn map_surface(s: &Surface, ext: &Extent, tol: f64) -> R<(BSurface, bool)> {
|
||||
let mut reversed = false;
|
||||
let s = map_surface_in(s, ext, 0, &mut reversed)?;
|
||||
let s = map_surface_in(s, ext, tol, 0, &mut reversed)?;
|
||||
Ok((s, reversed))
|
||||
}
|
||||
|
||||
@@ -538,7 +540,7 @@ fn canonical(s: &Surface, reversed: &mut bool) -> Option<BSurface> {
|
||||
}
|
||||
}
|
||||
|
||||
fn map_surface_in(s: &Surface, ext: &Extent, depth: usize, reversed: &mut bool) -> R<BSurface> {
|
||||
fn map_surface_in(s: &Surface, ext: &Extent, tol: f64, depth: usize, reversed: &mut bool) -> R<BSurface> {
|
||||
if depth > MAX_NESTING {
|
||||
return Err("surfaces nested too deeply".into());
|
||||
}
|
||||
@@ -549,6 +551,9 @@ fn map_surface_in(s: &Surface, ext: &Extent, depth: usize, reversed: &mut bool)
|
||||
Surface::Plane { position } => BSurface::Plane { origin: position.origin, u_axis: position.ref_direction, v_axis: position.y() },
|
||||
Surface::Cylinder { position, radius } => BSurface::Cylinder { frame: frame(position), radius: *radius },
|
||||
Surface::Cone { position, radius, semi_angle } => {
|
||||
if let Some(plane) = flat_cone(position, *radius, *semi_angle, ext, tol, reversed) {
|
||||
return Ok(plane);
|
||||
}
|
||||
if !(*radius >= 0.0) || !(semi_angle.abs() > 1e-12 && semi_angle.abs() < FRAC_PI_2) {
|
||||
return Err(unsupported(format!("a cone of radius {radius} and semi-angle {semi_angle}")));
|
||||
}
|
||||
@@ -563,17 +568,48 @@ fn map_surface_in(s: &Surface, ext: &Extent, depth: usize, reversed: &mut bool)
|
||||
}
|
||||
Surface::DegenerateTorus { .. } => return Err(unsupported("DEGENERATE_TOROIDAL_SURFACE")),
|
||||
Surface::BSpline(b) => super::map_bspline_surface(b)?,
|
||||
Surface::RectangularTrimmed { basis, .. } => map_surface_in(basis, ext, depth + 1, reversed)?,
|
||||
Surface::RectangularTrimmed { basis, .. } => map_surface_in(basis, ext, tol, depth + 1, reversed)?,
|
||||
Surface::Revolution { profile, axis } => revolution(profile, axis, ext)?,
|
||||
Surface::Extrusion { profile, direction, magnitude } => extrusion(profile, *direction, *magnitude, ext)?,
|
||||
Surface::Offset { basis, distance, .. } => {
|
||||
// Along STEP's normal: the record's, or its opposite.
|
||||
let b = map_surface_in(basis, ext, depth + 1, reversed)?;
|
||||
let b = map_surface_in(basis, ext, tol, depth + 1, reversed)?;
|
||||
offset(b, if *reversed { -*distance } else { *distance })?
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// A cone written for a plane (a semi-angle a whisker short of 90°, as exporters write one) as
|
||||
/// that plane: the plane through the placement's origin across its axis, the cone's limit as
|
||||
/// its angle opens to 90°. The cone's height above it is `(rho - radius) cot a` at parameter
|
||||
/// radius `rho`, monotone in `rho` away from the apex: over the face it stays within the
|
||||
/// heights of the boundary points and, should the face hold the axis, the apex's
|
||||
/// (`radius cot a`). `None` unless that deviation is within `tol`. STEP's normal there is
|
||||
/// `-rho tan a` along the axis, so the record's (the axis) is opposite STEP's where
|
||||
/// `rho tan a > 0`.
|
||||
fn flat_cone(position: &Placement, radius: f64, semi_angle: f64, ext: &Extent, tol: f64, reversed: &mut bool) -> Option<BSurface> {
|
||||
let (o, k) = (v3(position.origin), v3(position.axis).normalized()?);
|
||||
let cot = semi_angle.cos() / semi_angle.sin();
|
||||
let mut deviation = (radius * cot).abs();
|
||||
let mut widest: Option<(f64, f64)> = None;
|
||||
for p in &ext.points {
|
||||
let d = *p - o;
|
||||
let h = d.dot(k);
|
||||
deviation = deviation.max(h.abs());
|
||||
let r = (d - k * h).len();
|
||||
if widest.is_none_or(|(w, _)| r > w) {
|
||||
widest = Some((r, h));
|
||||
}
|
||||
}
|
||||
let (_, h) = widest?;
|
||||
if !(deviation <= tol) {
|
||||
return None;
|
||||
}
|
||||
// The parameter radius at the widest boundary point (it keeps one sign off the apex).
|
||||
*reversed ^= (radius + h * semi_angle.tan()) * semi_angle.tan() > 0.0;
|
||||
Some(BSurface::Plane { origin: position.origin, u_axis: position.ref_direction, v_axis: position.y() })
|
||||
}
|
||||
|
||||
/// The STEP parameters of `ps` and `pe` on a hyperbola or parabola.
|
||||
pub(super) fn open_conic_params(c: &Curve, ps: P3, pe: P3) -> R<(f64, f64)> {
|
||||
match (planar_param(c, v3(ps)), planar_param(c, v3(pe))) {
|
||||
|
||||
@@ -906,7 +906,7 @@ fn same_surface(data: &str, us: (f64, f64), vs: (f64, f64)) -> BSurface {
|
||||
.flat_map(|i| (0..=n).map(move |j| (us.0 + (us.1 - us.0) * i as f64 / n as f64, vs.0 + (vs.1 - vs.0) * j as f64 / n as f64)))
|
||||
.collect();
|
||||
let ext = swept::Extent { points: grid.iter().map(|&(u, v)| v3(s.point(u, v).unwrap())).collect(), seam: Vec::new() };
|
||||
let (record, reversed) = swept::map_surface(&s, &ext).unwrap();
|
||||
let (record, reversed) = swept::map_surface(&s, &ext, DEFAULT_TOLERANCE).unwrap();
|
||||
record.natural();
|
||||
let eval = SurfaceEval::new(&record).unwrap();
|
||||
for &(u, v) in &grid {
|
||||
@@ -1003,7 +1003,7 @@ fn swept_and_offset_surfaces_are_the_files_own() {
|
||||
"#1=CARTESIAN_POINT('',(0.,0.,0.));#2=DIRECTION('',(0.,0.,1.));#3=DIRECTION('',(1.,0.,0.));#4=AXIS2_PLACEMENT_3D('',#1,#2,#3);{data}\n"
|
||||
));
|
||||
let s = crate::read::Reader::new(&exch, crate::read::Units::default()).surface(10).unwrap();
|
||||
let e = swept::map_surface(&s, &ext).unwrap_err();
|
||||
let e = swept::map_surface(&s, &ext, DEFAULT_TOLERANCE).unwrap_err();
|
||||
assert!(e.contains(why), "{data}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user