use crate::topology::BrepSolid;
use crate::{Aabb, KernelRefusal, NurbsCurve, NurbsSurface, Vec4};
pub(crate) fn enabled() -> bool {
crate::switch!("BREP_WORKING_SCALE", true)
}
pub(crate) const WORKING_DIAGONAL: f64 = 1.0;
pub(crate) const FIRING_DIAGONAL: f64 = 0.0625;
const SMALLEST_DIAGONAL: f64 = 1e-150;
pub(crate) fn guard_factor(bounds: Aabb) -> Option<f64> {
if !enabled() {
return None;
}
factor_for_diagonal(bounds.diagonal())
}
pub(crate) fn factor_for_diagonal(diagonal: f64) -> Option<f64> {
if !(diagonal.is_finite() && diagonal >= SMALLEST_DIAGONAL && diagonal < FIRING_DIAGONAL) {
return None;
}
let mut factor = 1.0f64;
let mut scaled = diagonal;
while scaled < WORKING_DIAGONAL {
scaled *= 2.0;
factor *= 2.0;
}
Some(factor)
}
pub(crate) fn bounds_of<'a>(solids: impl IntoIterator<Item = &'a BrepSolid>) -> Option<Aabb> {
let mut all: Option<Aabb> = None;
for solid in solids {
if solid.vertices.is_empty() && solid.shells.iter().all(|shell| shell.faces.is_empty()) {
continue;
}
let bounds = crate::recentre::solid_bounds(solid);
match &mut all {
Some(all) => all.include(bounds),
None => all = Some(bounds),
}
}
all
}
fn scale_controls(points: &[Vec4], factor: f64) -> Vec<Vec4> {
points.iter().map(|p| Vec4 { x: p.x * factor, y: p.y * factor, z: p.z * factor, w: p.w }).collect()
}
fn scale_curve(curve: &NurbsCurve, factor: f64) -> Result<NurbsCurve, String> {
NurbsCurve::new(curve.degree, curve.knots.clone(), scale_controls(&curve.control_points, factor))
}
fn length_parameters(surface: &NurbsSurface) -> (bool, bool) {
let (Some(&u0), Some(&u1), Some(&v0), Some(&v1)) =
(surface.knots_u.first(), surface.knots_u.last(), surface.knots_v.first(), surface.knots_v.last())
else {
return (false, false);
};
let (du, dv) = ((u1 - u0) / 64.0, (v1 - v0) / 64.0);
if !(du > 0.0 && dv > 0.0) {
return (false, false);
}
let (mut along_u, mut along_v) = (true, true);
for i in 0..3 {
for j in 0..3 {
let u = u0 + (u1 - u0) * (0.25 + 0.25 * i as f64);
let v = v0 + (v1 - v0) * (0.25 + 0.25 * j as f64);
let (Ok(here), Ok(next_u), Ok(next_v)) =
(surface.evaluate(u, v), surface.evaluate(u + du, v), surface.evaluate(u, v + dv))
else {
return (false, false);
};
along_u &= (next_u.sub(here).length() / du - 1.0).abs() <= UNIT_SPEED_BAND;
along_v &= (next_v.sub(here).length() / dv - 1.0).abs() <= UNIT_SPEED_BAND;
}
}
(along_u, along_v)
}
const UNIT_SPEED_BAND: f64 = 1e-9;
fn scale_surface(surface: &NurbsSurface, factor: f64) -> Result<(NurbsSurface, bool, bool), String> {
let (along_u, along_v) = length_parameters(surface);
let knots = |knots: &[f64], scaled: bool| -> Vec<f64> {
if scaled { knots.iter().map(|knot| knot * factor).collect() } else { knots.to_vec() }
};
let scaled = NurbsSurface::new(
surface.degree_u,
surface.degree_v,
knots(&surface.knots_u, along_u),
knots(&surface.knots_v, along_v),
surface.control_points.iter().map(|row| scale_controls(row, factor)).collect(),
)?;
Ok((scaled, along_u, along_v))
}
pub(crate) fn scale_solid(solid: &BrepSolid, factor: f64) -> Result<BrepSolid, String> {
let mut result = solid.clone();
result.mass_properties_cache = Default::default();
for vertex in &mut result.vertices {
vertex.point = vertex.point.scale(factor);
}
for edge in &mut result.edges {
edge.curve = scale_curve(&edge.curve, factor)?;
}
for shell in &mut result.shells {
for face in &mut shell.faces {
let (surface, along_u, along_v) = scale_surface(&face.surface, factor)?;
face.surface = surface;
if !(along_u || along_v) {
continue;
}
let (fu, fv) = (if along_u { factor } else { 1.0 }, if along_v { factor } else { 1.0 });
for coedge in face.loops.iter_mut().flat_map(|loop_record| &mut loop_record.coedges) {
let controls = coedge.pcurve.control_points.iter().map(|p| Vec4 { x: p.x * fu, y: p.y * fv, z: p.z, w: p.w }).collect();
coedge.pcurve = NurbsCurve::new(coedge.pcurve.degree, coedge.pcurve.knots.clone(), controls)?;
}
}
}
Ok(result)
}
pub(crate) fn scale_operand(solid: &BrepSolid, factor: f64, entry: &str) -> Result<BrepSolid, KernelRefusal> {
scale_solid(solid, factor).map_err(|message| {
KernelRefusal::internal(
crate::KernelStage::Collect,
"working_scale",
format!("{entry}: the working scale could not scale a body by {factor}: {message}"),
)
})
}
pub(crate) fn name_scale(error: KernelRefusal, factor: f64) -> KernelRefusal {
error.with_message(|message| format!("{message} (lengths at the working scale, {factor} times the model's)"))
}
pub(crate) fn offset_factor(source: &BrepSolid, distance: f64) -> Option<(f64, Aabb)> {
let mut bounds = bounds_of([source])?;
let reach = distance.abs();
if !reach.is_finite() {
return None;
}
let pad = crate::Vec3::new(reach, reach, reach);
bounds = Aabb { minimum: bounds.minimum.sub(pad), maximum: bounds.maximum.add(pad) };
guard_factor(bounds).map(|factor| (factor, bounds))
}
pub(crate) struct ScaledOffset {
pub(crate) factor: f64,
pub(crate) source: BrepSolid,
pub(crate) distance: f64,
}
impl ScaledOffset {
pub(crate) fn of(source: &BrepSolid, distance: f64, entry: &str) -> Result<Option<Self>, KernelRefusal> {
let Some((factor, bounds)) = offset_factor(source, distance) else {
return Ok(None);
};
profile_fired(entry, factor, bounds);
let source = scale_operand(source, factor, entry)?;
Ok(Some(Self { factor, source, distance: distance * factor }))
}
pub(crate) fn back(&self, solid: &BrepSolid, entry: &str) -> Result<BrepSolid, KernelRefusal> {
scale_operand(solid, 1.0 / self.factor, entry)
}
pub(crate) fn refusal(&self, error: KernelRefusal) -> KernelRefusal {
name_scale(error, self.factor)
}
}
pub(crate) fn profile_fired(entry: &str, factor: f64, bounds: Aabb) {
if crate::profile::profile_enabled() {
profile_line!("working_scale.fired entry={entry} factor={factor} diagonal={:.4e}", bounds.diagonal());
}
}