* claim: #8706 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Properties: measure faster, show progress, and stop when closed (#8706) Properties on a large assembly measured every placed copy of every body afresh (transform plus three fine tessellations each), so it took minutes. #5203 (in #8103) already moved the measurement beside the window; this builds on it. - A rigid placement reuses the body's own cached measurement: volume, area and counts unchanged, centre placed, box from the placed corners (quarter turns) or from the body's shared mesh placed (other turns). Scaled or mirrored placements are still measured as placed. - Bodies are grouped by component once and the subtree traversal groups occurrences by parent once (both were quadratic). - The measurement beside the window is watched by a Progress: the card says "Measuring... n of N bodies" with a bar, and closing it (or switching designs) cancels the worker at its next body instead of leaving it running. - component.properties and occurrence.properties are answered on a copy for control-channel requests too, as inspect.measure is. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Properties: count the measuring work instead of timing it in the reuse test (#8706) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"en": { "ui.properties.measuring_bodies": "Measuring… {done} of {total} bodies" },
|
||||
"ar": { "ui.properties.measuring_bodies": "جارٍ القياس… {done} من {total} من الأجسام" },
|
||||
"bs": { "ui.properties.measuring_bodies": "Mjerenje… {done} od {total} tijela" },
|
||||
"cs": { "ui.properties.measuring_bodies": "Měření… {done} z {total} těles" },
|
||||
"de": { "ui.properties.measuring_bodies": "Wird gemessen… {done} von {total} Körpern" },
|
||||
"es": { "ui.properties.measuring_bodies": "Midiendo… {done} de {total} cuerpos" },
|
||||
"fr": { "ui.properties.measuring_bodies": "Mesure en cours… {done} corps sur {total}" },
|
||||
"gl": { "ui.properties.measuring_bodies": "Medindo… {done} de {total} corpos" },
|
||||
"he": { "ui.properties.measuring_bodies": "מודד… {done} מתוך {total} גופים" },
|
||||
"hr": { "ui.properties.measuring_bodies": "Mjerenje… {done} od {total} tijela" },
|
||||
"hu": { "ui.properties.measuring_bodies": "Mérés… {done} / {total} test" },
|
||||
"id": { "ui.properties.measuring_bodies": "Mengukur… {done} dari {total} bodi" },
|
||||
"it": { "ui.properties.measuring_bodies": "Misurazione… {done} di {total} corpi" },
|
||||
"ja": { "ui.properties.measuring_bodies": "測定中… {total} 個中 {done} 個のボディ" },
|
||||
"ko": { "ui.properties.measuring_bodies": "측정 중… 바디 {total}개 중 {done}개" },
|
||||
"ms": { "ui.properties.measuring_bodies": "Mengukur… {done} daripada {total} jasad" },
|
||||
"nb": { "ui.properties.measuring_bodies": "Måler… {done} av {total} legemer" },
|
||||
"nl": { "ui.properties.measuring_bodies": "Meten… {done} van {total} lichamen" },
|
||||
"ro": { "ui.properties.measuring_bodies": "Se măsoară… {done} din {total} corpuri" },
|
||||
"ru": { "ui.properties.measuring_bodies": "Измерение… {done} из {total} тел" },
|
||||
"sr": { "ui.properties.measuring_bodies": "Мерење… {done} од {total} тела" },
|
||||
"sv": { "ui.properties.measuring_bodies": "Mäter… {done} av {total} kroppar" },
|
||||
"tr": { "ui.properties.measuring_bodies": "Ölçülüyor… {total} gövdeden {done} tanesi" },
|
||||
"uk": { "ui.properties.measuring_bodies": "Вимірювання… {done} з {total} тіл" },
|
||||
"vi": { "ui.properties.measuring_bodies": "Đang đo… {done} trên {total} thân khối" },
|
||||
"zh": { "ui.properties.measuring_bodies": "正在测量… 第 {done} 个,共 {total} 个实体" },
|
||||
"zh-TW": { "ui.properties.measuring_bodies": "正在測量… 第 {done} 個,共 {total} 個實體" }
|
||||
}
|
||||
@@ -47,8 +47,18 @@ fn placed_doc(s: &Session) -> Document {
|
||||
/// A property total must cover the entire assembly. The display traversal intentionally
|
||||
/// truncates hostile designs, so use an explicit error instead of accepting its prefix.
|
||||
pub(in crate::cmd) fn placements(doc: &Document, cmd: &str) -> Result<Vec<(u64, Vec<u64>, Mat)>> {
|
||||
let mut out = vec![(0, Vec::new(), solidcraft_doc::IDENTITY)];
|
||||
let mut stack = vec![(0, Vec::<u64>::new(), solidcraft_doc::IDENTITY)];
|
||||
subtree(doc, (0, Vec::new(), solidcraft_doc::IDENTITY), true, cmd)
|
||||
}
|
||||
|
||||
/// `root` and, with `descendants`, every placement under it, each with its world transform.
|
||||
/// The occurrences are grouped by parent once: searching all of them at every placement made a
|
||||
/// large assembly's traversal quadratic.
|
||||
fn subtree(doc: &Document, root: (u64, Vec<u64>, Mat), descendants: bool, cmd: &str) -> Result<Vec<(u64, Vec<u64>, Mat)>> {
|
||||
let mut out = vec![root.clone()];
|
||||
if !descendants {
|
||||
return Ok(out);
|
||||
}
|
||||
let mut stack = vec![root];
|
||||
let mut children: std::collections::BTreeMap<u64, Vec<_>> = std::collections::BTreeMap::new();
|
||||
for occurrence in &doc.occurrences {
|
||||
children.entry(occurrence.parent).or_default().push(occurrence);
|
||||
@@ -105,6 +115,95 @@ pub(super) fn occurrence(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The linear part of `m` is a rotation (no scale, shear or mirror), to rounding.
|
||||
fn proper_rotation(m: &Mat) -> bool {
|
||||
let column = |i: usize| m.get(i).map_or(Vec3::ZERO, |c| Vec3::new(c[0], c[1], c[2]));
|
||||
let (x, y, z) = (column(0), column(1), column(2));
|
||||
m.iter().flatten().all(|v| v.is_finite())
|
||||
&& [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
|
||||
&& x.cross(y).dot(z) > 0.0
|
||||
}
|
||||
|
||||
/// Every axis of `m` goes to an axis (a quarter turn, or none): a box turned so stays a box.
|
||||
fn square_to_axes(m: &Mat) -> bool {
|
||||
m.iter().take(3).all(|c| c.iter().take(3).filter(|v| v.abs() > 1e-12).count() == 1)
|
||||
}
|
||||
|
||||
/// The box around the corners of `b` placed by `m`.
|
||||
fn placed_box(m: &Mat, b: &Aabb3) -> Aabb3 {
|
||||
let mut out = Aabb3::EMPTY;
|
||||
if b.is_empty() {
|
||||
return out;
|
||||
}
|
||||
for i in 0..8 {
|
||||
let pick = |bit: usize, lo: f64, hi: f64| if i & bit == 0 { lo } else { hi };
|
||||
out.add(solidcraft_doc::apply_point(m, Vec3::new(pick(1, b.min.x, b.max.x), pick(2, b.min.y, b.max.y), pick(4, b.min.z, b.max.z))));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A body's measurements where a placement puts it.
|
||||
struct Placed {
|
||||
volume: f64,
|
||||
area: f64,
|
||||
centroid: Vec3,
|
||||
bbox: Aabb3,
|
||||
closed: bool,
|
||||
faces: usize,
|
||||
edges: usize,
|
||||
vertices: usize,
|
||||
}
|
||||
|
||||
/// `body` measured where `transform` places it. A rigid placement moves nothing but the centre
|
||||
/// and the box: the body's own measurement (worked out once and shared by every placement of it,
|
||||
/// [`solidcraft_doc::ModelBody::measure`]) is reused, where measuring each placed copy again took
|
||||
/// three fine tessellations per copy and made Properties of a large assembly take minutes
|
||||
/// (#8706). A placement that turns the body off the axes takes its box from the body's mesh
|
||||
/// placed there (shared with the display). Any other placement (scaled or mirrored) is measured
|
||||
/// as placed, as before.
|
||||
fn measure_placed(body: &solidcraft_doc::ModelBody, transform: Mat) -> Result<Placed> {
|
||||
if proper_rotation(&transform) {
|
||||
let m = body.measure()?;
|
||||
let bbox = if square_to_axes(&transform) {
|
||||
placed_box(&transform, &m.bbox)
|
||||
} else {
|
||||
let mesh = body.mesh();
|
||||
let mut b = Aabb3::EMPTY;
|
||||
for p in &mesh.positions {
|
||||
b.add(solidcraft_doc::apply_point(&transform, *p));
|
||||
}
|
||||
if b.is_empty() { placed_box(&transform, &m.bbox) } else { b }
|
||||
};
|
||||
return Ok(Placed {
|
||||
volume: m.volume,
|
||||
area: m.area,
|
||||
centroid: solidcraft_doc::apply_point(&transform, m.centroid),
|
||||
bbox,
|
||||
closed: crate::cmd::inspect::encloses_volume(&body.body),
|
||||
faces: m.merged.faces,
|
||||
edges: m.merged.edges,
|
||||
vertices: m.merged.vertices,
|
||||
});
|
||||
}
|
||||
#[cfg(test)]
|
||||
work::count(|w| w.placed_measures += 1);
|
||||
let placed = solidcraft_kernel::transform_matrix(&body.body, transform)?;
|
||||
let m = solidcraft_kernel::measure(&placed)?;
|
||||
Ok(Placed {
|
||||
volume: m.volume,
|
||||
area: m.area,
|
||||
centroid: m.centroid,
|
||||
bbox: m.bbox,
|
||||
closed: crate::cmd::inspect::encloses_volume(&placed),
|
||||
faces: m.merged.faces,
|
||||
edges: m.merged.edges,
|
||||
vertices: m.merged.vertices,
|
||||
})
|
||||
}
|
||||
|
||||
fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool, about: Option<Vec3>, cmd: &str) -> Result<Value> {
|
||||
let state = s.model.state();
|
||||
let mut bodies = Vec::new();
|
||||
@@ -115,48 +214,54 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool,
|
||||
let mut placement_count = 0;
|
||||
let mut skipped = 0;
|
||||
let selected_placements = if selected.is_empty() {
|
||||
if descendants { placements(doc, cmd)? } else { vec![(0, Vec::new(), solidcraft_doc::IDENTITY)] }
|
||||
subtree(doc, (0, Vec::new(), solidcraft_doc::IDENTITY), descendants, cmd)?
|
||||
} else {
|
||||
let placement = s.occurrence_placement(selected).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
let mut out = vec![(placement.component, selected.to_vec(), placement.world)];
|
||||
let mut stack = if descendants { out.clone() } else { Vec::new() };
|
||||
while let Some((component, path, transform)) = stack.pop() {
|
||||
for occurrence in doc.occurrences.iter().filter(|o| o.parent == component) {
|
||||
if path.len() >= 64 || out.len() >= 100_000 {
|
||||
return Err(bad(cmd, "assembly exceeds physical-properties traversal limits (64 levels or 100000 placements)"));
|
||||
}
|
||||
let mut child = path.clone();
|
||||
child.push(occurrence.id);
|
||||
let world = solidcraft_doc::mat_mul(&transform, &occurrence.transform);
|
||||
out.push((occurrence.component, child.clone(), world));
|
||||
stack.push((occurrence.component, child, world));
|
||||
}
|
||||
}
|
||||
out
|
||||
subtree(doc, (placement.component, selected.to_vec(), placement.world), descendants, cmd)?
|
||||
};
|
||||
// Each component's bodies (with their index in the model), the timeline looked up once rather
|
||||
// than for every body at every placement.
|
||||
let mut by_component: std::collections::HashMap<u64, Vec<(usize, &solidcraft_doc::ModelBody)>> = std::collections::HashMap::new();
|
||||
for (index, (body, component)) in state.bodies.iter().zip(doc.model_body_components(&state)).enumerate() {
|
||||
by_component.entry(component).or_default().push((index, body));
|
||||
}
|
||||
// How each closed body's volume spreads about its centre of mass (#8095): one tessellation
|
||||
// however often it is placed, which each placement then turns.
|
||||
let components: BTreeSet<u64> = selected_placements.iter().map(|(component, _, _)| *component).collect();
|
||||
let spread_bodies: Vec<usize> = (0..state.bodies.len())
|
||||
.filter(|&i| {
|
||||
state.bodies.get(i).is_some_and(|b| components.contains(&doc.model_body_component(b)) && crate::cmd::inspect::encloses_volume(&b.body))
|
||||
})
|
||||
let spread_bodies: Vec<usize> = components
|
||||
.iter()
|
||||
.filter_map(|c| by_component.get(c))
|
||||
.flatten()
|
||||
.filter(|(_, b)| crate::cmd::inspect::encloses_volume(&b.body))
|
||||
.map(|(i, _)| *i)
|
||||
.collect();
|
||||
#[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 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.
|
||||
let watch = solidcraft_kernel::watch::current();
|
||||
let total_bodies: usize = selected_placements.iter().map(|(c, _, _)| by_component.get(c).map_or(0, Vec::len)).sum();
|
||||
let mut done = 0;
|
||||
// Closed bodies' (mass, centre of mass, inertia about it), all in world axes.
|
||||
let mut parts: Vec<(f64, Vec3, Option<Tensor3>)> = Vec::new();
|
||||
for (component, path, transform) in selected_placements {
|
||||
placement_count += 1;
|
||||
for (index, body) in state.bodies.iter().enumerate().filter(|(_, b)| doc.model_body_component(b) == component) {
|
||||
for &(index, body) in by_component.get(&component).into_iter().flatten() {
|
||||
if let Some(w) = &watch {
|
||||
if w.cancelled() {
|
||||
return Err(bad(cmd, "cancelled"));
|
||||
}
|
||||
w.progress("measuring", done, total_bodies);
|
||||
}
|
||||
done += 1;
|
||||
let transform: Mat = doc.model_body_offset(body).map(|offset| solidcraft_doc::mat_mul(&transform, offset)).unwrap_or(transform);
|
||||
let placed = solidcraft_kernel::transform_matrix(&body.body, transform)?;
|
||||
let measured = solidcraft_kernel::measure(&placed)?;
|
||||
let measured = measure_placed(body, transform)?;
|
||||
let density = doc.density(&body.name);
|
||||
let body_mass = measured.volume * density / 1000.0;
|
||||
let closed = crate::cmd::inspect::encloses_volume(&placed);
|
||||
let closed = measured.closed;
|
||||
// The mesh's spread with the exact mass, so the tensor agrees with the mass shown.
|
||||
let body_inertia = spread
|
||||
.get(&index)
|
||||
@@ -173,9 +278,9 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool,
|
||||
}
|
||||
area += measured.area;
|
||||
bounds = bounds.union(&measured.bbox);
|
||||
faces += measured.merged.faces;
|
||||
edges += measured.merged.edges;
|
||||
vertices += measured.merged.vertices;
|
||||
faces += measured.faces;
|
||||
edges += measured.edges;
|
||||
vertices += measured.vertices;
|
||||
bodies.push(json!({"name": body.name, "component": component, "path": path,
|
||||
"material": doc.body_material(&body.name),
|
||||
"closed": closed, "density_g_cm3": closed.then_some(density),
|
||||
@@ -185,6 +290,9 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool,
|
||||
"bbox": {"min": measured.bbox.min, "max": measured.bbox.max}}));
|
||||
}
|
||||
}
|
||||
if let Some(w) = &watch {
|
||||
w.progress("measuring", done, total_bodies);
|
||||
}
|
||||
if !(volume.is_finite() && area.is_finite() && mass.is_finite() && moment.is_finite()) {
|
||||
return Err(bad(cmd, "physical properties exceed supported numeric range"));
|
||||
}
|
||||
@@ -217,6 +325,46 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool,
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The tessellating work a properties command did on this thread, for tests: placed copies
|
||||
/// measured afresh (transformed, then tessellated) and bodies whose inertia spread was
|
||||
/// tessellated. Counted where the work is asked for, on the command's own thread.
|
||||
#[cfg(test)]
|
||||
pub(super) mod work {
|
||||
use std::cell::Cell;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct Work {
|
||||
pub placed_measures: usize,
|
||||
pub spreads: usize,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static WORK: Cell<Work> = const { Cell::new(Work { placed_measures: 0, spreads: 0 }) };
|
||||
}
|
||||
|
||||
pub(super) fn count(f: impl FnOnce(&mut Work)) {
|
||||
WORK.with(|w| {
|
||||
let mut work = w.get();
|
||||
f(&mut work);
|
||||
w.set(work);
|
||||
});
|
||||
}
|
||||
|
||||
/// `f`'s result and the work it did.
|
||||
pub fn capture<T>(f: impl FnOnce() -> T) -> (T, Work) {
|
||||
let before = WORK.with(Cell::get);
|
||||
let out = f();
|
||||
let after = WORK.with(Cell::get);
|
||||
(
|
||||
out,
|
||||
Work {
|
||||
placed_measures: after.placed_measures.saturating_sub(before.placed_measures),
|
||||
spreads: after.spreads.saturating_sub(before.spreads),
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "component_properties_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -422,3 +422,82 @@ fn configurations_switch_to_a_user_defined_material() {
|
||||
run(&mut s, "material.delete", json!({"material": "Black Walnut", "replace": "Default"}));
|
||||
assert!(!s.doc.materials.contains_key("Slat"));
|
||||
}
|
||||
|
||||
/// #8706: Properties of a large assembly took minutes because every placed copy of a body was
|
||||
/// transformed and measured again (three fine tessellations each). Every placement of a body now
|
||||
/// reuses one measurement of it: 41 placements measure no placed copy afresh and tessellate
|
||||
/// each distinct body's inertia spread (#8095) once, exactly as one placement does, and the
|
||||
/// answer is the same when measured again.
|
||||
#[test]
|
||||
fn repeated_placements_reuse_one_measurement_of_their_body() {
|
||||
let mut s = Session::default();
|
||||
let (component, _, _) = box_in(&mut s, "Block");
|
||||
run(&mut s, "solid.cylinder", json!({"diameter": 4, "height": 30}));
|
||||
for i in 1..40 {
|
||||
run(&mut s, "occurrence.copy", json!({"component": component, "translate": [20 * i, 0, 0]}));
|
||||
}
|
||||
let turned = run(&mut s, "occurrence.copy", json!({"component": component, "translate": [0, 50, 0]}));
|
||||
run(&mut s, "occurrence.move", json!({"occurrence": turned["occurrence"], "translate": [0, 0, 0], "axis": [1, 1, 1], "angle": "30 deg"}));
|
||||
let first = run(&mut s, "component.properties", json!({"component": "root"}));
|
||||
assert_eq!(first["body_count"], 82, "{first}");
|
||||
let (again, all) = super::work::capture(|| run(&mut s, "component.properties", json!({"component": "root"})));
|
||||
assert_eq!(first, again);
|
||||
let (block, one) = super::work::capture(|| run(&mut s, "occurrence.properties", json!({"occurrence": turned["occurrence"]})));
|
||||
// Before, every placed copy was transformed and tessellated afresh (82 here); now no copy
|
||||
// is, and the work is the same for 41 placements as for one: one spread per distinct body.
|
||||
let per_body = super::work::Work { placed_measures: 0, spreads: 2 };
|
||||
assert_eq!(all, per_body, "41 placements");
|
||||
assert_eq!(one, per_body, "one placement");
|
||||
close(&first["total"]["volume_mm3"], 41.0 * block["total"]["volume_mm3"].as_f64().unwrap());
|
||||
}
|
||||
|
||||
/// #8706: a body measured where a rigid placement puts it, from its own measurement, matches its
|
||||
/// placed copy measured afresh: volume, area, centre and counts, and the box (to the chord of
|
||||
/// the meshes it is taken from) also when the placement turns it off the axes.
|
||||
#[test]
|
||||
fn a_placed_body_measures_as_its_placed_copy() {
|
||||
use solidcraft_geom::Vec3;
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.cylinder", json!({"diameter": 4, "height": 30}));
|
||||
run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 5}));
|
||||
let state = s.model.state();
|
||||
let placements = [
|
||||
solidcraft_doc::IDENTITY,
|
||||
solidcraft_doc::rigid(Vec3::new(5.0, -3.0, 7.0), Vec3::ZERO, Vec3::Z, std::f64::consts::FRAC_PI_2),
|
||||
solidcraft_doc::rigid(Vec3::new(100.0, 0.0, 0.0), Vec3::new(1.0, 2.0, 3.0), Vec3::new(1.0, 1.0, 1.0), 0.5),
|
||||
];
|
||||
for body in &state.bodies {
|
||||
for m in placements {
|
||||
let fast = super::measure_placed(body, m).unwrap();
|
||||
let placed = solidcraft_kernel::transform_matrix(&body.body, m).unwrap();
|
||||
let slow = solidcraft_kernel::measure(&placed).unwrap();
|
||||
let near = |a: f64, b: f64, tol: f64| assert!((a - b).abs() <= tol * b.abs().max(1.0), "{} {a} != {b}", body.name);
|
||||
near(fast.volume, slow.volume, 1e-4);
|
||||
near(fast.area, slow.area, 1e-4);
|
||||
assert!((fast.centroid - slow.centroid).len() < 1e-3, "{} centre {:?} != {:?}", body.name, fast.centroid, slow.centroid);
|
||||
let box_near = (fast.bbox.min - slow.bbox.min).len() < 0.05 && (fast.bbox.max - slow.bbox.max).len() < 0.05;
|
||||
assert!(box_near, "{} box {:?} != {:?}", body.name, fast.bbox, slow.bbox);
|
||||
assert_eq!((fast.faces, fast.edges, fast.vertices), (slow.merged.faces, slow.merged.edges, slow.merged.vertices));
|
||||
assert_eq!(fast.closed, crate::cmd::inspect::encloses_volume(&placed));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #8706: a window waiting for the properties sees how many bodies are measured and can stop the
|
||||
/// measuring part way.
|
||||
#[test]
|
||||
fn a_watcher_sees_the_bodies_measured_and_can_stop_them() {
|
||||
use std::sync::Arc;
|
||||
let mut s = Session::default();
|
||||
let (component, _, _) = box_in(&mut s, "Block");
|
||||
for i in 1..4 {
|
||||
run(&mut s, "occurrence.copy", json!({"component": component, "translate": [20 * i, 0, 0]}));
|
||||
}
|
||||
let progress = Arc::new(solidcraft_doc::progress::Progress::default());
|
||||
let r = solidcraft_doc::progress::watch(progress.clone(), || s.execute("component.properties", &json!({"component": "root"})));
|
||||
assert_eq!(r.unwrap()["body_count"], 4);
|
||||
assert_eq!(progress.work(), Some(("measuring", 4, 4)));
|
||||
progress.cancel();
|
||||
let stopped = solidcraft_doc::progress::watch(progress, || s.execute("component.properties", &json!({"component": "root"})));
|
||||
assert!(stopped.unwrap_err().to_string().contains("cancelled"));
|
||||
}
|
||||
|
||||
@@ -73,7 +73,15 @@ const ANSWERED_ON_A_COPY: &[&str] = &["file.export", "file.save_mesh"];
|
||||
/// body, an inspection that measures them, #4604; a clearance or interference check of every pair
|
||||
/// of bodies, minutes on an assembly of 150): they run on a copy too, whatever the preference,
|
||||
/// since an answer from the design as it was when asked has no order to keep.
|
||||
const READ_ON_A_COPY: &[&str] = &["inspect.measure", "document.inspect", "inspect.clearance", "inspect.interference"];
|
||||
const READ_ON_A_COPY: &[&str] = &[
|
||||
"inspect.measure",
|
||||
"document.inspect",
|
||||
"inspect.clearance",
|
||||
"inspect.interference",
|
||||
// Physical properties of a component or placement: every body of every placement (#8706).
|
||||
"component.properties",
|
||||
"occurrence.properties",
|
||||
];
|
||||
|
||||
/// Exports and readings computing at once; more run here.
|
||||
const MAX_ANSWERING: usize = 4;
|
||||
|
||||
@@ -9,9 +9,12 @@
|
||||
//! about; both are `ui_kit::Window` cards. While the card is open, [`overlay`] marks the centre
|
||||
//! of mass in the view with the principal axes standing out of it.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::{Align2, FontId, Stroke};
|
||||
use serde_json::{Map, Value, json};
|
||||
use solidcraft_engine::doc::metadata::{DESCRIPTION, Owner, keys};
|
||||
use solidcraft_engine::doc::progress::Progress;
|
||||
use solidcraft_engine::geom::Vec3;
|
||||
|
||||
use crate::SolveApp;
|
||||
@@ -127,12 +130,14 @@ pub fn open_object(app: &mut SolveApp, command: &str, params: &Value, fallback:
|
||||
close_object(app);
|
||||
// A large assembly takes seconds to measure, which froze the window (#5203): measured on a
|
||||
// copy beside it, the card shows when done. Headless and in tests (no wait set), here.
|
||||
// The worker reports how many bodies it has measured, and stops when the card closes (#8706).
|
||||
let progress = Arc::new(Progress::default());
|
||||
if let Some(wait) = app.apply_off_thread
|
||||
&& let Some(rx) = measure_beside(app.session.scratch(), command, params)
|
||||
&& let Some(rx) = measure_beside(app.session.scratch(), command, params, progress.clone())
|
||||
{
|
||||
match rx.recv_timeout(wait) {
|
||||
Ok(reply) => opened(app, reply, fallback),
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => app.menu.props_measuring = Some(Measuring { fallback, rx }),
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => app.menu.props_measuring = Some(Measuring { fallback, rx, progress }),
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => app.set_status(app.tr("ui.properties.measuring_failed").to_string(), true),
|
||||
}
|
||||
return;
|
||||
@@ -148,10 +153,27 @@ pub fn close_object(app: &mut SolveApp) {
|
||||
}
|
||||
|
||||
/// A Properties measurement running beside the window (#5203): the card's title when the reply
|
||||
/// has no name, and the reply to come.
|
||||
/// has no name, the reply to come, and how far the worker is (#8706).
|
||||
pub struct Measuring {
|
||||
fallback: String,
|
||||
rx: std::sync::mpsc::Receiver<Result<Value, String>>,
|
||||
/// The worker's progress; cancelling it stops the measuring at its next body.
|
||||
progress: Arc<Progress>,
|
||||
}
|
||||
|
||||
impl Measuring {
|
||||
/// Bodies measured so far and how many there are (none before the worker counts them).
|
||||
pub fn bodies(&self) -> Option<(usize, usize)> {
|
||||
self.progress.work().filter(|(stage, _, _)| *stage == "measuring").map(|(_, done, total)| (done, total))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Measuring {
|
||||
/// A card closed (or a design switched away from) stops its measuring, which on a large
|
||||
/// assembly would otherwise run on for minutes (#8706).
|
||||
fn drop(&mut self) {
|
||||
self.progress.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
/// Show `reply` in the card, titled with its name (else `fallback`); a refusal goes to the
|
||||
@@ -166,15 +188,22 @@ fn opened(app: &mut SolveApp, reply: Result<Value, String>, fallback: String) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `command` on `copy` on a worker; the reply comes on the returned channel.
|
||||
/// Run `command` on `copy` on a worker, watched by `progress`; the reply comes on the returned
|
||||
/// channel.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn measure_beside(mut copy: solidcraft_engine::Session, command: &str, params: &Value) -> Option<std::sync::mpsc::Receiver<Result<Value, String>>> {
|
||||
fn measure_beside(
|
||||
mut copy: solidcraft_engine::Session,
|
||||
command: &str,
|
||||
params: &Value,
|
||||
progress: Arc<Progress>,
|
||||
) -> Option<std::sync::mpsc::Receiver<Result<Value, String>>> {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let (command, params) = (command.to_string(), params.clone());
|
||||
std::thread::Builder::new()
|
||||
.name("properties".into())
|
||||
.spawn(move || {
|
||||
let _ = tx.send(copy.execute(&command, ¶ms).map_err(|e| e.to_string()));
|
||||
let reply = solidcraft_engine::doc::progress::watch(progress, || copy.execute(&command, ¶ms));
|
||||
let _ = tx.send(reply.map_err(|e| e.to_string()));
|
||||
})
|
||||
.ok()?;
|
||||
Some(rx)
|
||||
@@ -182,26 +211,40 @@ fn measure_beside(mut copy: solidcraft_engine::Session, command: &str, params: &
|
||||
|
||||
/// No threads on the web: measured here.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn measure_beside(_copy: solidcraft_engine::Session, _command: &str, _params: &Value) -> Option<std::sync::mpsc::Receiver<Result<Value, String>>> {
|
||||
fn measure_beside(
|
||||
_copy: solidcraft_engine::Session,
|
||||
_command: &str,
|
||||
_params: &Value,
|
||||
_progress: Arc<Progress>,
|
||||
) -> Option<std::sync::mpsc::Receiver<Result<Value, String>>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// While a measurement runs beside the window: a card saying so (Close drops it), and the
|
||||
/// Properties card in its place once the reply is in.
|
||||
fn show_measuring(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
let Some(m) = app.menu.props_measuring.take() else { return };
|
||||
let Some(mut m) = app.menu.props_measuring.take() else { return };
|
||||
match m.rx.try_recv() {
|
||||
Ok(reply) => return opened(app, reply, m.fallback),
|
||||
Ok(reply) => return opened(app, reply, std::mem::take(&mut m.fallback)),
|
||||
Err(std::sync::mpsc::TryRecvError::Disconnected) => return app.set_status(app.tr("ui.properties.measuring_failed").to_string(), true),
|
||||
Err(std::sync::mpsc::TryRecvError::Empty) => {}
|
||||
}
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(100));
|
||||
let (heading, text) = (app.tr("ui.properties").to_string(), app.tr("ui.properties.measuring").to_string());
|
||||
// How far it is, once the worker has counted the bodies (#8706).
|
||||
let bodies = m.bodies();
|
||||
let heading = app.tr("ui.properties").to_string();
|
||||
let text = match bodies {
|
||||
Some((done, total)) => crate::i18n::format("ui.properties.measuring_bodies", &[("done", &done.to_string()), ("total", &total.to_string())]),
|
||||
None => app.tr("ui.properties.measuring").to_string(),
|
||||
};
|
||||
let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_props"), "settings", &heading).actions("", "Close", None).show(ctx, true, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spinner();
|
||||
ui_kit::text(ui, &text, ui_kit::Text::Note("measuring"));
|
||||
});
|
||||
if let Some((done, total)) = bodies.filter(|(_, total)| *total > 0) {
|
||||
ui_kit::progress(ui, "properties_measuring", done as f32 / total as f32);
|
||||
}
|
||||
});
|
||||
if !(closed || action == ui_kit::Action::Cancel) {
|
||||
app.menu.props_measuring = Some(m);
|
||||
@@ -591,7 +634,7 @@ mod tests {
|
||||
assert_eq!(m.rx.recv().unwrap().unwrap(), here, "the copy measures what the design here does");
|
||||
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
h.app.menu.props_measuring = Some(super::Measuring { fallback: String::new(), rx });
|
||||
h.app.menu.props_measuring = Some(super::Measuring { fallback: String::new(), rx, progress: Default::default() });
|
||||
h.frames(2);
|
||||
assert!(h.widget("Measuring…").is_some() && h.app.menu.props.is_none());
|
||||
tx.send(Ok(here.clone())).unwrap();
|
||||
@@ -599,12 +642,54 @@ mod tests {
|
||||
assert_eq!(h.app.menu.props.as_ref().map(|(_, v)| v), Some(&here));
|
||||
assert!(h.widget("Moment of inertia").is_some());
|
||||
|
||||
// #8706: while it measures, the card says how many bodies are done, and Close stops the
|
||||
// worker rather than leaving it to measure on for minutes.
|
||||
let (_tx, rx) = std::sync::mpsc::channel::<Result<serde_json::Value, String>>();
|
||||
super::close_object(&mut h.app);
|
||||
h.app.menu.props_measuring = Some(super::Measuring { fallback: String::new(), rx });
|
||||
let progress = std::sync::Arc::new(solidcraft_engine::doc::progress::Progress::default());
|
||||
h.app.menu.props_measuring = Some(super::Measuring { fallback: String::new(), rx, progress: progress.clone() });
|
||||
solidcraft_engine::doc::progress::watch(progress.clone(), || {
|
||||
if let Some(w) = solidcraft_engine::kernel::watch::current() {
|
||||
w.progress("measuring", 3, 10);
|
||||
}
|
||||
});
|
||||
h.frames(2);
|
||||
assert!(h.widget("Measuring… 3 of 10 bodies").is_some());
|
||||
h.step(&json!({"widget": "Close"})).unwrap();
|
||||
assert!(h.app.menu.props_measuring.is_none() && h.app.menu.props.is_none(), "Close drops the measurement");
|
||||
assert!(progress.is_cancelled(), "Close stops the worker");
|
||||
}
|
||||
|
||||
/// #8706: Properties of an assembly from the Browser's menu returns at once with the card
|
||||
/// measuring on a copy, and the result (the same a script gets) fills it in.
|
||||
#[test]
|
||||
fn assembly_properties_from_the_menu_measure_off_the_window_thread() {
|
||||
let mut h = Harness::new();
|
||||
let block = h.app.run("component.create", json!({"name": "Block"})).unwrap()["component"].as_u64().unwrap();
|
||||
h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10})).unwrap();
|
||||
for i in 1..12 {
|
||||
h.app.run("occurrence.copy", json!({"component": block, "translate": [20 * i, 0, 0]})).unwrap();
|
||||
}
|
||||
h.app.apply_off_thread = Some(std::time::Duration::ZERO);
|
||||
let items = crate::context_menu::items(&h.app, &crate::context_menu::Target::Component { id: 0 });
|
||||
let item = items.iter().find(|i| i.label == "Properties").expect("Properties item");
|
||||
crate::context_menu::run_item(&mut h.app, item, egui::pos2(0.0, 0.0));
|
||||
assert!(h.app.menu.props_measuring.is_some(), "the menu returns at once, the card measuring");
|
||||
assert!(h.app.menu.props.is_none());
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(300);
|
||||
while h.app.menu.props.is_none() {
|
||||
assert!(std::time::Instant::now() < deadline, "the measurements never came in");
|
||||
assert!(h.app.menu.props_measuring.is_some(), "still measuring until the result is in");
|
||||
h.frames(1);
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
assert!(h.app.menu.props_measuring.is_none());
|
||||
let (title, v) = h.app.menu.props.clone().unwrap();
|
||||
assert_eq!(title, h.app.session.doc.name);
|
||||
assert_eq!(v["body_count"], 12);
|
||||
assert!((v["total"]["volume_mm3"].as_f64().unwrap() - 12_000.0).abs() < 1e-6, "{v}");
|
||||
let script = h.app.session.execute("component.properties", &json!({"component": 0})).unwrap();
|
||||
assert_eq!(v, script);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user