* claim: #6025 * fix(engine): account for sheet perforations in physical properties * fix(inspect): retain kernel topology counts for sheet bodies
This commit is contained in:
1 parent
c8c0c28fc8
commit
91ecea8cfd
7 files changed
+446
-36
No files matched your search
@@ -2545,6 +2545,123 @@ impl SheetBody {
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Include the physical holes that perforation fields leave out of the B-rep measurement.
|
||||
/// `placement` maps this sheet's geometry into the measurement's frame. Hole cylinders
|
||||
/// lie on panels, clear of bends; their volume moments follow each panel's current fold.
|
||||
/// Bounding boxes and B-rep topology are unchanged by these interior holes.
|
||||
pub fn correct_perforation_properties(&self, measured: &mut kernel::BodyMeasure, placement: &Mat) -> Result<()> {
|
||||
let (mut removed, mut area_delta, mut moment_delta) = (0.0, 0.0, Vec3::ZERO);
|
||||
self.visit_perforation_cylinders(placement, |center, volume, area, _| {
|
||||
removed += volume;
|
||||
area_delta += area;
|
||||
// Use distances from the measured centre, including far-away placements.
|
||||
moment_delta += (measured.centroid - center) * volume;
|
||||
})?;
|
||||
if removed == 0.0 {
|
||||
return Ok(());
|
||||
}
|
||||
let volume = measured.volume - removed;
|
||||
let area = measured.area + area_delta;
|
||||
let centroid = measured.centroid + moment_delta / volume;
|
||||
if !(volume.is_finite() && volume > 0.0 && area.is_finite() && area >= 0.0 && centroid.is_finite()) {
|
||||
return Err(DocError::Invalid(format!("invalid perforation physical properties for `{}`", self.body)));
|
||||
}
|
||||
measured.volume = volume;
|
||||
measured.area = area;
|
||||
measured.centroid = centroid;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove the same hole cylinders from the inertia spread as from volume and centroid.
|
||||
/// The input and output tensors are at unit density, about their respective centroids.
|
||||
pub fn correct_perforation_mass_properties(&self, measured: &mut solidcraft_geom::MassProperties, placement: &Mat) -> Result<()> {
|
||||
use solidcraft_geom::inertia;
|
||||
let (mut removed, mut moment_delta, mut removed_inertia) = (0.0, Vec3::ZERO, [[0.0; 3]; 3]);
|
||||
self.visit_perforation_cylinders(placement, |center, volume, _, own| {
|
||||
let delta = measured.centroid - center;
|
||||
removed += volume;
|
||||
moment_delta += delta * volume;
|
||||
let about_center = inertia::shifted(&own, volume, delta);
|
||||
for (row, hole) in removed_inertia.iter_mut().zip(about_center) {
|
||||
for (value, h) in row.iter_mut().zip(hole) {
|
||||
*value += h;
|
||||
}
|
||||
}
|
||||
})?;
|
||||
if removed == 0.0 {
|
||||
return Ok(());
|
||||
}
|
||||
let volume = measured.volume - removed;
|
||||
let delta = moment_delta / volume;
|
||||
let centroid = measured.centroid + delta;
|
||||
let mut tensor = measured.inertia;
|
||||
for (row, hole) in tensor.iter_mut().zip(removed_inertia) {
|
||||
for (value, h) in row.iter_mut().zip(hole) {
|
||||
*value -= h;
|
||||
}
|
||||
}
|
||||
// Move from the old centre to the new one, reversing the parallel-axis term.
|
||||
let tensor = inertia::shifted(&tensor, -volume, delta);
|
||||
if !(volume.is_finite() && volume > 0.0 && centroid.is_finite() && tensor.iter().flatten().all(|v| v.is_finite())) {
|
||||
return Err(DocError::Invalid(format!("invalid perforation inertia for `{}`", self.body)));
|
||||
}
|
||||
measured.volume = volume;
|
||||
measured.centroid = centroid;
|
||||
measured.inertia = tensor;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Analytic cylinders at each panel's current fold, in the requested measurement frame.
|
||||
fn visit_perforation_cylinders(&self, placement: &Mat, mut visit: impl FnMut(Vec3, f64, f64, solidcraft_geom::inertia::Tensor3)) -> Result<()> {
|
||||
if self.perforations.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let invalid = || DocError::Invalid(format!("invalid perforation physical properties for `{}`", self.body));
|
||||
if !(self.t.is_finite() && self.t > 0.0) || placement.iter().flatten().any(|v| !v.is_finite()) {
|
||||
return Err(invalid());
|
||||
}
|
||||
let isometry = |m: &Mat| {
|
||||
let [x, y, z] = [0, 1, 2].map(|i| Vec3::new(m[i][0], m[i][1], m[i][2]));
|
||||
m.iter().flatten().all(|v| v.is_finite())
|
||||
&& m[0][3] == 0.0
|
||||
&& m[1][3] == 0.0
|
||||
&& m[2][3] == 0.0
|
||||
&& m[3][3] == 1.0
|
||||
&& [x, y, z].iter().all(|a| (a.dot(*a) - 1.0).abs() < 1e-9)
|
||||
&& x.dot(y).abs() < 1e-9
|
||||
&& x.dot(z).abs() < 1e-9
|
||||
&& y.dot(z).abs() < 1e-9
|
||||
};
|
||||
let panels: Vec<_> = self.panels().into_iter().map(|(i, region)| (mat_mul(placement, &self.world(i)), region)).collect();
|
||||
let flat = mat_mul(placement, &self.world(None));
|
||||
if !isometry(&flat) || panels.iter().any(|(world, _)| !isometry(world)) {
|
||||
return Err(DocError::Invalid("not supported yet: perforation physical properties under scale or shear".into()));
|
||||
}
|
||||
for p in &self.perforations {
|
||||
if !([p.diameter, p.pitch, p.margin].iter().all(|v| v.is_finite()) && p.diameter > 0.0 && p.pitch > p.diameter && p.margin >= 0.0) {
|
||||
return Err(invalid());
|
||||
}
|
||||
let holes = self.perforation_holes(p)?;
|
||||
let disk = std::f64::consts::PI * (p.diameter / 2.0).powi(2);
|
||||
let volume = disk * self.t;
|
||||
let area_delta = std::f64::consts::PI * p.diameter * self.t - 2.0 * disk;
|
||||
let radius2 = (p.diameter / 2.0).powi(2);
|
||||
let transverse = volume * (3.0 * radius2 + self.t * self.t) / 12.0;
|
||||
let own = [[transverse, 0.0, 0.0], [0.0, transverse, 0.0], [0.0, 0.0, volume * radius2 / 2.0]];
|
||||
for hole in holes {
|
||||
let world = if self.flat || panels.len() == 1 {
|
||||
&flat
|
||||
} else {
|
||||
&panels.iter().find(|(_, region)| region.contains(hole)).ok_or_else(invalid)?.0
|
||||
};
|
||||
let center = apply_point(world, v3(hole) + Vec3::Z * (self.t / 2.0));
|
||||
let rotation = [0, 1, 2].map(|i| [0, 1, 2].map(|j| world[j][i]));
|
||||
visit(center, volume, area_delta, solidcraft_geom::inertia::transformed(&own, &rotation));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Topology counted by faces and loops: a round hole is one face bounded by two closed circular
|
||||
/// edges (one vertex each), where the sewn solid splits it into arcs. Returns the change to
|
||||
/// the sewn (faces, edges, vertices).
|
||||
|
||||
@@ -234,7 +234,12 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool,
|
||||
#[cfg(test)]
|
||||
work::count(|w| w.spreads += spread_bodies.len());
|
||||
let spreads = solidcraft_kernel::map_on_threads(&spread_bodies, 16, |&i| {
|
||||
state.bodies.get(i).and_then(|b| solidcraft_io::mass_properties(&b.body).ok().flatten()).and_then(|m| m.gyration())
|
||||
let body = state.bodies.get(i)?;
|
||||
let mut measured = solidcraft_io::mass_properties(&body.body).ok().flatten()?;
|
||||
if let Some(sheet) = state.sheets.iter().find(|sheet| sheet.body == body.definition_name()) {
|
||||
sheet.correct_perforation_mass_properties(&mut measured, &solidcraft_doc::IDENTITY).ok()?;
|
||||
}
|
||||
measured.gyration()
|
||||
});
|
||||
let spread: BTreeMap<usize, Tensor3> = spread_bodies.into_iter().zip(spreads).filter_map(|(i, g)| Some((i, g.flatten()?))).collect();
|
||||
// A window waiting for the result (the Properties window) sees how far it is and can stop it.
|
||||
@@ -254,7 +259,17 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool,
|
||||
}
|
||||
done += 1;
|
||||
let transform: Mat = doc.model_body_offset(body).map(|offset| solidcraft_doc::mat_mul(&transform, offset)).unwrap_or(transform);
|
||||
let measured = measure_placed(body, transform)?;
|
||||
let mut measured = measure_placed(body, transform)?;
|
||||
if let Some(sheet) = state.sheets.iter().find(|sheet| sheet.body == body.definition_name() && !sheet.perforations.is_empty()) {
|
||||
let mut corrected = body.measure()?;
|
||||
corrected.volume = measured.volume;
|
||||
corrected.area = measured.area;
|
||||
corrected.centroid = measured.centroid;
|
||||
sheet.correct_perforation_properties(&mut corrected, &transform)?;
|
||||
measured.volume = corrected.volume;
|
||||
measured.area = corrected.area;
|
||||
measured.centroid = corrected.centroid;
|
||||
}
|
||||
let density = doc.density(&body.name);
|
||||
let body_mass = measured.volume * density / 1000.0;
|
||||
let closed = measured.closed;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::Session;
|
||||
use serde_json::{Value, json};
|
||||
use solidcore_record::Vec2;
|
||||
use solidcraft_geom::prelude::*;
|
||||
|
||||
fn run(s: &mut Session, cmd: &str, params: Value) -> Value {
|
||||
@@ -89,6 +90,252 @@ fn body_reassignment_offsets_preserve_world_properties() {
|
||||
close(&r["total"]["center_of_mass"][0], 5.0);
|
||||
}
|
||||
|
||||
fn panel_blank(s: &mut Session, width: f64, height: f64) {
|
||||
run(s, "sheet.manage_rules", json!({"name": "Panel 0.8", "thickness": "0.8", "active": true}));
|
||||
run(s, "sketch.create", json!({"plane": "XY", "name": "Blank"}));
|
||||
run(s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [width, height]}));
|
||||
run(s, "sketch.finish", json!({}));
|
||||
run(s, "sheet.flange", json!({"sketch": "Blank", "body_name": "Panel"}));
|
||||
}
|
||||
|
||||
fn perforated_panel(s: &mut Session) {
|
||||
panel_blank(s, 20.0, 10.0);
|
||||
run(s, "sheet.perforate", json!({"diameter": "2", "pitch": "10", "margin": "1", "pattern": "square"}));
|
||||
run(s, "material.assign", json!({"bodies": ["Panel"], "material": "Steel"}));
|
||||
}
|
||||
|
||||
/// Two radius-1 holes centred at (2, 2) and (12, 2), through a 20 x 10 x 0.8 blank.
|
||||
fn perforated_panel_expected() -> (f64, f64, [f64; 3]) {
|
||||
let removed = 2.0 * std::f64::consts::PI * 0.8;
|
||||
let volume = 160.0 - removed;
|
||||
let area = 448.0 - 0.8 * std::f64::consts::PI;
|
||||
(volume, area, [(160.0 * 10.0 - removed * 7.0) / volume, (160.0 * 5.0 - removed * 2.0) / volume, 0.4])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn perforated_sheet_properties_include_holes_and_their_off_centre_volume_moment() {
|
||||
let mut s = Session::default();
|
||||
perforated_panel(&mut s);
|
||||
let (volume, area, center) = perforated_panel_expected();
|
||||
let density = s.doc.density("Panel");
|
||||
let doc = s.doc.clone();
|
||||
let undo = s.undo.len();
|
||||
for command in ["component.properties", "inspect.measure"] {
|
||||
let result = run(&mut s, command, json!({}));
|
||||
close(&result["total"]["volume_mm3"], volume);
|
||||
close(&result["total"]["mass_g"], volume * density / 1000.0);
|
||||
close(&result["total"]["area_mm2"], area);
|
||||
for (axis, expected) in center.iter().enumerate() {
|
||||
close(&result["bodies"][0]["center_of_mass"][axis], *expected);
|
||||
}
|
||||
}
|
||||
let inspected = run(&mut s, "document.inspect", json!({"measure": true}));
|
||||
close(&inspected["bodies"][0]["volume_mm3"], volume);
|
||||
close(&inspected["bodies"][0]["area_mm2"], area);
|
||||
for key in ["faces", "edges", "vertices"] {
|
||||
assert_eq!(inspected["bodies"][0][key], inspected["bodies"][0]["kernel"][key], "document.inspect retains kernel {key}");
|
||||
}
|
||||
assert!(inspected["bodies"][0].get("sheet_metal").is_none());
|
||||
let picked = run(&mut s, "inspect.measure", json!({"items": [{"type": "body", "name": "Panel"}]}));
|
||||
close(&picked["items"][0]["volume_mm3"], volume);
|
||||
assert!(std::sync::Arc::ptr_eq(&s.doc, &doc));
|
||||
assert_eq!(s.undo.len(), undo, "measuring must not add an undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn perforated_sheet_instances_keep_physical_properties_in_nested_world_placements() {
|
||||
let mut s = Session::default();
|
||||
let parent = run(&mut s, "component.create", json!({"name": "Subassembly", "grounded": false}));
|
||||
let child = run(&mut s, "component.create", json!({"name": "Sheet", "grounded": false}));
|
||||
perforated_panel(&mut s);
|
||||
let sheet_density = s.doc.density("Panel");
|
||||
run(&mut s, "component.activate", json!({"component": "root"}));
|
||||
let copy = run(&mut s, "occurrence.copy", json!({"component": parent["component"], "translate": [40, 0, 0]}));
|
||||
run(
|
||||
&mut s,
|
||||
"occurrence.move",
|
||||
json!({"occurrence": parent["occurrence"], "translate": [20, 0, 10], "axis": [0, 0, 1], "angle": "90 deg", "capture": false}),
|
||||
);
|
||||
box_in(&mut s, "Ballast");
|
||||
let ballast_body = s.model.state().bodies.last().unwrap().name.clone();
|
||||
run(&mut s, "material.assign", json!({"bodies": [ballast_body], "material": "Aluminum"}));
|
||||
let ballast_mass = s.doc.density(&ballast_body);
|
||||
let (volume, area, center) = perforated_panel_expected();
|
||||
let sheet_mass = volume * sheet_density / 1000.0;
|
||||
let first = [20.0 - center[1], center[0], 10.0 + center[2]];
|
||||
let second = [40.0 + center[0], center[1], center[2]];
|
||||
let doc = s.doc.clone();
|
||||
let moves = s.pending_moves.clone();
|
||||
let undo = s.undo.len();
|
||||
for (parent_occurrence, expected) in [(&parent["occurrence"], first), (©["occurrence"], second)] {
|
||||
let properties =
|
||||
run(&mut s, "occurrence.properties", json!({"occurrence": child["occurrence"], "path": [parent_occurrence, child["occurrence"]]}));
|
||||
close(&properties["total"]["volume_mm3"], volume);
|
||||
close(&properties["total"]["mass_g"], sheet_mass);
|
||||
close(&properties["total"]["area_mm2"], area);
|
||||
for (axis, coordinate) in expected.iter().enumerate() {
|
||||
close(&properties["total"]["center_of_mass"][axis], *coordinate);
|
||||
}
|
||||
}
|
||||
let properties = run(&mut s, "component.properties", json!({"component": "root"}));
|
||||
let mass = 2.0 * sheet_mass + ballast_mass;
|
||||
close(&properties["total"]["volume_mm3"], 2.0 * volume + 1000.0);
|
||||
close(&properties["total"]["mass_g"], mass);
|
||||
for axis in 0..3 {
|
||||
close(&properties["total"]["center_of_mass"][axis], (sheet_mass * (first[axis] + second[axis]) + ballast_mass * 5.0) / mass);
|
||||
}
|
||||
let measured = run(&mut s, "inspect.measure", json!({}));
|
||||
close(&measured["total"]["volume_mm3"], 2.0 * volume + 1000.0);
|
||||
close(&measured["total"]["mass_g"], mass);
|
||||
assert_eq!(measured["bodies"].as_array().unwrap().iter().filter(|b| b["sheet_metal"] == true).count(), 2);
|
||||
assert!(std::sync::Arc::ptr_eq(&s.doc, &doc));
|
||||
assert_eq!(s.pending_moves, moves);
|
||||
assert_eq!(s.undo.len(), undo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn perforated_sheet_centroid_follows_a_folded_panel_and_unfolds() {
|
||||
use std::f64::consts::{FRAC_PI_2, PI};
|
||||
let mut s = Session::default();
|
||||
panel_blank(&mut s, 30.0, 10.0);
|
||||
run(
|
||||
&mut s,
|
||||
"sheet.fold",
|
||||
json!({"points": [[10, 0, 0], [10, 10, 0]], "angle": "90 deg", "radius": "0.8", "position": "centerline", "fixed": [2, 5, 0]}),
|
||||
);
|
||||
let before = run(&mut s, "component.properties", json!({"component": "root"}));
|
||||
run(&mut s, "sheet.perforate", json!({"diameter": "2", "pitch": "10", "margin": "0", "pattern": "square"}));
|
||||
let sheet = &s.model.state().sheets[0];
|
||||
let holes = sheet.perforation_holes(&sheet.perforations[0]).unwrap();
|
||||
assert_eq!(holes.len(), 2);
|
||||
// Fold boundaries carry kernel roundoff; keep the analytic centres and the
|
||||
// same sub-micrometre tolerance used by the property checks below.
|
||||
for (hole, expected) in holes.iter().zip([Vec2::new(1.0, 1.0), Vec2::new(21.0, 1.0)]) {
|
||||
assert!(hole.dist(expected) < 1e-6, "{hole:?} != {expected:?}");
|
||||
}
|
||||
// The right panel turns up by 90 degrees about a y-parallel bend axis at
|
||||
// z = radius + thickness. Its mid-plane is radius + thickness/2 from that axis.
|
||||
let allowance = FRAC_PI_2 * (0.8 + 0.44 * 0.8);
|
||||
let bend_start = 10.0 - allowance / 2.0;
|
||||
let right_hole = [bend_start + 1.2, 1.0, 1.6 + 21.0 - bend_start - allowance];
|
||||
let old_volume = before["total"]["volume_mm3"].as_f64().unwrap();
|
||||
let hole_volume = PI * 0.8;
|
||||
let volume = old_volume - 2.0 * hole_volume;
|
||||
let result = run(&mut s, "component.properties", json!({"component": "root"}));
|
||||
close(&result["total"]["volume_mm3"], volume);
|
||||
for (axis, left) in [1.0, 1.0, 0.4].iter().enumerate() {
|
||||
let old = before["total"]["center_of_mass"][axis].as_f64().unwrap();
|
||||
close(&result["total"]["center_of_mass"][axis], old + hole_volume * (2.0 * old - left - right_hole[axis]) / volume);
|
||||
}
|
||||
run(&mut s, "sheet.unfold", json!({}));
|
||||
let result = run(&mut s, "component.properties", json!({"component": "root"}));
|
||||
let volume = 240.0 - 2.0 * hole_volume;
|
||||
close(&result["total"]["volume_mm3"], volume);
|
||||
for (axis, expected) in [(240.0 * 15.0 - 2.0 * hole_volume * 11.0) / volume, (240.0 * 5.0 - 2.0 * hole_volume) / volume, 0.4].iter().enumerate() {
|
||||
close(&result["total"]["center_of_mass"][axis], *expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn perforated_sheet_correction_rejects_invalid_metadata_without_partial_changes() {
|
||||
let mut s = Session::default();
|
||||
perforated_panel(&mut s);
|
||||
let state = s.model.state();
|
||||
let measured = solidcraft_kernel::measure(&state.bodies[0].body).unwrap();
|
||||
for pitch in [0.0, -1.0, f64::NAN, f64::INFINITY] {
|
||||
let mut sheet = state.sheets[0].clone();
|
||||
sheet.perforations[0].pitch = pitch;
|
||||
let mut actual = measured.clone();
|
||||
assert!(sheet.correct_perforation_properties(&mut actual, &solidcraft_doc::IDENTITY).is_err());
|
||||
assert_eq!(actual.volume, measured.volume);
|
||||
assert_eq!(actual.area, measured.area);
|
||||
assert_eq!(actual.centroid, measured.centroid);
|
||||
}
|
||||
let mut scaled = solidcraft_doc::IDENTITY;
|
||||
scaled[0][0] = 2.0;
|
||||
let mut sheared = solidcraft_doc::IDENTITY;
|
||||
sheared[0][1] = 0.5;
|
||||
for placement in [scaled, sheared] {
|
||||
let mut actual = measured.clone();
|
||||
assert!(state.sheets[0].correct_perforation_properties(&mut actual, &placement).is_err());
|
||||
assert_eq!((actual.volume, actual.area, actual.centroid), (measured.volume, measured.area, measured.centroid));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn perforated_sheet_body_transfer_preserves_world_mass_and_centroid() {
|
||||
let mut s = Session::default();
|
||||
perforated_panel(&mut s);
|
||||
let moved = run(&mut s, "component.create", json!({"name": "MovedSheet", "grounded": false}));
|
||||
run(&mut s, "occurrence.move", json!({"occurrence": moved["occurrence"], "translate": [100, 0, 0]}));
|
||||
run(&mut s, "component.move_bodies", json!({"bodies": ["Panel"], "component": moved["component"]}));
|
||||
let (volume, _, center) = perforated_panel_expected();
|
||||
let mass = volume * s.doc.density("Panel") / 1000.0;
|
||||
for command in ["component.properties", "inspect.measure"] {
|
||||
let result = run(&mut s, command, json!({"component": "root"}));
|
||||
close(&result["total"]["volume_mm3"], volume);
|
||||
close(&result["total"]["mass_g"], mass);
|
||||
for (axis, expected) in center.iter().enumerate() {
|
||||
close(&result["bodies"][0]["center_of_mass"][axis], *expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn perforated_sheet_inertia_removes_analytic_hole_cylinders_and_turns_with_the_sheet() {
|
||||
let mut s = Session::default();
|
||||
let c = run(&mut s, "component.create", json!({"name": "Sheet", "grounded": false}));
|
||||
perforated_panel(&mut s);
|
||||
let (volume, _, center) = perforated_panel_expected();
|
||||
let old_center = [10.0, 5.0, 0.4];
|
||||
let mut expected = [[0.0; 3]; 3];
|
||||
let dimensions: [f64; 3] = [20.0, 10.0, 0.8];
|
||||
for i in 0..3 {
|
||||
expected[i][i] = 160.0 * (dimensions[(i + 1) % 3].powi(2) + dimensions[(i + 2) % 3].powi(2)) / 12.0;
|
||||
}
|
||||
let hole_volume = std::f64::consts::PI * 0.8;
|
||||
let own = [hole_volume * (3.0 + 0.64) / 12.0, hole_volume * (3.0 + 0.64) / 12.0, hole_volume / 2.0];
|
||||
for hole in [[2.0, 2.0, 0.4], [12.0, 2.0, 0.4]] {
|
||||
let d = [0, 1, 2].map(|i| hole[i] - old_center[i]);
|
||||
let d2: f64 = d.iter().map(|v| v * v).sum();
|
||||
for i in 0..3 {
|
||||
for j in 0..3 {
|
||||
expected[i][j] -= if i == j { own[i] + hole_volume * d2 } else { 0.0 } - hole_volume * d[i] * d[j];
|
||||
}
|
||||
}
|
||||
}
|
||||
let d = [0, 1, 2].map(|i| center[i] - old_center[i]);
|
||||
let d2: f64 = d.iter().map(|v| v * v).sum();
|
||||
for i in 0..3 {
|
||||
for j in 0..3 {
|
||||
expected[i][j] = (expected[i][j] - volume * (if i == j { d2 } else { 0.0 } - d[i] * d[j])) * s.doc.density("Panel") / 1000.0;
|
||||
}
|
||||
}
|
||||
let first = run(&mut s, "component.properties", json!({}));
|
||||
tensor_close(&first["total"]["inertia_g_mm2"], expected, 1e-9);
|
||||
let verify_assembly = |s: &mut Session, tensor: [[f64; 3]; 3], center: [f64; 3]| {
|
||||
let assembly = run(s, "assembly.mass_properties", json!({}));
|
||||
let occurrence = assembly["occurrences"].as_array().unwrap().iter().find(|o| o["occurrence"] == c["occurrence"]).unwrap();
|
||||
let mass = &occurrence["mass"];
|
||||
assert!((mass["mass_kg"].as_f64().unwrap() - volume * s.doc.density("Panel") * 1e-6).abs() < 1e-12);
|
||||
for (axis, coordinate) in center.iter().enumerate() {
|
||||
close(&mass["center_of_mass_mm"][axis], *coordinate);
|
||||
}
|
||||
tensor_close(&mass["inertia_world_kg_mm2"], tensor.map(|row| row.map(|value| value / 1000.0)), 1e-9);
|
||||
};
|
||||
verify_assembly(&mut s, expected, center);
|
||||
run(
|
||||
&mut s,
|
||||
"occurrence.move",
|
||||
json!({"occurrence": c["occurrence"], "translate": [100, 40, 10], "axis": [0, 0, 1], "angle": "90 deg", "capture": false}),
|
||||
);
|
||||
let turned = run(&mut s, "component.properties", json!({}));
|
||||
let rotation = [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]];
|
||||
let rotated = solidcraft_geom::inertia::transformed(&expected, &rotation);
|
||||
tensor_close(&turned["total"]["inertia_g_mm2"], rotated, 1e-9);
|
||||
verify_assembly(&mut s, rotated, [100.0 - center[1], 40.0 + center[0], 10.0 + center[2]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn properties_reject_hostile_identifiers_and_options() {
|
||||
let mut s = Session::default();
|
||||
|
||||
@@ -128,7 +128,30 @@ pub(crate) fn encloses_volume(body: &solidcraft_kernel::Body) -> bool {
|
||||
}
|
||||
|
||||
pub fn measure_json(b: &solidcraft_doc::ModelBody) -> Value {
|
||||
match b.measure() {
|
||||
measure_sheet_json(b, None)
|
||||
}
|
||||
|
||||
pub(super) fn measure_body(
|
||||
b: &solidcraft_doc::ModelBody,
|
||||
definitions: Option<&solidcraft_doc::ModelState>,
|
||||
) -> Result<solidcraft_kernel::BodyMeasure> {
|
||||
let mut measured = b.measure()?;
|
||||
if let Some(state) = definitions
|
||||
&& let Some(sheet) = state.sheets.iter().find(|sheet| sheet.body == b.definition_name() && !sheet.perforations.is_empty())
|
||||
{
|
||||
let definition = state.body(b.definition_name()).ok_or_else(|| EngineError::Other(format!("missing sheet body `{}`", sheet.body)))?;
|
||||
// A body transfer moves the geometry and sheet metadata together. Apply only
|
||||
// the placement relative to the current definition, so holes move once.
|
||||
let inverse = solidcraft_doc::mat_inverse(&definition.source_transform)
|
||||
.ok_or_else(|| EngineError::Other(format!("invalid sheet placement for `{}`", sheet.body)))?;
|
||||
let placement = solidcraft_doc::mat_mul(&b.source_transform, &inverse);
|
||||
sheet.correct_perforation_properties(&mut measured, &placement)?;
|
||||
}
|
||||
Ok(measured)
|
||||
}
|
||||
|
||||
fn measure_sheet_json(b: &solidcraft_doc::ModelBody, definitions: Option<&solidcraft_doc::ModelState>) -> Value {
|
||||
match measure_body(b, definitions) {
|
||||
Ok(m) => {
|
||||
let closed = encloses_volume(&b.body);
|
||||
json!({
|
||||
@@ -157,6 +180,7 @@ fn measure(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return super::measure_sel::measure_items(s, items);
|
||||
}
|
||||
let want = string_list(cmd, p, "bodies")?;
|
||||
let definitions = s.model.state();
|
||||
let st = s.world_state()?;
|
||||
let selected: Vec<_> = st.bodies.iter().filter(|b| want.is_empty() || want.contains(&b.name)).collect();
|
||||
if !want.is_empty() && selected.len() != want.len() {
|
||||
@@ -167,7 +191,7 @@ fn measure(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(json!({"body_count": bodies.len(), "bodies": bodies}));
|
||||
}
|
||||
// Each body is measured on its own: on all cores, in body order.
|
||||
let mut bodies: Vec<Value> = solidcraft_kernel::map_on_threads(&selected, 16, |b| measure_json(b))
|
||||
let mut bodies: Vec<Value> = solidcraft_kernel::map_on_threads(&selected, 16, |b| measure_sheet_json(b, Some(&definitions)))
|
||||
.into_iter()
|
||||
.zip(&selected)
|
||||
.map(|(m, b)| m.unwrap_or_else(|| json!({"name": b.name, "error": "measuring this body failed"})))
|
||||
@@ -182,35 +206,13 @@ fn measure(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
b["density_g_cm3"] = json!(rho);
|
||||
b["mass_g"] = json!(v * rho / 1000.0);
|
||||
}
|
||||
}
|
||||
// Sheet metal keeps the edges where bends meet flat faces (so bends stay visible): count its
|
||||
// B-rep faces as they are, without merging coplanar neighbours.
|
||||
let sheets = s.model.state().sheets.clone();
|
||||
for b in &mut bodies {
|
||||
if let Some(sh) = sheets.iter().find(|x| b["name"].as_str() == Some(x.body.as_str())) {
|
||||
let (df, de, dv) = sh.round_hole_correction();
|
||||
for (k, d) in [("faces", df), ("edges", de), ("vertices", dv)] {
|
||||
b[k] = json!(b["kernel"][k].as_i64().unwrap_or(0) + d);
|
||||
// Only Measure exposes sheet boundary counts; document.inspect keeps kernel counts.
|
||||
if let Some(sheet) = definitions.sheets.iter().find(|sheet| sheet.body == source) {
|
||||
let (df, de, dv) = sheet.round_hole_correction();
|
||||
for (key, delta) in [("faces", df), ("edges", de), ("vertices", dv)] {
|
||||
b[key] = json!(b["kernel"][key].as_i64().unwrap_or(0) + delta);
|
||||
}
|
||||
b["sheet_metal"] = json!(true);
|
||||
// A perforation field (#732) is not cut into the B-rep: take its open area out of the volume, the mass
|
||||
// and the area (both faces minus the holes, plus the bores).
|
||||
let open = sh.perforated_area();
|
||||
if open > 0.0 {
|
||||
if let Some(v) = b["volume_mm3"].as_f64() {
|
||||
let nv = v - open * sh.t;
|
||||
if let Some(m) = b["mass_g"].as_f64().filter(|_| v > 0.0) {
|
||||
b["mass_g"] = json!(m * nv / v);
|
||||
}
|
||||
b["volume_mm3"] = json!(nv);
|
||||
}
|
||||
let bores: f64 = sh
|
||||
.perforations
|
||||
.iter()
|
||||
.map(|p| sh.perforation_holes(p).map_or(0.0, |h| h.len() as f64) * std::f64::consts::PI * p.diameter * sh.t)
|
||||
.sum();
|
||||
b["area_mm2"] = json!(b["area_mm2"].as_f64().unwrap_or(0.0) - 2.0 * open + bores);
|
||||
}
|
||||
}
|
||||
}
|
||||
let skipped = bodies.iter().filter(|b| b["closed"] == false).count();
|
||||
@@ -395,9 +397,12 @@ fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let definitions = s.model.state();
|
||||
let with_measure = bool_(p, "measure").unwrap_or(false);
|
||||
// Each body is measured on its own: on all cores, in body order (as `inspect.measure`).
|
||||
let mut measured = if with_measure { solidcraft_kernel::map_on_threads(&st.bodies, 16, measure_json) } else { Vec::new() }.into_iter();
|
||||
let mut measured =
|
||||
if with_measure { solidcraft_kernel::map_on_threads(&st.bodies, 16, |b| measure_sheet_json(b, Some(&definitions))) } else { Vec::new() }
|
||||
.into_iter();
|
||||
let bodies: Vec<Value> = st
|
||||
.bodies
|
||||
.iter()
|
||||
|
||||
@@ -242,9 +242,20 @@ pub fn assembly(doc: &Document, state: &ModelState) -> Result<AssemblyMassResult
|
||||
if !closed {
|
||||
return Ok(Shape { closed, volume: 0.0, centroid: Vec3::ZERO, gyration: None });
|
||||
}
|
||||
let m = solidcraft_kernel::measure_mass(&body.body)?;
|
||||
let gyration = solidcraft_io::mass_properties(&body.body)?.and_then(|p| p.gyration());
|
||||
Ok(Shape { closed, volume: m.volume, centroid: m.centroid, gyration })
|
||||
let sheet = state.sheets.iter().find(|sheet| sheet.body == body.definition_name() && !sheet.perforations.is_empty());
|
||||
let (volume, centroid) = if sheet.is_some() {
|
||||
let measured = super::inspect::measure_body(body, Some(state))?;
|
||||
(measured.volume, measured.centroid)
|
||||
} else {
|
||||
let measured = solidcraft_kernel::measure_mass(&body.body)?;
|
||||
(measured.volume, measured.centroid)
|
||||
};
|
||||
let mut moments = solidcraft_io::mass_properties(&body.body)?;
|
||||
if let (Some(sheet), Some(moments)) = (sheet, moments.as_mut()) {
|
||||
sheet.correct_perforation_mass_properties(moments, &IDENTITY)?;
|
||||
}
|
||||
let gyration = moments.and_then(|p| p.gyration());
|
||||
Ok(Shape { closed, volume, centroid, gyration })
|
||||
});
|
||||
let mut shape: BTreeMap<usize, Shape> = BTreeMap::new();
|
||||
for (i, s) in measured.into_iter().zip(shapes) {
|
||||
|
||||
@@ -380,7 +380,12 @@ fn describe(s: &Session, st: &solidcraft_doc::ModelState, sel: &Sel) -> Option<I
|
||||
let closed = crate::cmd::inspect::encloses_volume(&body.body);
|
||||
let m = body.mesh();
|
||||
let tris: Vec<[Vec3; 3]> = m.triangles.iter().filter_map(|t| m.tri(t)).collect();
|
||||
let v = m.measure().volume;
|
||||
let definitions = s.model.state();
|
||||
let v = if definitions.sheets.iter().any(|sheet| sheet.body == body.definition_name() && !sheet.perforations.is_empty()) {
|
||||
super::inspect::measure_body(body, Some(&definitions)).ok()?.volume
|
||||
} else {
|
||||
m.measure().volume
|
||||
};
|
||||
plain(Geo::Tris(tris), None, json!({"type": "body", "name": name, "closed": closed, "volume_mm3": closed.then_some(v)}))
|
||||
}
|
||||
Sel::SketchCurve { id, sketch } => sketch_curve(sketch_of(s, st, *sketch, |sk| sk.curve_index(id).is_some())?, id),
|
||||
|
||||
@@ -40,6 +40,16 @@ null center of mass and bounding box. A failed body measurement returns an error
|
||||
presenting an incomplete assembly total. These commands leave geometry, pending placements
|
||||
and undo history unchanged.
|
||||
|
||||
Sheet-metal perforation fields contribute their physical holes to volume, mass, surface area
|
||||
and center of mass even though they do not cut the B-rep. Hole centers follow the panels when
|
||||
folded or unfolded and follow each occurrence's placement. Measure and component/occurrence
|
||||
Properties use the same correction. Bounding boxes and B-rep topology still describe the
|
||||
uncut body. A failed perforation calculation returns an error rather than an uncorrected total.
|
||||
The inertia tensor also removes each analytic hole cylinder, including its offset from the
|
||||
sheet's center of mass.
|
||||
Measuring a perforated sheet after scaling or shearing its metadata is not supported and
|
||||
returns an error. Rigid and mirrored placements preserve the analytic hole dimensions.
|
||||
|
||||
## Moment of inertia
|
||||
|
||||
Each closed body's entry has `inertia_g_mm2`: its inertia tensor about its own center of mass,
|
||||
|
||||
Reference in new issue
Block a user