866029aaa2
* Engine: one sketch store for the sketch commands (W38.0, #5425, no behaviour change) The sketch commands found and kept the sketch they work on in about forty places, each its own way. They now go through one module, cmd::sketch_store, so a drawing session (W38a/b) can put sheet and view sketches behind the same calls without the commands changing again. - target: the command's `sketch` param or the sketch being edited (target_sketch, moved). - active: the sketch being edited, if any. The thirteen commands that need one keep their own refusal text; unifying the three texts is a separate, visible change. - read and write: the only calls from the sketch commands to Document::sketch and sketch_mut. - update: change a sketch on a copy of the document and keep both, the edit the text and link commands made by hand (sketch.text, sketch.edit_text, the projection, intersection and include links, sketch.fit_curves_to_section, sketch.break_link). As before, those paths neither solve the sketch nor run its checks. - checked: the checks an edited sketch passes (the periodic splines), shared by edit_solved and sketch.offset.break. edit and edit_solved stay in sketch.rs and load and keep their sketch through read and write. Imported text, snap points and the face projections keep their own shape (a text that can't be linked is skipped, snap points copy the document only when one is needed) through read and write. The reads and writes that are about the design's own sketches stay as they are, each on a line marked `// design-only:` (Redefine Sketch Plane, a joint's curve, a motion trace's wire, and the session's live drag, parameter edits and `created` diff). A source scan, each_sketch_command_goes_through_the_store, fails when a command reads or writes a sketch, or asks for the active one, anywhere but the store or a marked design-only line in the files that work on the design's sketches. Every existing sketch test is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Engine: the sketch store's scan also catches the active sketch taken as a value (#5425, review of #6336) The scan only caught `active_sketch.ok_or`, so main's `let Some(id) = s.active_sketch else …` could have come back unseen (0xlillith's review). It now also flags the value-read forms: `) = s.active_sketch` (let-else and if let), `=> s.active_sketch` (a match arm), `s.active_sketch.and_then(` and `s.active_sketch.map(`. State checks (`is_some`, `is_none`, `== Some(`), assignments and snapshot copies stay allowed. The wider scan found five commands that hand-rolled the store's `target` rule (a `sketch` param or the sketch being edited). They now call `sketch_store::target`: sketch.inspect, sketch.glyphs, sketch.export_dxf, inspect.curvature_comb and inspect.minimum_radius (their `curves` form). Their refusals become target's: - no `sketch` and none being edited: "no sketch is being edited" (was "no such sketch (and none is active)", or "no such sketch" for sketch.glyphs); - an unknown name or id: "no sketch `X`" (an unknown id used to reach "that sketch is not evaluated"); - a feature that is not a sketch: "`X` is not a sketch"; - a `sketch` that is neither an id nor a name (true, a list, an object): refused, where it used to fall back to the sketch being edited. A null `sketch` still means none given (the scenario harness sends one): target now reads it that way for every sketch command (target_reads_a_null_sketch_as_none_given). No test, doc or schema text named the old wording; the params docs ("sketch?: id|name (default active)") still hold. The two remaining value reads, the default sketch for a feature (features.rs) and the sketch a measurement prefers (measure_sel.rs), go through `sketch_store::active`, with no change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Engine: a number in `sketch` is an exact sketch id, never a name (#5425, review of #6336) `sketch_store::target` turned a JSON number into text and looked it up with `Document::find_feature`, which falls back to a name when no feature has that id. So `{"sketch": 999999}` could pick a sketch named "999999" whose id is something else, and export or inspect it. sketch.export_dxf, sketch.glyphs and the two curvature inspects read an exact id before they moved onto the store; the other sketch commands (the old `target_sketch`) and sketch.inspect read a number as text. One rule now, for every command that takes `sketch`: a number is an exact id (`as_u64`, then the feature with that id); text is an id written out or a name, as before. A number that isn't a whole number of 0 or more (negative, fractional) is refused with "`sketch` must be an id or a name"; an id no feature has gives "no sketch `N`", as before. Nothing in the tests, docs, scenarios or examples names a sketch with digits, so nothing relied on the old fallback. Test (sketch_store): a sketch named "999999" with another id. sketch.export_dxf, sketch.glyphs (with another sketch being edited, for its enabled check), inspect.curvature_comb and inspect.minimum_radius (with a real curve id) refuse `{"sketch": 999999}`, find the sketch as `"999999"` and by its own id, and refuse -1 and 1.5. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Engine: MidPoint finds its sketch through the store too (#5425, after #5011) #5011 added a caller of the old `target_sketch` (MidPoint's `line_stays`, which swaps a point picked after its line) after this branch's base. It now reads the sketch through `sketch_store::target` and `sketch_store::read`, as the other sketch commands do, so a number there is an exact id too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Engine: standard parts fix their sketch's entities through the store (#5425, after #6376) #6376 (a standard part's sketches are fully defined) reads the sketch being drawn straight from the document's features, after this branch's base. `fix_all` now takes it from `sketch_store::active` and `sketch_store::read`, as the store's scan requires, with the same result. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Engine: Toggle Diameter and Delete on a profile find their sketch through the store (#5425) Two sketch commands landed on main after the store: sketch.toggle_diameter (#7729) still called the removed sketch::target_sketch, and Delete on a picked profile (#7107) read the sketch straight from the document. Both now go through sketch_store (target and read), and the store's source scan passes again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Sketch dimensioned: use the sketch store's target after the rebase Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Sketch dimensioned: read the sketch through the store Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: bherbruck <brennen.herbruck@gmail.com>
447 lines
22 KiB
Rust
447 lines
22 KiB
Rust
//! Inspection: curvature combs and minimum radius on sketch curves, model edges and faces;
|
|
//! centre of mass of bodies.
|
|
|
|
use serde_json::{Value, json};
|
|
use solidcraft_geom::{Aabb3, Seg2, Vec2, Vec3};
|
|
|
|
use super::CommandSpec;
|
|
use crate::params::{bad, num, string_list, vec3};
|
|
use crate::{EngineError, Result, Session};
|
|
|
|
pub static COMMANDS: &[CommandSpec] = &[
|
|
CommandSpec::new("inspect.curvature_comb", "Curvature Comb Analysis", curvature_comb)
|
|
.at("SKETCH", "INSPECT")
|
|
.icon("curvature_comb")
|
|
.noundo()
|
|
.params("curves?: [sketch curve ids] (sketch?: id|name, default active) | edges?: [[x,y,z] points on body edges] | faces?: [[x,y,z] points on faces] with count?: isoparametric curves each way (default 4; combs along the face's iso grid); density?: teeth per curve (default 40), scale?: comb length per unit curvature (default auto)"),
|
|
CommandSpec::new("inspect.minimum_radius", "Minimum Radius Analysis", minimum_radius)
|
|
.at("SKETCH", "INSPECT")
|
|
.icon("min_radius")
|
|
.noundo()
|
|
.params("curves?: [sketch curve ids] (sketch?) | edges?: [[x,y,z]…] | faces?: [[x,y,z]…] (default: every face of every body); the smallest radius of curvature of each and where it is"),
|
|
CommandSpec::new("inspect.isocurve", "Isocurve Analysis", isocurves)
|
|
.at("SKETCH", "INSPECT")
|
|
.icon("iso_analysis")
|
|
.noundo()
|
|
.params("faces: [[x,y,z]…] points on faces; count?: curves each way (default 8): the faces' isoparametric curves"),
|
|
CommandSpec::new("inspect.center_of_mass", "Center of Mass", center_of_mass)
|
|
.at("SKETCH", "INSPECT")
|
|
.icon("center_of_mass")
|
|
.noundo()
|
|
.params("bodies?: [names] (default all): the centre of mass (uniform density) of each and of all together"),
|
|
];
|
|
|
|
/// Curvature (signed, 1/mm) and unit normal of a segment at `t`.
|
|
fn seg_curvature(s: &Seg2, t: f64) -> (f64, Vec2) {
|
|
let d1 = s.derivative(t);
|
|
let h = 1e-5;
|
|
let (ta, tb) = ((t - h).max(0.0), (t + h).min(1.0));
|
|
let d2 = (s.derivative(tb) - s.derivative(ta)) / (tb - ta).max(1e-12);
|
|
let l = d1.len().max(1e-300);
|
|
let k = d1.cross(d2) / (l * l * l);
|
|
(k, d1.perp() / l)
|
|
}
|
|
|
|
/// Teeth along a 2D curve: (foot, curvature, normal).
|
|
fn teeth_2d(segs: &[Seg2], density: usize) -> Vec<(Vec2, f64, Vec2)> {
|
|
let per = density.div_ceil(segs.len().max(1)).max(2);
|
|
let mut out = Vec::new();
|
|
for s in segs {
|
|
for i in 0..=per {
|
|
let t = i as f64 / per as f64;
|
|
let (k, n) = seg_curvature(s, t);
|
|
out.push((s.point_at(t), k, n));
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Teeth along a 3D polyline (discrete curvature from three consecutive points).
|
|
fn teeth_3d(pts: &[Vec3]) -> Vec<(Vec3, f64, Vec3)> {
|
|
let mut out = Vec::new();
|
|
for w in pts.windows(3) {
|
|
let (a, b, c) = (w[0], w[1], w[2]);
|
|
let (ab, bc, ca) = (b - a, c - b, a - c);
|
|
let area2 = ab.cross(bc).len();
|
|
let den = ab.len() * bc.len() * ca.len();
|
|
let k = if den > 1e-300 { 2.0 * area2 / den } else { 0.0 };
|
|
// Towards the centre of curvature.
|
|
let n = (a + c - b * 2.0).normalized().unwrap_or(Vec3::ZERO);
|
|
out.push((b, k, n));
|
|
}
|
|
out
|
|
}
|
|
|
|
fn curvature_comb(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let cmd = "inspect.curvature_comb";
|
|
let density = num(p, "density").map(|d| d.clamp(2.0, 2000.0) as usize).unwrap_or(40);
|
|
let st = s.model.state();
|
|
let mut combs: Vec<(String, Vec<(Vec3, f64, Vec3)>)> = Vec::new();
|
|
let curves = string_list(cmd, p, "curves")?;
|
|
if !curves.is_empty() {
|
|
let id = super::sketch_store::target(s, p, cmd)?;
|
|
let ss = st.sketch(id).ok_or_else(|| EngineError::Other("that sketch is not evaluated".into()))?;
|
|
for c in curves.iter().take(1000) {
|
|
let ci = ss.sketch.curve_index(c).ok_or_else(|| bad(cmd, format!("unknown curve `{c}`")))?;
|
|
let segs = ss.sketch.exact_segs(ci).unwrap_or_else(|| ss.sketch.segs(ci));
|
|
let teeth = teeth_2d(&segs, density).into_iter().map(|(q, k, n)| (ss.plane.to_world(q), k, ss.plane.dir_to_world(n))).collect();
|
|
combs.push((c.clone(), teeth));
|
|
}
|
|
}
|
|
if let Some(edges) = p.get("edges").and_then(Value::as_array) {
|
|
for e in edges.iter().take(1000) {
|
|
let at = vec3(e).ok_or_else(|| bad(cmd, "`edges` must be points [x,y,z]"))?;
|
|
let mut best: Option<(f64, Vec<Vec3>)> = None;
|
|
for b in &st.bodies {
|
|
let m = b.mesh();
|
|
for (i, pts) in m.edges.iter().enumerate() {
|
|
if m.seams.get(i).copied().unwrap_or(false) {
|
|
continue;
|
|
}
|
|
let d = pts.windows(2).map(|w| at.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min);
|
|
if best.as_ref().is_none_or(|x| d < x.0) {
|
|
best = Some((d, pts.clone()));
|
|
}
|
|
}
|
|
}
|
|
let (_, pts) = best.ok_or_else(|| bad(cmd, "no edge there"))?;
|
|
combs.push((format!("edge@{},{},{}", at.x, at.y, at.z), teeth_3d(&pts)));
|
|
}
|
|
}
|
|
if let Some(faces) = p.get("faces") {
|
|
let faces = faces.as_array().filter(|a| !a.is_empty()).ok_or_else(|| bad(cmd, "`faces` must list points [x,y,z]"))?;
|
|
let count = match p.get("count") {
|
|
None | Some(Value::Null) => 4,
|
|
Some(_) => {
|
|
num(p, "count").filter(|c| c.is_finite()).map(|c| c.clamp(1.0, 50.0) as usize).ok_or_else(|| bad(cmd, "`count` must be a number"))?
|
|
}
|
|
};
|
|
for v in faces.iter().take(100) {
|
|
let at = vec3(v).ok_or_else(|| bad(cmd, "`faces` must list points [x,y,z]"))?;
|
|
let (bi, f) = face_at(&st, at).ok_or_else(|| bad(cmd, "no face there"))?;
|
|
let m = st.bodies.get(bi).map(|b| b.mesh()).ok_or_else(|| bad(cmd, "that face's body is not evaluated"))?;
|
|
for (k, w) in solidcraft_doc::iso_grid(&m, f, at, count).iter().enumerate() {
|
|
combs.push((format!("face@{},{},{}#{k}", at.x, at.y, at.z), teeth_3d(w)));
|
|
}
|
|
}
|
|
}
|
|
if combs.is_empty() {
|
|
return Err(bad(cmd, "give `curves`, `edges` or `faces`"));
|
|
}
|
|
// One scale for all combs: the longest tooth is a fifth of the largest curve's size.
|
|
let kmax = combs.iter().flat_map(|c| c.1.iter().map(|t| t.1.abs())).fold(0.0_f64, f64::max);
|
|
let bounds: Aabb3 = combs.iter().flat_map(|c| c.1.iter().map(|t| t.0)).collect();
|
|
let diag = bounds.diagonal();
|
|
let scale =
|
|
num(p, "scale").filter(|x| *x > 0.0).unwrap_or(if kmax > 1e-12 && !bounds.is_empty() && diag.is_finite() { 0.2 * diag / kmax } else { 1.0 });
|
|
let out: Vec<Value> = combs
|
|
.iter()
|
|
.map(|(id, teeth)| {
|
|
let lines: Vec<[[f64; 3]; 2]> = teeth.iter().map(|(q, k, n)| [(*q).into(), (*q - *n * (k * scale)).into()]).collect();
|
|
let kmax_c = teeth.iter().map(|t| t.1.abs()).fold(0.0_f64, f64::max);
|
|
json!({
|
|
"curve": id,
|
|
"teeth": lines,
|
|
"envelope": lines.iter().map(|l| l[1]).collect::<Vec<_>>(),
|
|
"max_curvature": kmax_c,
|
|
"min_radius": if kmax_c > 1e-12 { Value::from(1.0 / kmax_c) } else { Value::Null },
|
|
})
|
|
})
|
|
.collect();
|
|
Ok(json!({"combs": out, "scale": scale}))
|
|
}
|
|
|
|
/// Smallest radius along teeth: (radius, where), or None when straight.
|
|
fn min_of(teeth: &[(Vec3, f64, Vec3)]) -> Option<(f64, Vec3)> {
|
|
teeth.iter().filter(|t| t.1.abs() > 1e-9).max_by(|a, b| a.1.abs().total_cmp(&b.1.abs())).map(|t| (1.0 / t.1.abs(), t.0))
|
|
}
|
|
|
|
/// The face of a body at `at` (nearest triangle): (body index, face index).
|
|
fn face_at(st: &solidcraft_doc::ModelState, at: Vec3) -> Option<(usize, u32)> {
|
|
let mut best: Option<(f64, usize, u32)> = None;
|
|
for (bi, b) in st.bodies.iter().enumerate() {
|
|
let m = b.mesh();
|
|
for (ti, t) in m.triangles.iter().enumerate() {
|
|
let [a, bb, c] = t.map(|i| m.positions.get(i as usize).copied().unwrap_or_default());
|
|
let d = at.dist(closest_on_triangle(at, a, bb, c));
|
|
if best.is_none_or(|x| d < x.0) {
|
|
best = Some((d, bi, m.tri_face.get(ti).copied().unwrap_or(0)));
|
|
}
|
|
}
|
|
}
|
|
best.filter(|b| b.0 < 1.0).map(|b| (b.1, b.2))
|
|
}
|
|
|
|
fn closest_on_triangle(p: Vec3, a: Vec3, b: Vec3, c: Vec3) -> Vec3 {
|
|
// Project onto the plane, then clamp to the edges if outside.
|
|
let n = (b - a).cross(c - a);
|
|
let nn = n.dot(n);
|
|
if nn < 1e-300 {
|
|
return a;
|
|
}
|
|
let q = p - n * ((p - a).dot(n) / nn);
|
|
let inside = |u: Vec3, v: Vec3| (v - u).cross(q - u).dot(n) >= 0.0;
|
|
if inside(a, b) && inside(b, c) && inside(c, a) {
|
|
return q;
|
|
}
|
|
let seg = |u: Vec3, v: Vec3| {
|
|
let d = v - u;
|
|
let t = if d.dot(d) > 1e-300 { ((p - u).dot(d) / d.dot(d)).clamp(0.0, 1.0) } else { 0.0 };
|
|
u + d * t
|
|
};
|
|
[seg(a, b), seg(b, c), seg(c, a)].into_iter().min_by(|x, y| x.dist(p).total_cmp(&y.dist(p))).unwrap_or(a)
|
|
}
|
|
|
|
/// Smallest radius of curvature over a face of a mesh, from the turn of the vertex normals
|
|
/// along each triangle side: (radius, where).
|
|
fn face_min_radius(m: &solidcraft_geom::Mesh, face: u32) -> Option<(f64, Vec3)> {
|
|
let mut best: Option<(f64, Vec3)> = None;
|
|
for (ti, t) in m.triangles.iter().enumerate() {
|
|
if m.tri_face.get(ti) != Some(&face) {
|
|
continue;
|
|
}
|
|
for k in 0..3 {
|
|
let (i, j) = (t[k] as usize, t[(k + 1) % 3] as usize);
|
|
let (Some(pi), Some(pj), Some(ni), Some(nj)) = (m.positions.get(i), m.positions.get(j), m.normals.get(i), m.normals.get(j)) else {
|
|
continue;
|
|
};
|
|
let d = *pj - *pi;
|
|
let dd = d.dot(d);
|
|
if dd < 1e-18 {
|
|
continue;
|
|
}
|
|
let kappa = ((*nj - *ni).dot(d) / dd).abs();
|
|
if kappa > 1e-6 && best.is_none_or(|b| 1.0 / kappa < b.0) {
|
|
best = Some((1.0 / kappa, (*pi + *pj) * 0.5));
|
|
}
|
|
}
|
|
}
|
|
best
|
|
}
|
|
|
|
fn minimum_radius(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let cmd = "inspect.minimum_radius";
|
|
let st = s.model.state();
|
|
let mut items: Vec<(String, Option<(f64, Vec3)>)> = Vec::new();
|
|
let curves = string_list(cmd, p, "curves")?;
|
|
if !curves.is_empty() {
|
|
let id = super::sketch_store::target(s, p, cmd)?;
|
|
let ss = st.sketch(id).ok_or_else(|| EngineError::Other("that sketch is not evaluated".into()))?;
|
|
for c in curves.iter().take(1000) {
|
|
let ci = ss.sketch.curve_index(c).ok_or_else(|| bad(cmd, format!("unknown curve `{c}`")))?;
|
|
let segs = ss.sketch.exact_segs(ci).unwrap_or_else(|| ss.sketch.segs(ci));
|
|
let teeth: Vec<(Vec3, f64, Vec3)> =
|
|
teeth_2d(&segs, 400).into_iter().map(|(q, k, n)| (ss.plane.to_world(q), k, ss.plane.dir_to_world(n))).collect();
|
|
items.push((c.clone(), min_of(&teeth)));
|
|
}
|
|
}
|
|
if let Some(edges) = p.get("edges").and_then(Value::as_array) {
|
|
for e in edges.iter().take(1000) {
|
|
let at = vec3(e).ok_or_else(|| bad(cmd, "`edges` must be points [x,y,z]"))?;
|
|
let mut best: Option<(f64, Vec<Vec3>)> = None;
|
|
for b in &st.bodies {
|
|
let m = b.mesh();
|
|
for (i, pts) in m.edges.iter().enumerate() {
|
|
if m.seams.get(i).copied().unwrap_or(false) {
|
|
continue;
|
|
}
|
|
let d = pts.windows(2).map(|w| at.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min);
|
|
if best.as_ref().is_none_or(|x| d < x.0) {
|
|
best = Some((d, pts.clone()));
|
|
}
|
|
}
|
|
}
|
|
let (_, pts) = best.ok_or_else(|| bad(cmd, "no edge there"))?;
|
|
items.push((format!("edge@{},{},{}", at.x, at.y, at.z), min_of(&teeth_3d(&pts))));
|
|
}
|
|
}
|
|
let faces: Vec<Vec3> = match p.get("faces").and_then(Value::as_array) {
|
|
Some(a) => a.iter().take(1000).map(|v| vec3(v).ok_or_else(|| bad(cmd, "`faces` must be points [x,y,z]"))).collect::<Result<_>>()?,
|
|
None => Vec::new(),
|
|
};
|
|
for at in &faces {
|
|
let (bi, f) = face_at(&st, *at).ok_or_else(|| bad(cmd, "no face there"))?;
|
|
let m = st.bodies.get(bi).map(|b| b.mesh()).ok_or_else(|| bad(cmd, "body"))?;
|
|
items.push((format!("face@{},{},{}", at.x, at.y, at.z), face_min_radius(&m, f)));
|
|
}
|
|
if items.is_empty() {
|
|
// Every face of every body.
|
|
for b in &st.bodies {
|
|
let m = b.mesh();
|
|
let n = m.tri_face.iter().copied().max().map(|x| x + 1).unwrap_or(0);
|
|
for f in 0..n.min(100_000) {
|
|
items.push((format!("{}:face{f}", b.name), face_min_radius(&m, f)));
|
|
}
|
|
}
|
|
}
|
|
let overall = items.iter().filter_map(|i| i.1).min_by(|a, b| a.0.total_cmp(&b.0));
|
|
let fmt = |x: Option<(f64, Vec3)>| match x {
|
|
Some((r, at)) => json!({"min_radius": r, "at": [at.x, at.y, at.z]}),
|
|
None => json!({"min_radius": null}),
|
|
};
|
|
Ok(json!({
|
|
"items": items.iter().map(|(id, x)| { let mut v = fmt(*x); v["item"] = json!(id); v }).collect::<Vec<_>>(),
|
|
"min_radius": overall.map(|o| o.0),
|
|
"at": overall.map(|o| [o.1.x, o.1.y, o.1.z]),
|
|
}))
|
|
}
|
|
|
|
fn isocurves(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let cmd = "inspect.isocurve";
|
|
let count = num(p, "count").map(|c| c.clamp(1.0, 100.0) as usize).unwrap_or(8);
|
|
let faces = p.get("faces").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`faces` must list points [x,y,z]"))?;
|
|
if faces.is_empty() {
|
|
return Err(bad(cmd, "`faces` is empty"));
|
|
}
|
|
let st = s.model.state();
|
|
let mut out = Vec::new();
|
|
for v in faces.iter().take(100) {
|
|
let at = vec3(v).ok_or_else(|| bad(cmd, "`faces` must list points [x,y,z]"))?;
|
|
let (bi, f) = face_at(&st, at).ok_or_else(|| bad(cmd, "no face there"))?;
|
|
let m = st.bodies.get(bi).map(|b| b.mesh()).ok_or_else(|| bad(cmd, "body"))?;
|
|
for w in solidcraft_doc::iso_grid(&m, f, at, count) {
|
|
out.push(w.iter().map(|q| [q.x, q.y, q.z]).collect::<Vec<_>>());
|
|
}
|
|
}
|
|
Ok(json!({"curves": out}))
|
|
}
|
|
|
|
fn center_of_mass(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let cmd = "inspect.center_of_mass";
|
|
let names = string_list(cmd, p, "bodies")?;
|
|
// The world state, as Measure reads: placed occurrences where they are, each placement once.
|
|
let st = s.world_state();
|
|
let mut out = Vec::new();
|
|
let (mut vol, mut moment) = (0.0, Vec3::ZERO);
|
|
for b in st.bodies.iter().filter(|b| names.is_empty() || names.contains(&b.name)) {
|
|
let m = b.mesh().measure();
|
|
if !(m.volume.is_finite() && m.centroid.is_finite()) {
|
|
continue;
|
|
}
|
|
vol += m.volume;
|
|
moment += m.centroid * m.volume;
|
|
out.push(json!({"body": b.name, "center": [m.centroid.x, m.centroid.y, m.centroid.z], "volume": m.volume}));
|
|
}
|
|
if out.is_empty() {
|
|
return Err(bad(cmd, if names.is_empty() { "there are no bodies" } else { "no such bodies" }));
|
|
}
|
|
let c = if vol.abs() > 1e-300 { moment / vol } else { Vec3::ZERO };
|
|
Ok(json!({"center": [c.x, c.y, c.z], "volume": vol, "bodies": out}))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use serde_json::{Value, json};
|
|
|
|
use crate::Session;
|
|
|
|
#[test]
|
|
fn curvature_combs() {
|
|
let mut s = Session::default();
|
|
s.execute("sketch.create", &json!({"plane": "XY"})).unwrap();
|
|
let c = s.execute("sketch.circle.center", &json!({"center": [0, 0], "radius": 5})).unwrap()["curves"][0].clone();
|
|
let l = s.execute("sketch.line", &json!({"points": [[0, 20], [10, 20]]})).unwrap()["curves"][0].clone();
|
|
let r = s.execute("inspect.curvature_comb", &json!({"curves": [c, l], "density": 20})).unwrap();
|
|
let circle = &r["combs"][0];
|
|
assert!((circle["min_radius"].as_f64().unwrap() - 5.0).abs() < 1e-3, "{circle}");
|
|
assert!(r["combs"][1]["min_radius"].is_null(), "a line is straight");
|
|
// Circle teeth stand out on the convex side, away from the centre.
|
|
let t = &circle["teeth"][3];
|
|
let (a, b) = ((t[0][0].as_f64().unwrap(), t[0][1].as_f64().unwrap()), (t[1][0].as_f64().unwrap(), t[1][1].as_f64().unwrap()));
|
|
assert!(b.0 * b.0 + b.1 * b.1 > a.0 * a.0 + a.1 * a.1);
|
|
s.execute("sketch.finish", &json!({})).unwrap();
|
|
s.execute("solid.cylinder", &json!({"base": [50, 0, 0], "radius": 8, "height": 10})).unwrap();
|
|
let r = s.execute("inspect.curvature_comb", &json!({"edges": [[58, 0, 10]]})).unwrap();
|
|
assert!((r["combs"][0]["min_radius"].as_f64().unwrap() - 8.0).abs() < 0.5, "{r}");
|
|
assert!(s.execute("inspect.curvature_comb", &json!({})).is_err());
|
|
// Combs along the side face's isocurves: rings of radius 8 and straight lines along it.
|
|
let r = s.execute("inspect.curvature_comb", &json!({"faces": [[58, 0, 5]], "count": 3})).unwrap();
|
|
let combs = r["combs"].as_array().unwrap();
|
|
assert!(combs.len() >= 6, "{}", combs.len());
|
|
let rings = combs.iter().filter(|c| c["min_radius"].as_f64().is_some_and(|m| (m - 8.0).abs() < 0.5)).count();
|
|
let straight = combs.iter().filter(|c| c["min_radius"].is_null() || c["min_radius"].as_f64().is_some_and(|m| m > 1e3)).count();
|
|
assert!(rings >= 3 && straight >= 3, "{rings} rings, {straight} straight: {r}");
|
|
assert!(s.execute("inspect.curvature_comb", &json!({"faces": []})).is_err());
|
|
assert!(s.execute("inspect.curvature_comb", &json!({"faces": [[58, 0, 5]], "count": "x"})).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn minimum_radius_and_center_of_mass() {
|
|
let mut s = Session::default();
|
|
s.execute("sketch.create", &json!({"plane": "XY"})).unwrap();
|
|
let e = s.execute("sketch.ellipse", &json!({"center": [0, 0], "major": [10, 0], "minor_radius": 4})).unwrap()["curves"][0].clone();
|
|
// An ellipse's tightest bend is at the major axis ends: b²/a.
|
|
let r = s.execute("inspect.minimum_radius", &json!({"curves": [e]})).unwrap();
|
|
assert!((r["min_radius"].as_f64().unwrap() - 1.6).abs() < 1e-3, "{r}");
|
|
assert!((r["at"][0].as_f64().unwrap().abs() - 10.0).abs() < 0.1, "{r}");
|
|
s.execute("sketch.finish", &json!({})).unwrap();
|
|
s.execute("solid.cylinder", &json!({"base": [50, 0, 0], "radius": 8, "height": 10})).unwrap();
|
|
// The cylinder's side face: radius 8 (the mesh estimate is close).
|
|
let r = s.execute("inspect.minimum_radius", &json!({"faces": [[58, 0, 5]]})).unwrap();
|
|
assert!((r["min_radius"].as_f64().unwrap() - 8.0).abs() < 0.4, "{r}");
|
|
let r = s.execute("inspect.minimum_radius", &json!({})).unwrap();
|
|
assert!((r["min_radius"].as_f64().unwrap() - 8.0).abs() < 0.4, "{r}");
|
|
// Centre of mass: a box beside the cylinder.
|
|
s.execute("solid.box", &json!({"corner": [0, 0, 0], "length": 10, "width": 10, "height": 10})).unwrap();
|
|
let r = s.execute("inspect.center_of_mass", &json!({})).unwrap();
|
|
let (vb, vc) = (1000.0, std::f64::consts::PI * 640.0);
|
|
let want = (5.0 * vb + 50.0 * vc) / (vb + vc);
|
|
assert!((r["center"][0].as_f64().unwrap() - want).abs() < 0.1, "{r}");
|
|
assert!((r["center"][2].as_f64().unwrap() - 5.0).abs() < 0.05, "{r}");
|
|
assert!(s.execute("inspect.center_of_mass", &json!({"bodies": ["nope"]})).is_err());
|
|
// Isocurves on the cylinder's side: rings around it and lines along it.
|
|
let r = s.execute("inspect.isocurve", &json!({"faces": [[58, 0, 5]], "count": 4})).unwrap();
|
|
let curves = r["curves"].as_array().unwrap();
|
|
let ring =
|
|
|c: &Value| c.as_array().unwrap().iter().all(|q| ((q[0].as_f64().unwrap() - 50.0).hypot(q[1].as_f64().unwrap()) - 8.0).abs() < 0.2);
|
|
assert!(curves.len() >= 8, "{}", curves.len());
|
|
assert!(curves.iter().all(ring), "every curve lies on the cylinder");
|
|
let flat = |c: &Value| {
|
|
let z: Vec<f64> = c.as_array().unwrap().iter().map(|q| q[2].as_f64().unwrap()).collect();
|
|
z.iter().cloned().fold(f64::NEG_INFINITY, f64::max) - z.iter().cloned().fold(f64::INFINITY, f64::min) < 1e-6
|
|
};
|
|
assert!(curves.iter().filter(|c| flat(c)).count() >= 4, "rings at constant height");
|
|
assert!(s.execute("inspect.isocurve", &json!({"faces": []})).is_err());
|
|
}
|
|
|
|
/// #5246: the centre of mass of an assembly is the world's, like Measure's and Properties':
|
|
/// a moved occurrence where it is, a copy counted and found by its world name.
|
|
#[test]
|
|
fn center_of_mass_measures_occurrences_where_they_are_placed() {
|
|
let mut s = Session::default();
|
|
for (c, p) in [
|
|
("solid.box", json!({"length": 100, "width": 100, "height": 10, "body_name": "Plate"})),
|
|
("component.create", json!({"name": "Fixture"})),
|
|
("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [200, 0, 0], "body_name": "Block"})),
|
|
("component.activate", json!({"component": "root"})),
|
|
// The first part is grounded when it is made; this one is moved.
|
|
("occurrence.ground", json!({"occurrence": "Fixture:1", "grounded": false})),
|
|
("occurrence.move", json!({"occurrence": "Fixture:1", "translate": [0, 0, 100], "space": "world"})),
|
|
] {
|
|
s.execute(c, &p).unwrap_or_else(|e| panic!("{c}: {e}"));
|
|
}
|
|
let at = |r: &Value, k: usize| r["center"][k].as_f64().unwrap();
|
|
let r = s.execute("inspect.center_of_mass", &json!({"bodies": ["Block"]})).unwrap();
|
|
assert!((at(&r, 0) - 205.0).abs() < 1e-6 && (at(&r, 2) - 105.0).abs() < 1e-6, "{r}");
|
|
s.execute("occurrence.copy", &json!({"component": "Fixture", "translate": [0, 300, 0]})).unwrap();
|
|
let r = s.execute("inspect.center_of_mass", &json!({})).unwrap();
|
|
assert_eq!(r["bodies"].as_array().unwrap().len(), 3, "{r}");
|
|
assert!((r["volume"].as_f64().unwrap() - 102_000.0).abs() < 1e-6, "{r}");
|
|
// The same as Properties' mass centre: every body has the same density here.
|
|
let props = s.execute("component.properties", &json!({"component": "root"})).unwrap();
|
|
for k in 0..3 {
|
|
let want = props["total"]["center_of_mass"][k].as_f64().unwrap();
|
|
assert!((at(&r, k) - want).abs() < 1e-9, "{k}: {r} vs {props}");
|
|
}
|
|
let copy = r["bodies"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.find(|b| b["body"] != "Plate" && b["body"] != "Block")
|
|
.expect("the copy, by its world name")["body"]
|
|
.clone();
|
|
let r = s.execute("inspect.center_of_mass", &json!({"bodies": [copy]})).unwrap();
|
|
assert!((at(&r, 1) - 305.0).abs() < 1e-6, "{r}");
|
|
}
|
|
}
|