Compare commits

...
Author SHA1 Message Date
Phanoob d0a7c74ce5 Merge remote-tracking branch 'upstream/main' into rename-no-rebuild 2026-10-19 15:20:10 +02:00
takuto-NA b76302e850 Assembly: reuse reference meshes during rigid joint motion (#2922) (#2924)
Thanks @takuto-NA.
2026-10-19 09:15:26 -04:00
SS-EN 771f62be71 Interference: clear apart pairs from their meshes, intersect the rest in parallel, time budget (#2895)
Thanks @SS-EN.
2026-10-19 09:14:52 -04:00
fugazister aee47fca00 Messages window: keep status messages to read and copy again (#2763) (#2764)
Status messages are kept for the session in a Messages window (Help menu, or click the status chip), newest first, with Copy all.
2026-10-19 09:09:35 -04:00
PhanoobandClaude Opus 5.5 bd81c4622e Renaming a body or a feature builds nothing again (#3044)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:00:23 +02:00
The Nomad 4c30d944f5 3D mouse: only the window with focus moves (#2077) (#2212)
With two windows open, the 3D mouse now moves only the one with focus.
2026-10-19 08:48:06 -04:00
bherbruckandClaude Opus 5.5 5f399207bf CI: a translation change tests the UI and xtask, not the whole workspace (#3061)
assets/locales/ belongs to no crate, so affected.py selected the full
workspace (every crate, all four test shards) for a catalog-only PR. Only
solidcraft-ui-egui embeds the catalogs and xtask checks them; map the folder
to those two packages and their dependents.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 08:31:49 -04:00
SS-EN 7fd51ce6a5 timeline.roll_to: accept "end", refuse other non-number positions (#2902)
A position that is not a number or "end" is now refused instead of moving the marker to the end.
2026-10-19 08:18:01 -04:00
PhanoobandClaude Opus 5.5 95731a804a claim: #3044
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:00:32 +02:00
rlartot aef13b52f4 Pattern and Mirror copies of a primitive change only the seed's targets (#2755) (#2756)
Thanks @rlartot.
2026-10-19 07:44:40 -04:00
33 changed files with 1642 additions and 99 deletions

No files matched your search

+4 -1
View File
@@ -625,7 +625,10 @@ mod tests {
wheel: WheelGuard::default(),
started: now,
};
mouse.tick_at(&mut app, &Context::default(), now);
// A window that has run a frame with focus, as the app's always has by now.
let ctx = Context::default();
let _ = ctx.run_ui(egui::RawInput::default(), |_| {});
mouse.tick_at(&mut app, &ctx, now);
let DeviceMotion { motion, seconds } = app.viewport.device_motion.expect("the frame hands the page its motion");
assert_eq!(motion, Motion { translation: [0.0; 3], rotation: [0.0, 0.0, -1.0] });
assert!(seconds > 0.0);
+9
View File
@@ -687,6 +687,15 @@
"joint.from_bodies_hint": "Každé vybrané těleso se přesune do vlastní nové komponenty a zůstane na místě.",
"joint.one_body": "Oba výběry jsou na {body}. Druhý vyberte na jiném dílu.",
"joint.one_component": "Tyto díly jsou tělesy jedné komponenty: {bodies}. Kloub pohybuje jednou komponentou vůči druhé, takže každý díl potřebuje vlastní komponentu.",
"messages.ago_h": "před {n} h",
"messages.ago_min": "před {n} min",
"messages.ago_s": "před {n} s",
"messages.chip_hint": "Klikněte pro všechny zprávy této relace",
"messages.clear": "Vymazat",
"messages.copy_all": "Kopírovat vše",
"messages.menu": "Zprávy…",
"messages.none": "Zatím žádné zprávy.",
"messages.title": "Zprávy",
"nav.touchpad.help": "Podržením Shift a pohybem ukazatele posouváte; podržením Alt/Option a pohybem otáčíte. Tlačítko myši není potřeba. Svislé posouvání přibližuje.",
"nav.touchpad.label": "Touchpad",
"nav.touchpad.orbit": "Otáčení (podržte Alt/Option a pohybujte; bez tlačítka myši)",
+9
View File
@@ -719,6 +719,15 @@
"joint.from_bodies_hint": "Each picked body moves into a new component of its own and stays where it is.",
"joint.one_body": "Both picks are on {body}. Pick the second one on another part.",
"joint.one_component": "These parts are bodies of one component: {bodies}. A joint moves one component against another, so each part needs a component of its own.",
"messages.ago_h": "{n} h ago",
"messages.ago_min": "{n} min ago",
"messages.ago_s": "{n} s ago",
"messages.chip_hint": "Click for all messages of this session",
"messages.clear": "Clear",
"messages.copy_all": "Copy all",
"messages.menu": "Messages…",
"messages.none": "No messages yet.",
"messages.title": "Messages",
"motion.checked_to": "Checked to step {step} only: the check ran out of its work budget",
"motion.collision": "{a} · {b}: steps {steps}",
"motion.duration_hint": "seconds (empty: per step)",
+9
View File
@@ -704,6 +704,15 @@
"joint.from_bodies_hint": "Ogni corpo selezionato viene spostato in un nuovo componente distinto, mantenendo la sua posizione.",
"joint.one_body": "Entrambe le selezioni sono su {body}. Seleziona il secondo elemento su un'altra parte.",
"joint.one_component": "Queste parti sono corpi di un unico componente: {bodies}. Un giunto muove un componente rispetto a un altro, quindi ogni parte richiede un componente distinto.",
"messages.ago_h": "{n} h fa",
"messages.ago_min": "{n} min fa",
"messages.ago_s": "{n} s fa",
"messages.chip_hint": "Fai clic per tutti i messaggi di questa sessione",
"messages.clear": "Cancella",
"messages.copy_all": "Copia tutto",
"messages.menu": "Messaggi…",
"messages.none": "Ancora nessun messaggio.",
"messages.title": "Messaggi",
"motion.checked_to": "Controllato solo fino al passo {step}: il controllo ha esaurito il limite di calcolo",
"motion.collision": "{a} · {b}: passi {steps}",
"motion.duration_hint": "secondi (vuoto: per passo)",
+9
View File
@@ -719,6 +719,15 @@
"joint.from_bodies_hint": "選択した各ボディを、位置はそのままで専用の新しいコンポーネントに移動します。",
"joint.one_body": "両方の選択が {body} 上にあります。2 つ目は別の部品で選択してください。",
"joint.one_component": "これらの部品は 1 つのコンポーネントのボディです: {bodies}。ジョイントはコンポーネント同士を動かすため、部品ごとに専用のコンポーネントが必要です。",
"messages.ago_h": "{n} 時間前",
"messages.ago_min": "{n} 分前",
"messages.ago_s": "{n} 秒前",
"messages.chip_hint": "クリックするとこのセッションのすべてのメッセージを表示します",
"messages.clear": "クリア",
"messages.copy_all": "すべてコピー",
"messages.menu": "メッセージ…",
"messages.none": "まだメッセージはありません。",
"messages.title": "メッセージ",
"motion.checked_to": "ステップ {step} までしか確認していません: 確認の計算量の上限に達しました",
"motion.collision": "{a} · {b}: ステップ {steps}",
"motion.duration_hint": "秒 (空欄: ステップごと)",
+9
View File
@@ -719,6 +719,15 @@
"joint.from_bodies_hint": "每个所选实体移入各自的新组件,位置保持不变。",
"joint.one_body": "两次选择都在 {body} 上。请在另一个零件上选择第二个。",
"joint.one_component": "这些零件是同一组件的实体:{bodies}。接头使一个组件相对另一个组件运动,因此每个零件都需要自己的组件。",
"messages.ago_h": "{n} 小时前",
"messages.ago_min": "{n} 分钟前",
"messages.ago_s": "{n} 秒前",
"messages.chip_hint": "点击查看本次会话的所有消息",
"messages.clear": "清除",
"messages.copy_all": "全部复制",
"messages.menu": "消息…",
"messages.none": "暂无消息。",
"messages.title": "消息",
"motion.checked_to": "仅检查到第 {step} 步:检查已用完其工作量上限",
"motion.collision": "{a} · {b}:第 {steps} 步",
"motion.duration_hint": "秒(留空:按步)",
+175 -6
View File
@@ -1,5 +1,8 @@
//! Timeline evaluation.
#[path = "placed_mesh.rs"]
mod placed_mesh;
use std::collections::BTreeMap;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, OnceLock};
@@ -28,6 +31,8 @@ pub struct ModelBody {
// Timeline snapshots are cloned before meshes are requested. Share the cell itself so
// meshing any snapshot also warms every unchanged copy of this body.
mesh: Arc<OnceLock<Arc<Mesh>>>,
/// Lazy canonical reference triangles for a proper rigid occurrence placement.
mesh_placement: Option<Arc<placed_mesh::PlacedMesh>>,
/// The display plan (none when the body has no plan: a mesh body, or one the planner
/// refuses), shared like the mesh. A GPU viewport draws it.
plan: Arc<[OnceLock<Option<Arc<TessPlan>>>; 4]>,
@@ -61,6 +66,7 @@ impl ModelBody {
body,
feature,
mesh: Arc::new(OnceLock::new()),
mesh_placement: None,
plan: Arc::new(Default::default()),
plan_mesh: Arc::new(Default::default()),
key: 0,
@@ -83,9 +89,10 @@ impl ModelBody {
// finding their surface, picks naming their face, sketch planes), and a different
// triangulation moved those and changed what designs build. A GPU viewport draws the
// plan ([`ModelBody::display_plan`]).
self.mesh
.get_or_init(|| Arc::new(self.body.reference_display_mesh_angular(self.display_tol(), kernel::DISPLAY_ANGLE).unwrap_or_default()))
.clone()
match self.mesh_placement.as_deref() {
Some(placed) => self.mesh.get_or_init(|| placed.mesh()).clone(),
None => placed_mesh::reference_mesh(&self.body, &self.mesh, self.display_tol()),
}
}
/// The display plan of this body at the viewport's display quality
@@ -145,9 +152,10 @@ impl ModelBody {
Some((Arc::new(plan), Arc::new(mesh)))
}
/// The chord tolerance of [`ModelBody::mesh`] (mm): 1/1000 of the body's size, at least 1 µm.
/// The chord tolerance of [`ModelBody::mesh`] (mm): 1/1000 of the definition's size, at least
/// 1 µm. Proper rigid placements retain that tolerance along with the reference triangles.
pub fn display_tol(&self) -> f64 {
(self.body.size() * 1e-3).max(1e-3)
self.mesh_placement.as_ref().map(|placed| placed.tolerance).unwrap_or_else(|| (self.body.size() * 1e-3).max(1e-3))
}
/// Already computed display geometry; saving must not trigger cold tessellation.
@@ -1398,6 +1406,156 @@ impl Model {
self.last_recomputed = recomputed;
self.last_restored = restored;
}
/// The model after body `old` was renamed `new`, `before` and `after` being the document
/// either side of the rename, without building anything again (#3044): a rename changes no
/// geometry, but it changes the features that name the body, and so every fingerprint from
/// the body's feature on, and `evaluate` would rebuild all of them. Here each result keeps its
/// geometry and takes the new name (its bodies, threads and sheets, and its sketches' links
/// where the rename changed them), and its fingerprint is worked out on `after`, so the next
/// `evaluate` reuses it.
///
/// `false`, with the model as it was, where a full evaluation might name something else
/// differently: a body whose name was made from `old` at evaluation (`old (2)` or `old'`, a
/// piece split off it) and isn't kept in its feature's names, a body already called `new`
/// at some step, a component's placed body, a message that names `old`, or results that
/// don't match the timeline. The caller then evaluates.
pub fn rename_body(&mut self, before: &Document, after: &Document, old: &str, new: &str) -> bool {
if self.no_cache || old == new || self.results.len() != after.features.len() || before.features.len() != after.features.len() {
return false;
}
let made_from_old = |name: &str| name.strip_prefix(old).is_some_and(|rest| rest.starts_with(" (") || rest.starts_with('\''));
let kept = |b: &ModelBody| after.feature(b.feature).is_some_and(|f| f.body_names.contains(&b.name));
let names_old = |m: &Option<String>| m.as_deref().is_some_and(|m| m.contains(old));
for (r, f) in self.results.iter().zip(&after.features) {
if r.id != f.id || r.stale || names_old(&r.error) || names_old(&r.warning) {
return false;
}
if r.state.bodies.iter().any(|b| b.name == new || b.source_name.is_some() || (made_from_old(&b.name) && !kept(b))) {
return false;
}
}
// The links the rename changed, by sketch feature and link id: their new source and names.
let mut links: std::collections::HashMap<(u64, &str), &solidcraft_sketch::Link> = std::collections::HashMap::new();
for (fb, fa) in before.features.iter().zip(&after.features) {
if let (FeatureKind::Sketch { sketch: sb, .. }, FeatureKind::Sketch { sketch: sa, .. }) = (&fb.kind, &fa.kind) {
for (lb, la) in sb.links.iter().zip(&sa.links) {
if lb.id == la.id && (lb.source != la.source || lb.face_name != la.face_name || lb.edge_name != la.edge_name) {
links.insert((fa.id, la.id.as_str()), la);
}
}
}
}
let rename = |st: &ModelState| -> Option<ModelState> {
let sketch_changed = |sk: &SolvedSketch| sk.sketch.links.iter().any(|l| links.contains_key(&(sk.feature, l.id.as_str())));
let touched = st.bodies.iter().any(|b| b.name == old)
|| st.threads.iter().any(|t| t.body == old)
|| st.sheets.iter().any(|sh| sh.body == old)
|| st.sketches.iter().any(|sk| sketch_changed(sk));
if !touched {
return None;
}
let mut st = st.clone();
for b in st.bodies.iter_mut().filter(|b| b.name == old) {
b.name = new.to_string();
}
for t in st.threads.iter_mut().filter(|t| t.body == old) {
t.body = new.to_string();
}
for sh in st.sheets.iter_mut().filter(|sh| sh.body == old) {
sh.body = new.to_string();
}
for sk in &mut st.sketches {
if sketch_changed(sk) {
let solved = Arc::make_mut(sk);
for l in &mut solved.sketch.links {
if let Some(la) = links.get(&(solved.feature, l.id.as_str())) {
l.source = la.source.clone();
l.face_name.clone_from(&la.face_name);
l.edge_name.clone_from(&la.edge_name);
}
}
}
}
Some(st)
};
self.renamed(after, rename);
true
}
/// The model after feature `id` was renamed `old` to `new` in `after`, without building
/// anything again (#3044), as [`Model::rename_body`]: the feature's result, its solved
/// sketch and its construction geometry take the new name. `false`, with the model as it
/// was, where an evaluation might name something else differently: a body, thread or sheet
/// whose name holds `old`, a message that names it, or results that don't match the timeline.
pub fn rename_feature(&mut self, after: &Document, id: u64, old: &str, new: &str) -> bool {
if self.no_cache || old == new || old.is_empty() || self.results.len() != after.features.len() {
return false;
}
let names_old = |m: &Option<String>| m.as_deref().is_some_and(|m| m.contains(old));
for (r, f) in self.results.iter().zip(&after.features) {
if r.id != f.id || r.stale || names_old(&r.error) || names_old(&r.warning) {
return false;
}
let st = &r.state;
if st.bodies.iter().any(|b| b.name.contains(old) || b.source_name.as_deref().is_some_and(|n| n.contains(old)))
|| st.threads.iter().any(|t| t.body.contains(old))
|| st.sheets.iter().any(|sh| sh.body.contains(old))
{
return false;
}
}
let rename = |st: &ModelState| -> Option<ModelState> {
let touched =
st.sketches.iter().any(|sk| sk.feature == id && sk.name == old) || st.construct.iter().any(|c| c.feature == id && c.name == old);
if !touched {
return None;
}
let mut st = st.clone();
for sk in st.sketches.iter_mut().filter(|sk| sk.feature == id && sk.name == old) {
new.clone_into(&mut Arc::make_mut(sk).name);
}
for c in st.construct.iter_mut().filter(|c| c.feature == id && c.name == old) {
new.clone_into(&mut c.name);
}
Some(st)
};
self.renamed(after, rename);
for r in self.results.iter_mut().filter(|r| r.id == id) {
new.clone_into(&mut r.name);
}
true
}
/// Each result with its state as `rename` makes it (`None`: as it was) and its fingerprint
/// worked out on `after`, so the next `evaluate` reuses it; nothing is built.
fn renamed(&mut self, after: &Document, rename: impl Fn(&ModelState) -> Option<ModelState>) {
let (vals, _) = evaluation_values(after);
let steps = StepDigests::of(after, &self.step_digests);
let marker = after.marker.unwrap_or(usize::MAX);
// Results share their states (a feature that changes nothing passes its input on): each
// state is renamed once.
let mut done: std::collections::HashMap<*const ModelState, Arc<ModelState>> = std::collections::HashMap::new();
let mut prev_fp = 0u64;
let mut out = Vec::with_capacity(self.results.len());
for (i, (r, f)) in self.results.iter().zip(&after.features).enumerate() {
let fp = chain_fingerprint(after, &vals, f, prev_fp, i >= marker, &steps);
prev_fp = fp;
let state = match done.get(&Arc::as_ptr(&r.state)) {
Some(s) => s.clone(),
None => {
let s = rename(&r.state).map_or_else(|| r.state.clone(), Arc::new);
done.insert(Arc::as_ptr(&r.state), s.clone());
s
}
};
out.push(FeatureResult { fingerprint: fp, state, ..r.clone() });
}
self.step_digests = steps;
self.results = out;
self.last_recomputed = 0;
self.last_restored = 0;
}
}
/// Key of the design's length unit (mm per unit) among the values (no parameter can be named
@@ -4356,6 +4514,9 @@ fn replay(
continue;
}
let (op, targets) = feature_op(src);
// A primitive's or a hole's targets are its participants (#1108): the copies change
// those bodies only, like the feature itself (#2755).
let targets = if targets.is_empty() { src.participants.clone() } else { targets };
let mut copies = Vec::new();
if let FeatureKind::Hole { diameter, depth, hole, to, .. } = &src.kind {
// A hole is drilled again at each copy of its spot (found on the surface there), so
@@ -5707,11 +5868,19 @@ impl PlacedBodies {
Some((_, placed)) => {
let mut fresh = ModelBody::new(name, placed.body.clone(), b.feature);
fresh.mesh = placed.mesh.clone();
fresh.mesh_placement = placed.mesh_placement.clone();
fresh.plan = placed.plan.clone();
fresh.plan_mesh = placed.plan_mesh.clone();
fresh
}
None => ModelBody::new(name, kernel::transform_matrix(&b.body, *m).unwrap_or_else(|_| b.body.clone()), b.feature),
None => match kernel::transform_matrix(&b.body, *m) {
Ok(body) => {
let mut fresh = ModelBody::new(name, body, b.feature);
fresh.mesh_placement = placed_mesh::PlacedMesh::new(b, m).map(Arc::new);
fresh
}
Err(_) => ModelBody::new(name, b.body.clone(), b.feature),
},
}
}
}
+144
View File
@@ -0,0 +1,144 @@
//! Reference triangles belong to a definition, even while its occurrences move. Keep one lazy
//! source mesh and map it into each pose; retain the exact placed B-rep separately in ModelBody.
use std::sync::{Arc, OnceLock};
use solidcraft_geom::{Mesh, Vec3};
use solidcraft_kernel::{self as kernel, Body};
use super::ModelBody;
#[derive(Debug)]
pub(super) struct PlacedMesh {
body: Body,
mesh: Arc<OnceLock<Arc<Mesh>>>,
transform: crate::Mat,
pub(super) tolerance: f64,
}
impl PlacedMesh {
/// Share the original definition, never a chain of previously placed meshes. A source's
/// OnceLock lives with its immutable geometry, so edits get a new source automatically.
pub(super) fn new(source: &ModelBody, transform: &crate::Mat) -> Option<Self> {
if !proper_rigid(transform) {
return None;
}
Some(match source.mesh_placement.as_deref() {
Some(original) => Self {
body: original.body.clone(),
mesh: original.mesh.clone(),
transform: crate::mat_mul(transform, &original.transform),
tolerance: original.tolerance,
},
None => Self { body: source.body.clone(), mesh: source.mesh.clone(), transform: *transform, tolerance: source.display_tol() },
})
}
pub(super) fn mesh(&self) -> Arc<Mesh> {
let source = reference_mesh(&self.body, &self.mesh, self.tolerance);
Arc::new(Mesh {
positions: source.positions.iter().map(|p| crate::apply_point(&self.transform, *p)).collect(),
normals: source.normals.iter().map(|n| crate::apply_vector(&self.transform, *n)).collect(),
edges: source.edges.iter().map(|edge| edge.iter().map(|p| crate::apply_point(&self.transform, *p)).collect()).collect(),
triangles: source.triangles.clone(),
tri_face: source.tri_face.clone(),
edge_faces: source.edge_faces.clone(),
seams: source.seams.clone(),
smooth_edges: source.smooth_edges.clone(),
sharp_edges: source.sharp_edges.clone(),
})
}
}
pub(super) fn reference_mesh(body: &Body, mesh: &OnceLock<Arc<Mesh>>, tolerance: f64) -> Arc<Mesh> {
mesh.get_or_init(|| Arc::new(body.reference_display_mesh_angular(tolerance, kernel::DISPLAY_ANGLE).unwrap_or_default())).clone()
}
/// Only proper rotations and translations preserve triangle winding, normal lengths and the
/// reference chord tolerance. Scale, shear, reflection and malformed matrices use the mesher.
fn proper_rigid(m: &crate::Mat) -> bool {
if m.iter().flatten().any(|v| !v.is_finite()) || m[0][3] != 0. || m[1][3] != 0. || m[2][3] != 0. || m[3][3] != 1. {
return false;
}
let [x, y, z] = [Vec3::new(m[0][0], m[0][1], m[0][2]), Vec3::new(m[1][0], m[1][1], m[1][2]), Vec3::new(m[2][0], m[2][1], m[2][2])];
[x, y, z].iter().all(|v| (v.dot(*v) - 1.).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) - 1.).abs() < 1e-9
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn placed_mesh_is_lazy_and_composes_from_one_immutable_source() {
let source = ModelBody::new("Part".into(), kernel::box_solid(Vec3::ZERO, Vec3::new(2., 3., 4.)).unwrap(), 1);
let a = crate::rigid(Vec3::new(10., 20., 30.), Vec3::ZERO, Vec3::Z, 0.7);
let b = crate::rigid(Vec3::new(3., -5., 2.), Vec3::ZERO, Vec3::X, 0.4);
let mut first = ModelBody::new("First".into(), kernel::transform_matrix(&source.body, a).unwrap(), 1);
first.mesh_placement = Some(Arc::new(PlacedMesh::new(&source, &a).unwrap()));
let mut nested = ModelBody::new("Nested".into(), kernel::transform_matrix(&first.body, b).unwrap(), 1);
nested.mesh_placement = Some(Arc::new(PlacedMesh::new(&first, &b).unwrap()));
assert_eq!(first.display_tol(), source.display_tol());
assert_eq!(nested.display_tol(), source.display_tol());
assert!(source.cached_mesh().is_none());
assert!(first.cached_mesh().is_none());
let mesh = nested.mesh();
assert!(source.cached_mesh().is_some(), "the canonical source is warmed on demand");
assert!(first.cached_mesh().is_none(), "composition does not retain or evaluate intermediate poses");
let local = source.mesh();
let matrix = crate::mat_mul(&b, &a);
for (p, q) in local.positions.iter().zip(&mesh.positions) {
assert!(crate::apply_point(&matrix, *p).dist(*q) < 1e-8);
}
let (other, work) = kernel::profile::capture(|| first.mesh());
assert_eq!(work.tessellate_ms, 0.);
assert_eq!(other.tri_face, local.tri_face);
assert!(Arc::ptr_eq(&mesh, &nested.mesh()));
}
#[test]
fn world_instances_warm_one_definition_and_an_edit_replaces_it() {
let mut doc = crate::Document::new("instances");
let component = doc.add_component(Some("Part"), 0).unwrap();
doc.body_components.insert("Pin".into(), component);
let first = doc.occurrences[0].id;
doc.occurrences[0].transform = crate::rigid(Vec3::new(10., 0., 0.), Vec3::ZERO, Vec3::Y, 0.3);
doc.add_occurrence(component, 0, crate::rigid(Vec3::new(0., 20., 0.), Vec3::ZERO, Vec3::X, 0.6)).unwrap();
let mut state = crate::ModelState::default();
state.bodies.push(ModelBody::new("Pin".into(), kernel::cylinder(Vec3::ZERO, Vec3::Z, 2., 8.).unwrap(), 1));
let mut cache = super::super::PlacedBodies::default();
let before = super::super::world_state_reusing(&doc, &state, &mut cache);
assert!(state.bodies[0].cached_mesh().is_none(), "placing bodies must remain lazy");
let old = before.bodies[0].mesh();
assert!(state.bodies[0].cached_mesh().is_some());
let (_, work) = kernel::profile::capture(|| before.bodies[1].mesh());
assert_eq!(work.tessellate_ms, 0., "the second instance shares the first one's triangulation");
doc.occurrences.iter_mut().find(|o| o.id == first).unwrap().transform = crate::rigid(Vec3::new(30., 0., 0.), Vec3::ZERO, Vec3::Y, 0.9);
let moved = super::super::world_state_reusing(&doc, &state, &mut cache);
let (_, work) = kernel::profile::capture(|| moved.bodies[0].mesh());
assert_eq!(work.tessellate_ms, 0., "a new pose shares the same definition");
state.bodies[0] = ModelBody::new("Pin".into(), kernel::cylinder(Vec3::ZERO, Vec3::Z, 4., 8.).unwrap(), 1);
let edited = super::super::world_state_reusing(&doc, &state, &mut cache);
assert!(state.bodies[0].cached_mesh().is_none());
let new = edited.bodies[0].mesh();
assert!(state.bodies[0].cached_mesh().is_some(), "changed geometry warms its new definition cache");
assert_ne!(new.bounds(), moved.bodies[0].mesh().bounds());
assert!(Arc::ptr_eq(&old, &before.bodies[0].mesh()), "editing does not mutate older snapshots");
}
#[test]
fn only_proper_rigid_affine_matrices_reuse_reference_meshes() {
let source = ModelBody::new("Part".into(), kernel::box_solid(Vec3::ZERO, Vec3::new(2., 3., 4.)).unwrap(), 1);
assert!(PlacedMesh::new(&source, &crate::IDENTITY).is_some());
for (col, row, value) in [(0, 0, -1.), (0, 0, 2.), (0, 1, 0.5), (0, 3, 0.1), (3, 3, 2.), (3, 0, f64::NAN), (3, 2, f64::INFINITY)] {
let mut matrix = crate::IDENTITY;
matrix[col][row] = value;
assert!(PlacedMesh::new(&source, &matrix).is_none(), "{matrix:?}");
}
// A positive unit determinant alone is insufficient: this scale changes normals and tolerance.
let mut scale = crate::IDENTITY;
scale[0][0] = 2.;
scale[1][1] = 0.5;
assert!(PlacedMesh::new(&source, &scale).is_none());
}
}
+170
View File
@@ -1182,3 +1182,173 @@ mod tests {
assert_eq!(s.visibility.hidden_folders, vec!["o:4/sketches".to_string()]);
}
}
/// #3044: a rename builds nothing again. The model the rename leaves is the one a full
/// evaluation of the renamed design gives, whether it took the new name in place or, where it
/// can't tell, evaluated.
#[cfg(test)]
mod rename_tests {
use serde_json::{Value, json};
use crate::Session;
fn run(s: &mut Session, id: &str, p: Value) -> Value {
match s.execute(id, &p) {
Ok(v) => v,
Err(e) => panic!("{id} {p}: {e}"),
}
}
/// What a later feature or the view reads from a state: its bodies (name, feature, volume),
/// threads, sheets and sketch link sources.
fn summary(st: &solidcraft_doc::ModelState) -> String {
let bodies: Vec<String> = st
.bodies
.iter()
.map(|b| format!("{} f{} {:.6}", b.name, b.feature, solidcraft_kernel::measure(&b.body).map(|m| m.volume).unwrap_or(f64::NAN)))
.collect();
let threads: Vec<&str> = st.threads.iter().map(|t| t.body.as_str()).collect();
let sheets: Vec<&str> = st.sheets.iter().map(|t| t.body.as_str()).collect();
let links: Vec<String> = st
.sketches
.iter()
.flat_map(|sk| sk.sketch.links.iter().map(move |l| format!("{}:{} {:?} {:?} {:?}", sk.feature, l.id, l.source, l.face_name, l.edge_name)))
.collect();
let sketches: Vec<String> = st.sketches.iter().map(|sk| format!("{} {}", sk.feature, sk.name)).collect();
let construct: Vec<String> = st.construct.iter().map(|c| format!("{} {}", c.feature, c.name)).collect();
format!("{bodies:?} {threads:?} {sheets:?} {links:?} {sketches:?} {construct:?}")
}
/// Rename body `old` to `new`; whether that built nothing again. The model then is the one a
/// full evaluation (no cache) of the renamed design gives, feature by feature.
fn rename(s: &mut Session, old: &str, new: &str) -> bool {
renamed_like_evaluated(s, "body.rename", json!({"body": old, "name": new}))
}
/// Rename feature `old` to `new`, as `rename` does a body.
fn rename_feature(s: &mut Session, old: &str, new: &str) -> bool {
renamed_like_evaluated(s, "timeline.rename", json!({"feature": old, "name": new}))
}
fn renamed_like_evaluated(s: &mut Session, id: &str, p: Value) -> bool {
let evaluations = s.evaluations;
run(s, id, p);
let in_place = s.evaluations == evaluations;
let mut fresh = Session::new((*s.doc).clone());
fresh.model.no_cache = true;
fresh.refresh();
assert_eq!(s.model.results.len(), fresh.model.results.len());
for (r, f) in s.model.results.iter().zip(&fresh.model.results) {
assert_eq!((&r.name, &r.error, &r.warning, r.skipped), (&f.name, &f.error, &f.warning, f.skipped), "feature {}", r.name);
assert_eq!(summary(&r.state), summary(&f.state), "after feature {}", r.name);
}
// And the next evaluation reuses every result.
s.refresh();
assert_eq!(s.model.last_recomputed, 0, "a rename leaves results the next evaluation rebuilds");
in_place
}
#[test]
fn renaming_the_sensor_enclosures_bodies_builds_nothing() {
let mut s = Session::default();
let script: Value = serde_json::from_str(include_str!("../../../../examples/acceptance/sensor_enclosure.json")).unwrap();
s.run_script(&script).unwrap();
assert!(rename(&mut s, "Case", "Shell"));
assert!(rename(&mut s, "Lid", "Cover"));
// Undo puts the old names back, as it puts back any edit.
run(&mut s, "edit.undo", json!({}));
assert!(s.model.state().body("Lid").is_some());
}
/// A body a later feature names, and a sketch on its face whose links name it; the copies a
/// pattern made of another body, renamed one by one.
#[test]
fn a_rename_follows_users_face_sketches_and_copies_without_building() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "operation": "new_body", "body_name": "X"}));
run(&mut s, "solid.pattern.rectangular", json!({"bodies": ["X"], "dir1": [1, 0, 0], "count1": 3, "spacing1": 20}));
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [0, 30, 0], "operation": "new_body", "body_name": "Y"}));
run(&mut s, "solid.move", json!({"bodies": ["Y"], "translate": [0, 0, 5]}));
run(&mut s, "sketch.create", json!({"plane": {"face": [5, 35, 15]}}));
run(&mut s, "sketch.circle.center", json!({"center": [5, 35], "radius": 2}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": -3, "operation": "cut", "profiles": [{"point": [5, 35]}]}));
assert!(rename(&mut s, "Y", "Stand"));
let st = s.model.state();
let named = st.sketches.iter().flat_map(|sk| &sk.sketch.links).filter(|l| format!("{:?}", l.source).contains("\"Stand\"")).count();
assert!(named > 0, "the face sketch's links name the renamed body");
assert!(rename(&mut s, "X (3)", "Last"));
assert!(rename(&mut s, "X (2)", "Middle"));
}
/// The copies a pattern makes are named after their body when the pattern is evaluated:
/// renaming the body renames them, so it evaluates, and gives what an evaluation gives.
#[test]
fn a_patterned_body_is_renamed_by_evaluating() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "operation": "new_body", "body_name": "X"}));
run(&mut s, "solid.pattern.rectangular", json!({"bodies": ["X"], "dir1": [1, 0, 0], "count1": 3, "spacing1": 20}));
assert!(!rename(&mut s, "X", "Base"));
let names: Vec<String> = s.model.state().bodies.iter().map(|b| b.name.clone()).collect();
assert_eq!(names, ["Base", "Base (2)", "Base (3)"]);
}
/// Features renamed: a sketch later features use, and a construction plane a sketch is on (by
/// name). Their results, solved sketches and planes take the new name; nothing is built.
#[test]
fn renaming_features_builds_nothing() {
let mut s = Session::default();
let script: Value = serde_json::from_str(include_str!("../../../../examples/acceptance/sensor_enclosure.json")).unwrap();
s.run_script(&script).unwrap();
let sketch = s.doc.features.iter().find(|f| matches!(f.kind, solidcraft_doc::FeatureKind::Sketch { .. })).unwrap().name.clone();
assert!(rename_feature(&mut s, &sketch, "Outline"));
let mut s = Session::default();
run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": 5, "name": "Shelf"}));
run(&mut s, "sketch.create", json!({"plane": "Shelf"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 4}));
assert!(rename_feature(&mut s, "Shelf", "Ledge"));
}
/// Folders and components renamed: what they name isn't geometry, and the evaluation that
/// follows reuses every result.
#[test]
fn renaming_folders_and_components_builds_nothing() {
let mut s = Session::default();
let part = run(&mut s, "component.create", json!({"name": "Part"}))["component"].as_u64().unwrap();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "name": "First", "body_name": "A"}));
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0], "name": "Second", "body_name": "B"}));
let folder = run(&mut s, "browser.group", json!({"folder": "bodies", "items": ["A"]}))["group"].as_u64().unwrap();
let features = run(&mut s, "timeline.group", json!({"name": "Pair", "features": ["First", "Second"]}))["group"].as_u64().unwrap();
for (id, p) in [
("browser.rename_group", json!({"group": folder, "name": "Fasteners"})),
("timeline.rename_group", json!({"group": features, "name": "Both"})),
("component.rename", json!({"component": part, "name": "Bracket"})),
] {
run(&mut s, id, p);
assert_eq!(s.model.last_recomputed, 0, "{id} built something again");
}
}
/// A body named like a feature: an evaluation may name it after the feature, so renaming the
/// feature evaluates, and gives what an evaluation gives.
#[test]
fn a_feature_a_body_is_named_like_is_renamed_by_evaluating() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "name": "Block", "body_name": "Block"}));
assert!(!rename_feature(&mut s, "Block", "Brick"));
}
/// A body split later: the pieces are named after it when the split is evaluated, so the
/// rename evaluates, and gives what an evaluation gives.
#[test]
fn a_body_split_later_is_renamed_by_evaluating() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 20, "width": 10, "height": 10, "operation": "new_body", "body_name": "Block"}));
run(&mut s, "solid.split_body", json!({"body": "Block", "plane": {"origin": [10, 0, 0], "normal": [1, 0, 0]}}));
let names: Vec<String> = s.model.state().bodies.iter().map(|b| b.name.clone()).collect();
assert!(names.iter().any(|n| n.starts_with("Block (")), "{names:?}");
assert!(!rename(&mut s, "Block", "Beam"));
}
}
+13 -3
View File
@@ -41,9 +41,9 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("timeline.move_many", "Move Timeline Items", move_many).icon("reorder").params(
"features?: [id|name], groups?: [folder ids], group?: folder id, position: insertion slot; atomically changes folder membership and moves all selected contents as one block",
),
CommandSpec::new("timeline.rollback", "Move Timeline Marker", rollback).icon("rollback").params("position: number of features to keep active (omit = end)"),
CommandSpec::new("timeline.rollback", "Move Timeline Marker", rollback).icon("rollback").params("position: number of features to keep active, or \"end\" (omit = end)"),
CommandSpec::new("timeline.roll_to", "Roll History Marker", rollback).icon("rollback")
.params("position: number of features to keep active (omit = end) | feature: id|name (the marker goes right after it)"),
.params("position: number of features to keep active, or \"end\" (omit = end) | feature: id|name (the marker goes right after it)"),
CommandSpec::new("timeline.reorder", "Reorder Feature", reorder).icon("reorder")
.params("feature: id|name, position: its new index; refused when a feature that worked would fail"),
CommandSpec::new("timeline.reorder_many", "Reorder Features", reorder_many).icon("reorder").params(
@@ -509,7 +509,17 @@ fn rollback(s: &mut Session, p: &Value) -> Result<Value> {
let id = feature_id(s, Some(f), "timeline.roll_to")?;
s.doc.feature_index(id).map(|i| i + 1)
}
None => num(p, "position").map(|x| x.max(0.0) as usize),
// A number of features, or "end" (as omitting it); anything else is refused rather than
// read as "end".
None => match p.get("position") {
None | Some(Value::Null) => None,
Some(Value::String(t)) if t.trim().eq_ignore_ascii_case("end") => None,
Some(v) => {
let x = v.as_f64().or_else(|| v.as_str().and_then(|t| t.trim().parse::<f64>().ok())).and_then(crate::params::finite);
let why = "`position` must be a number of features to keep active, or \"end\"";
Some(x.map(|x| x.max(0.0) as usize).ok_or_else(|| bad("timeline.roll_to", why))?)
}
},
};
s.doc_mut().marker = match pos {
Some(k) if k < n => Some(k),
+22
View File
@@ -8,6 +8,28 @@ fn run(s: &mut Session, id: &str, params: Value) -> Value {
s.execute(id, &params).unwrap_or_else(|e| panic!("{id} {params}: {e}"))
}
/// `timeline.roll_to` takes a number of features or "end"; any other value is refused instead of
/// silently moving the marker to the end.
#[test]
fn roll_to_takes_a_number_or_end_and_refuses_anything_else() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10}));
run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 20, "operation": "join"}));
for cmd in ["timeline.roll_to", "timeline.rollback"] {
assert_eq!(run(&mut s, cmd, json!({"position": 1}))["marker"], 1);
assert_eq!(run(&mut s, cmd, json!({"position": "end"}))["marker"], 2);
assert_eq!(run(&mut s, cmd, json!({"position": "1"}))["marker"], 1, "a number in a string is still a number");
assert_eq!(run(&mut s, cmd, json!({"position": "END"}))["marker"], 2);
run(&mut s, cmd, json!({"position": 1}));
for bad in [json!("start"), json!("first"), json!([1]), json!({"n": 1}), json!(true), json!("NaN")] {
let e = s.execute(cmd, &json!({"position": bad})).unwrap_err().to_string();
assert!(e.contains("`position` must be a number") && e.contains("\"end\""), "{bad}: {e}");
assert_eq!(s.doc.marker, Some(1), "{bad}: the refused call left the marker where it was");
}
assert_eq!(run(&mut s, cmd, json!({}))["marker"], 2, "omitted: the end");
}
}
#[test]
fn g2_fillet_survives_edit_undo_and_reopen() {
use solidcraft_doc::{Document, FeatureKind, FilletStyle};
+439
View File
@@ -0,0 +1,439 @@
//! Interference (`inspect.interference`): the pairs of bodies that share volume, and how much.
//!
//! Pairs are pruned in three steps before anything exact runs. Their boxes first (sort and
//! sweep), then their display meshes: a mesh lies within its chord tolerance of the faces, so
//! two meshes farther apart than a margin over both tolerances belong to bodies whose boundaries
//! don't meet, and unless one body sits inside the other (a point of each face of one tested
//! against the other's mesh) the pair is clear without a boolean. The pairs left are intersected
//! exactly and measured, in parallel on desktop (one after another in the browser), the slowest
//! first, under a time budget: pairs not finished when it runs out are listed as not checked
//! rather than holding the call. The shared part is measured as `solidcraft_kernel::measure`
//! measures it (its mass properties alone).
use std::collections::HashSet;
use std::sync::Arc;
use serde_json::{Value, json};
use solidcraft_geom::mesh_distance::TriangleSet;
use solidcraft_geom::{Aabb3, Mesh, Vec3};
use solidcraft_kernel::Body;
use solidcraft_kernel::profile::KernelTimes;
use crate::params::{bad, num, string_list};
use crate::{Result, Session};
/// Most pairs with overlapping bounding boxes one call intersects.
pub(crate) const MAX_INTERFERENCE_PAIRS: usize = 20_000;
/// The time budget when the call gives none (s): under the 300 s an MCP client waits for a tool.
pub(crate) const DEFAULT_BUDGET_S: f64 = 240.0;
/// The longest time budget a call may ask for (s).
const MAX_BUDGET_S: f64 = 86_400.0;
/// How many chord tolerances apart (of both meshes together) two meshes must be to clear a pair
/// without intersecting it: twice what the tolerances allow, for meshers that sag a little more.
const MESH_MARGIN: f64 = 4.0;
/// Most pairs listed under `slowest`.
const SLOWEST: usize = 8;
/// One pair to intersect exactly: the bodies (cheap clones sharing the solids) and their names.
struct Job {
pair: usize,
a: Body,
b: Body,
names: (String, String),
/// Faces of one times faces of the other: the slowest pairs start first.
cost: usize,
}
/// What an exact check of one pair came to.
enum Outcome {
Hit(Value),
Clear,
Unchecked(String),
}
/// One pair's answer and where its time went.
struct Done {
outcome: Outcome,
/// Unverified boolean results are listed as unchecked and still reported as a hit.
note: Option<String>,
ms: f64,
kernel: KernelTimes,
}
pub(super) fn interference(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "inspect.interference";
let started = web_time::Instant::now();
let budget_s = match p.get("budget_s") {
None | Some(Value::Null) => DEFAULT_BUDGET_S,
Some(_) => match num(p, "budget_s") {
Some(v) if v > 0.0 && v <= MAX_BUDGET_S => v,
_ => return Err(bad(cmd, format!("`budget_s` must be a number of seconds above 0, at most {MAX_BUDGET_S}"))),
},
};
let budget = std::time::Duration::from_secs_f64(budget_s);
let want = string_list(p, "bodies");
let st = s.world_state();
let bodies: Vec<&solidcraft_doc::ModelBody> =
st.bodies.iter().filter(|b| want.is_empty() || want.contains(&b.name)).filter(|b| !b.body.is_mesh()).collect();
// The bodies' display meshes, made once (in parallel) and kept on the bodies: a design open
// in the app has them already.
let meshes: Vec<Arc<Mesh>> = {
let made = solidcraft_kernel::map_with_local_pools(&bodies, usize::MAX, |b| Ok(b.mesh()));
made.into_iter().map(|m| m.unwrap_or_default()).collect()
};
// Prune by bounding boxes first (sort and sweep), so the cost follows the pairs that can
// touch rather than the square of the body count.
// Each mesh lies within its chord of the faces, inside a round one: grown by that, the boxes
// of bodies a hundredth of a millimetre into each other still meet (an arm's round end into a
// rounded rim, its facets clear of the rim's).
let chords: Vec<f64> = bodies.iter().map(|b| b.display_tol()).collect();
let boxes: Vec<Aabb3> = meshes
.iter()
.zip(&chords)
.map(|(m, &chord)| {
let (bx, g) = (m.bounds(), 2.0 * chord);
if bx.is_empty() { bx } else { Aabb3 { min: bx.min - Vec3::new(g, g, g), max: bx.max + Vec3::new(g, g, g) } }
})
.collect();
let (pairs, skipped) = super::joints::overlapping_pairs(&boxes, MAX_INTERFERENCE_PAIRS);
// Then by the meshes: pairs whose meshes stay apart (and neither holds the other) are clear.
let used: Vec<bool> = {
let mut u = vec![false; bodies.len()];
for &(i, j) in &pairs {
for k in [i, j] {
if let Some(x) = u.get_mut(k) {
*x = true;
}
}
}
u
};
let sets: Vec<Option<TriangleSet>> = {
let idx: Vec<usize> = (0..bodies.len()).filter(|&i| used.get(i).copied().unwrap_or(false)).collect();
let made = solidcraft_kernel::map_with_local_pools(&idx, usize::MAX, |&i| Ok(meshes.get(i).map(|m| TriangleSet::new(m))));
let mut out: Vec<Option<TriangleSet>> = std::iter::repeat_with(|| None).take(bodies.len()).collect();
for (&i, set) in idx.iter().zip(made) {
if let (Some(slot), Ok(set)) = (out.get_mut(i), set) {
*slot = set;
}
}
out
};
let need_exact = solidcraft_kernel::map_with_local_pools(&pairs, usize::MAX, |&(i, j)| {
let (Some(Some(sa)), Some(Some(sb)), Some(ma), Some(mb)) = (sets.get(i), sets.get(j), meshes.get(i), meshes.get(j)) else {
return Ok(true);
};
let margin = MESH_MARGIN * (chords.get(i).copied().unwrap_or(0.0) + chords.get(j).copied().unwrap_or(0.0));
Ok(!meshes_apart(ma, sa, mb, sb, margin))
});
let mut jobs = Vec::new();
let mut cleared = 0usize;
for (k, (&(i, j), exact)) in pairs.iter().zip(need_exact).enumerate() {
if !exact.unwrap_or(true) {
cleared += 1;
continue;
}
let (Some(a), Some(b)) = (bodies.get(i), bodies.get(j)) else { continue };
jobs.push(Job {
pair: k,
a: a.body.clone(),
b: b.body.clone(),
names: (a.name.clone(), b.name.clone()),
cost: a.body.face_count().saturating_mul(b.body.face_count()),
});
}
let intersected = jobs.len();
jobs.sort_by(|x, y| y.cost.cmp(&x.cost).then(x.pair.cmp(&y.pair)));
let left = budget.saturating_sub(started.elapsed());
let waited = web_time::Instant::now();
let (done, threads) = run_jobs(jobs, left);
let waited_ms = waited.elapsed().as_secs_f64() * 1000.0;
let (mut hits, mut unchecked, mut timed) = (Vec::new(), Vec::new(), Vec::new());
let (mut not_checked, mut boolean_ms, mut tessellate_ms) = (0usize, 0.0, 0.0);
for ((a, b), d) in done {
let Some(d) = d else {
not_checked += 1;
unchecked.push(json!({"a": a, "b": b, "reason": format!("not checked: the time budget of {budget_s} s ran out (budget_s)")}));
continue;
};
boolean_ms += d.kernel.boolean_ms;
tessellate_ms += d.kernel.tessellate_ms;
timed.push((
d.ms,
json!({"a": a, "b": b, "ms": round_ms(d.ms), "boolean_ms": round_ms(d.kernel.boolean_ms),
"tessellate_ms": round_ms(d.kernel.tessellate_ms)}),
));
if let Some(reason) = d.note {
unchecked.push(json!({"a": a, "b": b, "reason": reason}));
}
match d.outcome {
Outcome::Hit(v) => hits.push(v),
Outcome::Clear => {}
Outcome::Unchecked(reason) => unchecked.push(json!({"a": a, "b": b, "reason": reason})),
}
}
// A timing profile of the command (`--profile`) counts the kernel time the workers spent,
// shared out over the time this thread waited for them (on the calling thread it is counted
// already).
if threads > 0 && boolean_ms + tessellate_ms > 0.0 {
let share = (waited_ms / (boolean_ms + tessellate_ms)).min(1.0);
solidcraft_kernel::profile::credit(KernelTimes { boolean_ms: boolean_ms * share, tessellate_ms: tessellate_ms * share });
}
timed.sort_by(|x, y| y.0.total_cmp(&x.0));
let slowest: Vec<Value> = timed.into_iter().take(SLOWEST).map(|t| t.1).collect();
Ok(json!({
"interferences": hits, "count": hits.len(), "checked": bodies.len(), "unchecked": unchecked,
"truncated": skipped > 0, "skipped_pairs": skipped,
"pairs_candidate": pairs.len(), "pairs_cleared": cleared, "pairs_intersected": intersected,
"pairs_not_checked": not_checked, "budget_s": budget_s, "budget_exceeded": not_checked > 0,
"threads": threads, "boolean_ms": round_ms(boolean_ms), "tessellate_ms": round_ms(tessellate_ms),
"slowest": slowest, "ms": round_ms(started.elapsed().as_secs_f64() * 1000.0),
}))
}
fn round_ms(ms: f64) -> f64 {
(ms * 1000.0).round() / 1000.0
}
/// Are two bodies' meshes farther apart than `margin` with neither body inside the other? Then
/// their boundaries don't meet (each mesh is within its chord tolerance of its faces, which the
/// margin covers), so the bodies share no volume. Conservative: an empty mesh, nested boxes or
/// a point of one inside the other answer no.
fn meshes_apart(ma: &Mesh, sa: &TriangleSet, mb: &Mesh, sb: &TriangleSet, margin: f64) -> bool {
if ma.triangles.is_empty() || mb.triangles.is_empty() || !margin.is_finite() {
return false;
}
if sa.closest(sb, margin).is_some() {
return false;
}
// Apart boundaries: either the bodies are apart, or one holds the other (or a piece of it).
let (ba, bb) = (ma.bounds(), mb.bounds());
if nested(&ba, &bb) || nested(&bb, &ba) {
return false;
}
!(any_inside(&face_points(ma), mb) || any_inside(&face_points(mb), ma))
}
/// Is `inner` inside `outer`?
fn nested(inner: &Aabb3, outer: &Aabb3) -> bool {
!inner.is_empty()
&& outer.min.x <= inner.min.x
&& outer.min.y <= inner.min.y
&& outer.min.z <= inner.min.z
&& inner.max.x <= outer.max.x
&& inner.max.y <= outer.max.y
&& inner.max.z <= outer.max.z
}
/// A corner of each face's first triangle (every piece of a body in several pieces has a face).
fn face_points(m: &Mesh) -> Vec<Vec3> {
let mut seen = HashSet::new();
let mut out = Vec::new();
for (k, t) in m.triangles.iter().enumerate() {
let face = m.tri_face.get(k).copied().unwrap_or(0);
if seen.insert(face)
&& let Some(p) = m.positions.get(t[0] as usize)
{
out.push(*p);
}
}
out
}
/// Is any of `points` inside the closed mesh `outer`?
fn any_inside(points: &[Vec3], outer: &Mesh) -> bool {
let b = outer.bounds();
let within = |p: &&Vec3| b.min.x <= p.x && p.x <= b.max.x && b.min.y <= p.y && p.y <= b.max.y && b.min.z <= p.z && p.z <= b.max.z;
let candidates: Vec<&Vec3> = points.iter().filter(within).collect();
match candidates.len() {
0 => false,
1..=4 => candidates.iter().any(|p| outer.contains(**p)),
_ => {
let index = outer.inside_index();
candidates.iter().any(|p| index.contains(**p))
}
}
}
/// The exact check of one pair: a pin a hair off the axis of its hole by the walls' crescent,
/// otherwise the intersection measured.
fn check(job: &Job) -> Done {
let started = web_time::Instant::now();
let ((outcome, note), kernel) = solidcraft_kernel::profile::capture(|| check_pair(&job.a, &job.b, &job.names));
Done { outcome, note, ms: started.elapsed().as_secs_f64() * 1000.0, kernel }
}
fn check_pair(a: &Body, b: &Body, (na, nb): &(String, String)) -> (Outcome, Option<String>) {
let threshold = 1e-9 * a.size().max(1.0).powi(3);
// A pin a hair off the axis of its hole: the crescent the walls share, which the boolean
// can't intersect.
if let Some(o) = solidcraft_kernel::coaxial_overlap(a, b) {
if o.volume > threshold {
let hit = json!({"a": na, "b": nb, "volume_mm3": o.volume, "area_mm2": o.area, "center": o.centroid,
"bbox": {"min": o.bbox.min, "max": o.bbox.max}, "near_coaxial": {"offset_mm": o.offset, "length_mm": o.length}});
return (Outcome::Hit(hit), None);
}
return (Outcome::Clear, None);
}
// A pair whose shared part can't be worked out is reported, not passed as clear.
let (shared, report) = solidcraft_kernel::capture_boolean_diagnostics(|| solidcraft_kernel::boolean(a, b, solidcraft_kernel::BoolOp::Intersect));
let shared = match shared {
Ok(o) => o,
Err(e) => return (Outcome::Unchecked(e.to_string()), None),
};
let mut note = report.unverified();
let pieces = match shared {
Some(o) => vec![o],
// A body in several pieces, one of them wholly inside the other body: the whole bodies'
// boolean can come out empty, so the pieces are intersected one by one.
None if a.shell_count() > 1 || b.shell_count() > 1 => match by_pieces(a, b) {
Ok((pieces, unverified)) => {
note = note.or(unverified);
pieces
}
Err(e) => return (Outcome::Unchecked(e), note),
},
None => return (Outcome::Clear, note),
};
// The shared parts measured together: volumes and areas add, the centre is the volumes'.
let mut measured = Vec::new();
for o in &pieces {
match solidcraft_kernel::measure_mass(o) {
Ok(m) => measured.push(m),
Err(e) => return (Outcome::Unchecked(e.to_string()), note),
}
}
let volume: f64 = measured.iter().map(|m| m.volume).sum();
if volume > threshold {
let area: f64 = measured.iter().map(|m| m.area).sum();
let bbox = measured.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.bbox));
let center = match measured.as_slice() {
[m] => m.centroid,
_ => measured.iter().fold(Vec3::ZERO, |c, m| c + m.centroid * m.volume) / volume,
};
let hit = json!({"a": na, "b": nb, "volume_mm3": volume, "area_mm2": area, "center": center, "bbox": {"min": bbox.min, "max": bbox.max}});
return (Outcome::Hit(hit), note);
}
(Outcome::Clear, note)
}
/// Most pairs of pieces [`by_pieces`] intersects.
const MAX_PIECE_PAIRS: usize = 256;
/// The shared parts of two bodies, a piece of each at a time, and why any of them is unverified.
fn by_pieces(a: &Body, b: &Body) -> std::result::Result<(Vec<Body>, Option<String>), String> {
let (la, lb) = (a.lumps().map_err(|e| e.to_string())?, b.lumps().map_err(|e| e.to_string())?);
if la.len() < 2 && lb.len() < 2 {
return Ok((Vec::new(), None));
}
if la.len().saturating_mul(lb.len()) > MAX_PIECE_PAIRS {
return Err(format!("not checked: {} by {} pieces are more than {MAX_PIECE_PAIRS} pairs of pieces", la.len(), lb.len()));
}
let (mut out, mut note) = (Vec::new(), None);
for x in &la {
for y in &lb {
let (r, report) =
solidcraft_kernel::capture_boolean_diagnostics(|| solidcraft_kernel::boolean(x, y, solidcraft_kernel::BoolOp::Intersect));
note = note.or(report.unverified());
if let Some(o) = r.map_err(|e| e.to_string())? {
out.push(o);
}
}
}
Ok((out, note))
}
/// Each job's answer (in pair order, with the pair's names; `None`: not finished within
/// `budget`) and how many worker threads ran them (0: this thread did).
fn run_jobs(jobs: Vec<Job>, budget: std::time::Duration) -> (Vec<((String, String), Option<Done>)>, usize) {
let mut order: Vec<(usize, usize, (String, String))> = jobs.iter().enumerate().map(|(k, j)| (j.pair, k, j.names.clone())).collect();
order.sort_unstable_by_key(|o| o.0);
let (mut results, threads) = run_ordered(jobs, budget);
let out = order.into_iter().map(|(_, k, names)| (names, results.get_mut(k).and_then(Option::take))).collect();
(out, threads)
}
/// Each job's answer in job order, and the threads used. On desktop the jobs run on worker
/// threads of their own, which the call does not wait for once `budget` is spent: a pair still
/// running then finishes in the background and is dropped (a kernel boolean can't be stopped
/// part way).
#[cfg(not(target_arch = "wasm32"))]
fn run_ordered(jobs: Vec<Job>, budget: std::time::Duration) -> (Vec<Option<Done>>, usize) {
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::mpsc;
let n = jobs.len();
let mut out: Vec<Option<Done>> = std::iter::repeat_with(|| None).take(n).collect();
if n == 0 || budget.is_zero() {
return (out, 0);
}
let deadline = web_time::Instant::now() + budget;
// The workers outlive the call when the budget runs out, so they own what they work on.
let jobs = Arc::new(jobs);
let next = Arc::new(AtomicUsize::new(0));
let stop = Arc::new(AtomicBool::new(false));
let (tx, rx) = mpsc::channel::<(usize, Done)>();
let want = std::thread::available_parallelism().map(usize::from).unwrap_or(1).min(n).max(1);
let mut threads = 0;
for _ in 0..want {
let (jobs, next, stop, tx) = (jobs.clone(), next.clone(), stop.clone(), tx.clone());
let spawned = std::thread::Builder::new().name("solidcraft-interference".into()).spawn(move || {
while !stop.load(Ordering::Relaxed) {
let k = next.fetch_add(1, Ordering::Relaxed);
let Some(job) = jobs.get(k) else { break };
let done = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| check(job))).unwrap_or_else(|_| Done {
outcome: Outcome::Unchecked("internal error while checking this pair".into()),
note: None,
ms: 0.0,
kernel: KernelTimes::default(),
});
if tx.send((k, done)).is_err() {
break;
}
}
});
if spawned.is_ok() {
threads += 1;
}
}
drop(tx);
if threads == 0 {
// No thread could be started: one pair after another here.
return (run_here(&jobs, deadline), 0);
}
let mut received = 0;
while received < n {
let left = deadline.saturating_duration_since(web_time::Instant::now());
match rx.recv_timeout(left) {
Ok((k, done)) => {
if let Some(slot) = out.get_mut(k) {
*slot = Some(done);
}
received += 1;
}
// Out of time, or every worker gone (none is left with work then).
Err(_) => break,
}
}
stop.store(true, Ordering::Relaxed);
(out, threads)
}
/// The browser has no threads: one pair after another, none started once the budget is spent.
#[cfg(target_arch = "wasm32")]
fn run_ordered(jobs: Vec<Job>, budget: std::time::Duration) -> (Vec<Option<Done>>, usize) {
(run_here(&jobs, web_time::Instant::now() + budget), 0)
}
/// The jobs one after another on this thread, none started past `deadline`.
fn run_here(jobs: &[Job], deadline: web_time::Instant) -> Vec<Option<Done>> {
jobs.iter().map(|job| (web_time::Instant::now() < deadline).then(|| check(job))).collect()
}
#[cfg(test)]
#[path = "interference_tests.rs"]
mod tests;
+110
View File
@@ -0,0 +1,110 @@
//! `inspect.interference`: the mesh pre-filter, the bodies it must not clear, and the budget.
use serde_json::{Value, json};
use crate::Session;
fn run(s: &mut Session, id: &str, p: Value) -> Value {
match s.execute(id, &p) {
Ok(v) => v,
Err(e) => panic!("{id} {p}: {e}"),
}
}
fn f(v: &Value) -> f64 {
v.as_f64().unwrap_or(f64::NAN)
}
/// Curved bodies whose boxes overlap but which stay apart are answered from their meshes: no
/// boolean runs. Two cylinders on a diagonal (centres 12.7 mm apart, radii 5), and a torus
/// beside a sphere that sits in the corner of its box.
#[test]
fn separated_curved_bodies_are_cleared_without_a_boolean() {
let mut s = Session::default();
run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 10, "base": [0, 0, 0], "body_name": "C1"}));
run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 10, "base": [9, 9, 0], "operation": "new", "body_name": "C2"}));
run(&mut s, "solid.torus", json!({"major": 20, "minor": 3, "center": [60, 0, 0], "body_name": "Torus"}));
// In the torus box's corner (the box reaches 23 out on each axis), 1.66 mm clear of the tube.
run(&mut s, "solid.sphere", json!({"radius": 3, "center": [80, 19, 1], "operation": "new", "body_name": "Ball"}));
let i = run(&mut s, "inspect.interference", json!({}));
assert_eq!(i["count"], 0, "{i}");
assert_eq!(i["pairs_candidate"], 2, "{i}");
assert_eq!(i["pairs_cleared"], 2, "{i}");
assert_eq!(i["pairs_intersected"], 0, "{i}");
assert_eq!(f(&i["boolean_ms"]), 0.0, "{i}");
assert_eq!(i["unchecked"].as_array().map(Vec::len), Some(0), "{i}");
// Moved into each other, the same pairs are intersected and overlap.
run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 10, "base": [7, 0, 0], "operation": "new", "body_name": "C3"}));
let i = run(&mut s, "inspect.interference", json!({"bodies": ["C1", "C3"]}));
assert_eq!(i["count"], 1, "{i}");
assert_eq!(i["pairs_intersected"], 1, "{i}");
// The lens of two r5 circles 7 apart, 10 high.
let (r, d): (f64, f64) = (5.0, 7.0);
let lens = 2.0 * r * r * (d / (2.0 * r)).acos() - d / 2.0 * (4.0 * r * r - d * d).sqrt();
let got = f(&i["interferences"][0]["volume_mm3"]);
assert!((got - 10.0 * lens).abs() < 1e-3 * 10.0 * lens, "{got} against {}: {i}", 10.0 * lens);
}
/// A body wholly inside another has meshes that never meet: it is still intersected, and its
/// whole volume is the overlap.
#[test]
fn a_body_inside_another_is_still_found() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 40, "corner": [-20, -20, -20], "body_name": "Block"}));
run(&mut s, "solid.sphere", json!({"radius": 5, "center": [3, -2, 1], "operation": "new", "body_name": "Ball"}));
let i = run(&mut s, "inspect.interference", json!({}));
assert_eq!(i["count"], 1, "{i}");
assert_eq!(i["pairs_cleared"], 0, "{i}");
let want = 4.0 / 3.0 * std::f64::consts::PI * 125.0;
let got = f(&i["interferences"][0]["volume_mm3"]);
assert!((got - want).abs() < 1e-3 * want, "{got} against {want}: {i}");
}
/// A body in two pieces, one of them wholly inside a block and the other outside it: the boxes
/// are not nested and the meshes never meet, but a point of the inner piece's faces is inside
/// the block, so the pair is intersected. The whole bodies' boolean comes out empty there, so
/// the pieces are intersected one by one.
#[test]
fn a_piece_of_a_body_inside_another_is_still_found() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 20, "corner": [0, 0, 0], "body_name": "Block"}));
run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [5, 5, 5], "operation": "new", "body_name": "Pieces"}));
run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [30, 5, 5], "operation": "join", "targets": ["Pieces"]}));
let st = s.world_state();
let pieces = st.bodies.iter().find(|b| b.name == "Pieces").map(|b| b.body.shell_count());
assert_eq!(pieces, Some(2), "the two cubes are one body in two pieces");
let i = run(&mut s, "inspect.interference", json!({}));
assert_eq!(i["count"], 1, "{i}");
assert_eq!(i["pairs_cleared"], 0, "{i}");
assert!((f(&i["interferences"][0]["volume_mm3"]) - 8.0).abs() < 1e-6, "{i}");
}
/// A budget spent before any pair could start lists every pair as not checked (and the call
/// returns); bad budgets are refused.
#[test]
fn pairs_left_when_the_budget_runs_out_are_listed_not_checked() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [0, 0, 0], "body_name": "A"}));
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [5, 0, 0], "operation": "new", "body_name": "B"}));
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [12, 0, 0], "operation": "new", "body_name": "C"}));
let i = run(&mut s, "inspect.interference", json!({"budget_s": 1e-12}));
assert_eq!(i["count"], 0, "{i}");
assert_eq!(i["budget_exceeded"], true, "{i}");
assert_eq!(i["pairs_not_checked"], 2, "{i}");
let unchecked = i["unchecked"].as_array().cloned().unwrap_or_default();
assert_eq!(unchecked.len(), 2, "{i}");
assert!(unchecked.iter().all(|u| u["reason"].as_str().is_some_and(|r| r.starts_with("not checked") && r.contains("time budget"))), "{i}");
// The default budget checks both pairs: 500 and 300 mm³.
let i = run(&mut s, "inspect.interference", json!({}));
assert_eq!(i["budget_exceeded"], false, "{i}");
assert_eq!(i["budget_s"], 240.0, "{i}");
assert_eq!(i["count"], 2, "{i}");
let mut v: Vec<f64> = i["interferences"].as_array().into_iter().flatten().map(|h| f(&h["volume_mm3"])).collect();
v.sort_by(f64::total_cmp);
assert!((v[0] - 300.0).abs() < 1e-6 && (v[1] - 500.0).abs() < 1e-6, "{i}");
// Answers come in pair order whatever order they finished in.
assert_eq!((i["interferences"][0]["a"].as_str(), i["interferences"][0]["b"].as_str()), (Some("A"), Some("B")), "{i}");
for bad in [json!(0), json!(-1), json!("soon"), json!(f64::MAX), json!(1e6)] {
assert!(s.execute("inspect.interference", &json!({"budget_s": bad})).is_err(), "{bad}");
}
}
+3 -58
View File
@@ -12,7 +12,7 @@ use solidcraft_doc::joints::{self, Coupling, Joint, JointExprs, JointKind, Joint
use solidcraft_geom::{Aabb3, Vec3};
use super::CommandSpec;
use crate::params::{bad, bool_, num, str_, string_list, vec3};
use crate::params::{bad, bool_, num, str_, vec3};
use crate::{EngineError, Result, Session};
pub static COMMANDS: &[CommandSpec] = &[
@@ -77,8 +77,8 @@ pub static COMMANDS: &[CommandSpec] = &[
(joint chains joined to nothing grounded: the solver places none of them, so driving them moves nothing)",
),
CommandSpec::new("joint.solve", "Solve Joints", solve_cmd).icon("compute").params("re-place the occurrences from the joints → conflicts, errors, dof"),
CommandSpec::new("inspect.interference", "Interference", interference).at("SOLID", "INSPECT").icon("interference").noundo().params(
"bodies?: [names] (default: all, in world placement) → interferences: pairs that overlap with the overlap volume, area, bounding box and centre (a pin a hair off the axis of a hole of its size also has near_coaxial: {offset_mm, length_mm}, its volume the crescent the walls share); unchecked: pairs that could not be checked, with the reason. Bodies are pruned by bounding box first, so any number of bodies is fine; at most 20000 pairs whose boxes overlap are intersected per call (truncated: true and skipped_pairs: n say when more were left out)",
CommandSpec::new("inspect.interference", "Interference", super::interference::interference).at("SOLID", "INSPECT").icon("interference").noundo().params(
"bodies?: [names] (default: all, in world placement); budget_s?: seconds (default 240, at most 86400: pairs not finished by then are listed in unchecked as \"not checked: the time budget … ran out\" and the call returns) → interferences: pairs that overlap with the overlap volume, area, bounding box and centre (a pin a hair off the axis of a hole of its size also has near_coaxial: {offset_mm, length_mm}, its volume the crescent the walls share); unchecked: pairs that could not be checked, with the reason. Bodies are pruned by bounding box first, then by their display meshes (pairs whose meshes stay apart by more than their chord tolerances, neither inside the other, are clear without a boolean), so any number of bodies is fine; the pairs left are intersected exactly, in parallel on desktop, the slowest first; at most 20000 pairs whose boxes overlap are intersected per call (truncated: true and skipped_pairs: n say when more were left out). Also: pairs_candidate (boxes overlap), pairs_cleared (by the meshes), pairs_intersected, pairs_not_checked, budget_exceeded, threads (worker threads; 0: on the calling thread), boolean_ms and tessellate_ms (kernel time summed over the pairs), slowest: [{a, b, ms, boolean_ms, tessellate_ms}] and ms",
),
];
@@ -1320,61 +1320,6 @@ fn solve_cmd(s: &mut Session, p: &Value) -> Result<Value> {
Ok(sol_json(&sol, p))
}
fn interference(s: &mut Session, p: &Value) -> Result<Value> {
let want = string_list(p, "bodies");
let st = s.world_state();
let bodies: Vec<&solidcraft_doc::ModelBody> =
st.bodies.iter().filter(|b| want.is_empty() || want.contains(&b.name)).filter(|b| !b.body.is_mesh()).collect();
// Prune by bounding boxes first (sort and sweep), so the cost follows the pairs that can
// touch rather than the square of the body count.
let boxes: Vec<Aabb3> = bodies.iter().map(|b| b.mesh().bounds()).collect();
let (pairs, skipped) = overlapping_pairs(&boxes, MAX_INTERFERENCE_PAIRS);
let (mut hits, mut unchecked) = (Vec::new(), Vec::new());
for (i, j) in pairs {
let (Some(a), Some(b)) = (bodies.get(i), bodies.get(j)) else { continue };
let threshold = 1e-9 * a.body.size().max(1.0).powi(3);
// A pin a hair off the axis of its hole: the crescent the walls share, which the
// boolean can't intersect.
if let Some(o) = solidcraft_kernel::coaxial_overlap(&a.body, &b.body) {
if o.volume > threshold {
hits.push(json!({"a": a.name, "b": b.name, "volume_mm3": o.volume, "area_mm2": o.area, "center": o.centroid,
"bbox": {"min": o.bbox.min, "max": o.bbox.max}, "near_coaxial": {"offset_mm": o.offset, "length_mm": o.length}}));
}
continue;
}
// A pair whose shared part can't be worked out is reported, not passed as clear.
let (shared, report) =
solidcraft_kernel::capture_boolean_diagnostics(|| solidcraft_kernel::boolean(&a.body, &b.body, solidcraft_kernel::BoolOp::Intersect));
let mut skip = |reason: String| unchecked.push(json!({"a": a.name, "b": b.name, "reason": reason}));
let shared = match shared {
Ok(o) => o,
Err(e) => {
skip(e.to_string());
continue;
}
};
if let Some(reason) = report.unverified() {
skip(reason);
}
let Some(o) = shared else { continue };
let m = match solidcraft_kernel::measure(&o) {
Ok(m) => m,
Err(e) => {
skip(e.to_string());
continue;
}
};
if m.volume > threshold {
hits.push(json!({"a": a.name, "b": b.name, "volume_mm3": m.volume, "area_mm2": m.area, "center": m.centroid, "bbox": {"min": m.bbox.min, "max": m.bbox.max}}));
}
}
Ok(json!({"interferences": hits, "count": hits.len(), "checked": bodies.len(), "unchecked": unchecked,
"truncated": skipped > 0, "skipped_pairs": skipped}))
}
/// Most pairs with overlapping bounding boxes `inspect.interference` intersects in one call.
const MAX_INTERFERENCE_PAIRS: usize = 20_000;
/// Index pairs `(i, j)`, `i < j`, whose boxes overlap or touch (sort and sweep along X), at most
/// `limit` of them, plus how many more there were.
pub(crate) fn overlapping_pairs(boxes: &[Aabb3], limit: usize) -> (Vec<(usize, usize)>, usize) {
+1
View File
@@ -39,6 +39,7 @@ mod component_link;
mod config;
mod file;
mod inspect;
mod interference;
pub(crate) mod joints;
mod libraries;
mod material_properties;
+28
View File
@@ -521,3 +521,31 @@ fn pattern_of_cuts_beside_a_round_needs_no_retries() {
let v = volume(&mut s);
assert!(rel(v, expected) < 1e-5, "{v} vs {expected}");
}
/// #2755: a cut cylinder with `targets` cuts only those bodies, and so do its pattern and mirror
/// copies: a body over the plate that the cylinder was told to leave alone keeps its volume.
#[test]
fn copies_of_a_primitive_cut_only_its_targets() {
let body_volume = |s: &mut Session, name: &str| {
let m = run(s, "inspect.measure", json!({"bodies": [name]}));
m["bodies"][0]["volume_mm3"].as_f64().unwrap_or(f64::NAN)
};
// The command, and the holes in the plate after it (the cylinder's and its copies).
for (copy, holes) in [
(json!(["solid.pattern.rectangular", {"features": ["Trou"], "dir1": [1, 0, 0], "count1": 3, "spacing1": 30}]), 3.0),
(json!(["solid.mirror", {"features": ["Trou"], "plane": {"origin": [50, 0, 0], "normal": [1, 0, 0]}}]), 2.0),
] {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 100, "width": 60, "height": 10, "body_name": "Plaque"}));
run(&mut s, "solid.box", json!({"length": 100, "width": 60, "height": 10, "corner": [0, 0, 5], "operation": "new", "body_name": "Voisin"}));
let cyl = json!({"radius": 3, "height": 30, "base": [10, 10, -5], "operation": "cut", "targets": ["Plaque"], "name": "Trou"});
run(&mut s, "solid.cylinder", cyl);
assert!(rel(body_volume(&mut s, "Voisin"), 60000.0) < 1e-9);
let (id, p) = (copy[0].as_str().unwrap_or_default(), copy[1].clone());
let r = run(&mut s, id, p);
assert_eq!(r["changed_bodies"], json!(["Plaque"]), "{id}");
assert!(rel(body_volume(&mut s, "Voisin"), 60000.0) < 1e-9, "{id} cut Voisin");
let removed = 60000.0 - body_volume(&mut s, "Plaque");
assert!(rel(removed, holes * PI * 9.0 * 10.0) < 1e-3, "{id}: {removed} mm³ cut from Plaque");
}
}
+46 -4
View File
@@ -344,6 +344,26 @@ impl Default for Session {
}
}
/// What a rename command renamed (from its result and the document before it), so the model
/// can take the new name without building anything again (#3044).
enum Renamed {
Body { old: String, new: String },
Feature { id: u64, old: String, new: String },
}
impl Renamed {
fn of(command: &str, result: &Value, before: &Document) -> Option<Renamed> {
let new = result.get("name")?.as_str()?.to_string();
match command {
"body.rename" => Some(Renamed::Body { old: result.get("body")?.as_str()?.to_string(), new }),
"timeline.rename" => {
let id = result.get("feature")?.as_u64()?;
Some(Renamed::Feature { id, old: before.feature(id)?.name.clone(), new })
}
_ => None,
}
}
}
impl Session {
pub fn new(mut doc: Document) -> Self {
// The session keeps what is hidden (not an undo step); the design file carries it.
@@ -576,6 +596,26 @@ impl Session {
{
self.evaluations += 1;
}
self.after_evaluation();
}
/// A body or feature renamed (`previous` the document before): the model takes the new
/// name without building anything again, or is evaluated where that might not give what an
/// evaluation gives (see `Model::rename_body` and `Model::rename_feature`, #3044).
fn refresh_renamed(&mut self, previous: &Arc<Document>, renamed: &Renamed) {
let in_place = match renamed {
Renamed::Body { old, new } => self.model.rename_body(previous, &self.doc, old, new),
Renamed::Feature { id, old, new } => self.model.rename_feature(&self.doc, *id, old, new),
};
if in_place {
self.after_evaluation();
} else {
self.refresh();
}
}
/// What follows a new model: a new revision, and what depends on the model brought up to it.
fn after_evaluation(&mut self) {
self.revision += 1;
self.prune_occurrence_state();
// Joints follow the geometry their origins snap to.
@@ -718,6 +758,7 @@ impl Session {
let changed = !Arc::ptr_eq(&self.doc, &before.doc);
match r {
Ok((v, live_edit)) => {
let renamed = Renamed::of(spec.id, &v, &before.doc);
let v = if changed { self.with_created(spec.id, params, &before, v) } else { v };
if changed {
let render_only = self.render_only_change(&before);
@@ -729,10 +770,11 @@ impl Session {
}
self.redo.clear();
}
match live_edit {
Some(edit) => self.refresh_live(edit),
None if render_only => self.refresh_render(&previous_doc),
None => self.refresh(),
match (live_edit, renamed) {
(Some(edit), _) => self.refresh_live(edit),
(None, _) if render_only => self.refresh_render(&previous_doc),
(None, Some(renamed)) => self.refresh_renamed(&previous_doc, &renamed),
(None, None) => self.refresh(),
}
}
Ok(v)
@@ -197,7 +197,7 @@ fn moved_component_bodies_are_not_placed_again_when_something_else_changes() {
let again = after.body(&rim.name).unwrap();
assert!(Arc::ptr_eq(&mesh, &again.mesh()), "an unchanged placed body keeps its mesh");
assert!(again.body.same(&rim.body));
// The placement moves: placed and meshed again where it now is.
// The placement moves: new world coordinates, reusing the definition's triangulation.
run(&mut session, "occurrence.move", json!({"occurrence":occurrence,"translate":[0,50,0]}));
let moved = session.world_state();
let moved_rim = moved.bodies.iter().find(|b| b.source_name.as_deref() == Some("Rim")).unwrap();
@@ -213,3 +213,52 @@ fn moved_component_bodies_are_not_placed_again_when_something_else_changes() {
assert!(source.mesh().bounds().min.dist(Vec3::ZERO) < 1e-6);
assert!(mesh.bounds().min.dist(Vec3::new(100., 0., 0.)) < 1e-6);
}
/// Driving an unchanged definition must map its warm reference triangles, not re-tessellate
/// the placed B-rep on the first mesh read of every new pose (viewport bounds does that read).
#[test]
fn joint_drive_reuses_reference_tessellation_across_rigid_poses() {
let mut session = Session::default();
run(&mut session, "solid.cylinder", json!({"radius":3,"height":8,"base":[4,0,0],"body_name":"Crank"}));
run(&mut session, "component.create", json!({"name":"Crank","parent":"root","activate":false}));
run(&mut session, "component.move_bodies", json!({"bodies":["Crank"],"component":"Crank"}));
run(
&mut session,
"joint.as_built",
json!({"type":"revolute","name":"Crank","a":0,"b":"Crank","at":{"occurrence":0,"point":[0,0,0],"z":[0,0,1]}}),
);
let definitions = session.model.state();
let original = session.world_state();
let local = original.body("Crank").unwrap().mesh();
let bounds = local.bounds();
for angle in [37., 91., 37., 0.] {
let driven = run(&mut session, "joint.drive", json!({"joint":"Crank","value":angle}));
assert_eq!(driven["moved"], true);
assert!(Arc::ptr_eq(&definitions, &session.model.state()));
let world = session.world_state();
let body = world.body("Crank").unwrap();
let (mesh, work) = crate::kernel::profile::capture(|| body.mesh());
assert_eq!(work.tessellate_ms, 0., "a warm definition must not enter the kernel mesher at a new pose: {work:?}");
assert_eq!(mesh.positions.len(), local.positions.len());
assert_eq!(mesh.normals.len(), local.normals.len());
assert_eq!(mesh.edges.iter().map(Vec::len).collect::<Vec<_>>(), local.edges.iter().map(Vec::len).collect::<Vec<_>>());
assert_eq!(mesh.triangles, local.triangles);
assert_eq!(mesh.tri_face, local.tri_face);
assert_eq!(mesh.edge_faces, local.edge_faces);
assert_eq!(mesh.seams, local.seams);
assert_eq!(mesh.smooth_edges, local.smooth_edges);
assert_eq!(mesh.sharp_edges, local.sharp_edges);
for (p, q) in local.positions.iter().zip(&mesh.positions) {
assert!(crate::doc::apply_point(&body.source_transform, *p).dist(*q) < 1e-8);
}
for (n, q) in local.normals.iter().zip(&mesh.normals) {
assert!(crate::doc::apply_vector(&body.source_transform, *n).dist(*q) < 1e-8);
}
for (edge, placed) in local.edges.iter().zip(&mesh.edges) {
for (p, q) in edge.iter().zip(placed) {
assert!(crate::doc::apply_point(&body.source_transform, *p).dist(*q) < 1e-8);
}
}
}
assert_eq!(local.bounds(), bounds, "old snapshots stay immutable");
}
+1 -1
View File
@@ -176,7 +176,7 @@ pub use iges_out::iges_export_bodies;
pub use lip::raise_band;
pub use loft_blend::loft_blend;
pub use matchsurf::{match_surface, seam_continuity};
pub use measure::{BodyMeasure, measure};
pub use measure::{BodyMeasure, MassMeasure, measure, measure_mass};
pub use mesh_convert::convert_prismatic_mesh;
pub use meshbody::{MAX_TRIANGLES, mesh_body};
pub use native::{decode_native_body, encode_native_body, native_preview_mesh};
+95 -14
View File
@@ -55,6 +55,16 @@ fn min_edge_radius(m: &Mesh) -> Option<f64> {
best
}
/// Volume, area, centre and box of a body, as [`measure`] works them out, without the topology
/// counts (and the tessellation they take).
#[derive(Clone, Copy, Debug, Serialize)]
pub struct MassMeasure {
pub volume: f64,
pub area: f64,
pub centroid: Vec3,
pub bbox: Aabb3,
}
/// Measure a body from a fine tessellation (chord tolerance 5e-5 of the body size, finer for
/// small radii down to 5e-6). Faces whose fine tessellation disagrees with a coarse one (a
/// meshing failure) use the coarse result.
@@ -78,14 +88,69 @@ pub fn measure(b: &Body) -> Result<BodyMeasure> {
merged,
});
}
let (m, topo) = mass(b, true)?;
let topo = match topo {
Some(t) => t,
None => b.tessellate((b.size() * 1e-3).max(1e-3))?,
};
Ok(BodyMeasure {
volume: m.volume,
area: m.area,
centroid: m.centroid,
bbox: m.bbox,
faces: b.face_count(),
edges: b.edge_count(),
vertices: b.vertex_count(),
shells: b.shell_count(),
merged: merged_topology(b, &topo)?,
})
}
/// [`measure`]'s volume, area, centre and box alone: the same numbers, a tessellation fewer
/// (for callers that need no topology counts, such as an interference check).
pub fn measure_mass(b: &Body) -> Result<MassMeasure> {
if b.triangle_mesh().is_some() {
let m = measure(b)?;
return Ok(MassMeasure { volume: m.volume, area: m.area, centroid: m.centroid, bbox: m.bbox });
}
Ok(mass(b, false)?.0)
}
/// The mass properties of a B-rep body from three tessellations: a coarse one (which sets how
/// fine the others go), then a fine and a medium one at once on desktop (one after the other
/// in the browser). With `topology`, also the coarse unrefined mesh the topology counts take,
/// made alongside them.
fn mass(b: &Body, topology: bool) -> Result<(MassMeasure, Option<Mesh>)> {
let size = b.size();
let coarse = b.tessellate_with((size * 1e-3).max(1e-3), true)?;
let coarse_tol = (size * 1e-3).max(1e-3);
let coarse = b.tessellate_with(coarse_tol, true)?;
// Chord error relative to a radius sets the volume error: keep it near 3e-4 of the
// smallest radius (thin tubes, small fillets).
let tight = min_edge_radius(&coarse).map(|r| r * 3e-4).unwrap_or(f64::INFINITY);
let fine_tol = (size * 5e-5).min(tight).max(size * 5e-6).max(1e-4);
let fine = b.tessellate_with(fine_tol, true)?;
let medium = b.tessellate_with((fine_tol * 5.0).max(2e-4), true)?;
let mut jobs = vec![(fine_tol, true), ((fine_tol * 5.0).max(2e-4), true)];
if topology {
jobs.push((coarse_tol, false));
}
// Independent tessellations of one body: each on its own thread, the calling thread's
// profile counting their wall time once as tessellation. Not from inside a worker pool: a
// pool thread blocked on threads of its own could leave their meshing (which runs on the
// shared pool) without a worker.
#[cfg(not(target_arch = "wasm32"))]
let threads = if rayon::current_thread_index().is_none() { jobs.len() } else { 1 };
#[cfg(target_arch = "wasm32")]
let threads = 1;
let made = crate::profile::timed(crate::profile::Kind::Tessellate, || {
crate::par::map_on_threads(&jobs, threads, |&(tol, refine)| b.tessellate_with(tol, refine))
});
let mut made = made.into_iter().map(|m| m.unwrap_or_else(|| Err(crate::KernelError::Internal("tessellation failed".into()))));
let missing = || crate::KernelError::Internal("tessellation missing".into());
let fine = made.next().ok_or_else(missing)??;
let medium = made.next().ok_or_else(missing)??;
let topo = match made.next() {
Some(m) => Some(m?),
None => None,
};
let nf = b.face_count();
let (sf, sm, sc) = (face_sums(&fine, nf), face_sums(&medium, nf), face_sums(&coarse, nf));
let close = |x: f64, y: f64| (x - y).abs() <= 0.01 * x.abs().max(y.abs()) + 1e-9;
@@ -105,15 +170,31 @@ pub fn measure(b: &Body) -> Result<BodyMeasure> {
}
let volume = v6 / 6.0;
let centroid = if v6.abs() > 1e-12 { mom / (4.0 * v6) } else { fine.bounds().center() };
Ok(BodyMeasure {
volume,
area,
centroid,
bbox: coarse.bounds().union(&fine.bounds()),
faces: b.face_count(),
edges: b.edge_count(),
vertices: b.vertex_count(),
shells: b.shell_count(),
merged: merged_topology(b, &b.tessellate((size * 1e-3).max(1e-3))?)?,
})
Ok((MassMeasure { volume, area, centroid, bbox: coarse.bounds().union(&fine.bounds()) }, topo))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{BoolOp, boolean, cylinder, torus};
/// The mass properties alone are [`measure`]'s, to the bit, with the tessellations made at
/// once; and on a curved intersection they are the textbook ones.
#[test]
fn mass_alone_is_the_full_measure() {
let ring = torus(Vec3::ZERO, 10.0, 2.0).unwrap();
let post = cylinder(Vec3::new(10.0, 0.0, -5.0), Vec3::Z, 1.5, 10.0).unwrap();
let shared = boolean(&ring, &post, BoolOp::Intersect).unwrap().unwrap();
for b in [&ring, &shared] {
let (full, mass) = (measure(b).unwrap(), measure_mass(b).unwrap());
assert_eq!(full.volume.to_bits(), mass.volume.to_bits());
assert_eq!(full.area.to_bits(), mass.area.to_bits());
assert_eq!(full.centroid, mass.centroid);
assert_eq!((full.bbox.min, full.bbox.max), (mass.bbox.min, mass.bbox.max));
}
let want = 2.0 * std::f64::consts::PI.powi(2) * 10.0 * 4.0;
let got = measure_mass(&ring).unwrap().volume;
assert!((got - want).abs() < 1e-3 * want, "{got} against {want}");
assert!(measure(&ring).unwrap().merged.faces > 0);
}
}
+28
View File
@@ -59,6 +59,21 @@ pub fn capture<T>(f: impl FnOnce() -> T) -> (T, KernelTimes) {
(r, times)
}
/// Count kernel time spent on other threads for this thread's running capture (when one runs
/// and no timed call does): work this thread handed out and waited for. The caller keeps the
/// sum within the wall time it waited, so the totals still never pass what the command took.
pub fn credit(times: KernelTimes) {
let ok = |x: f64| if x.is_finite() && x > 0.0 { x } else { 0.0 };
STATE.with(|s| {
let mut st = s.get();
if st.on && !st.busy {
st.times.boolean_ms += ok(times.boolean_ms);
st.times.tessellate_ms += ok(times.tessellate_ms);
s.set(st);
}
});
}
/// Time `f` as `kind` when a capture is running and no timed call is.
pub(crate) fn timed<T>(kind: Kind, f: impl FnOnce() -> T) -> T {
let st = STATE.with(Cell::get);
@@ -122,6 +137,19 @@ mod tests {
assert!(t.boolean_ms + t.tessellate_ms <= elapsed + 1e-6, "{t:?} in {elapsed} ms");
}
#[test]
fn time_credited_from_other_threads_counts_only_inside_a_capture() {
let t = KernelTimes { boolean_ms: 4.0, tessellate_ms: 1.0 };
credit(t);
let ((), got) = capture(|| {
credit(t);
credit(KernelTimes { boolean_ms: f64::NAN, tessellate_ms: -3.0 });
// Inside a timed call it would count twice: it is the call's time already.
timed(Kind::Boolean, || credit(t));
});
assert_eq!((got.boolean_ms >= 4.0, got.boolean_ms < 8.0, got.tessellate_ms), (true, true, 1.0), "{got:?}");
}
#[test]
fn inner_captures_add_to_the_outer_one_and_a_panic_restores_it() {
let ((), outer) = capture(|| {
+1
View File
@@ -284,6 +284,7 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) ->
}
"engine.commands" => wrap(app.session.execute("engine.commands", &json!({})).map_err(|e| e.to_string())),
"document.inspect" => wrap(app.session.execute("document.inspect", p).map_err(|e| e.to_string())),
"ui.messages" => ok(crate::messages::control(app, p)),
"ui.inspect" => ok(json!({
"ui": serde_json::to_value(&app.ui).unwrap_or_default(),
"visibility": app.session.visibility,
+6 -2
View File
@@ -1,6 +1,7 @@
//! The Help menu (the ? button on the application bar): Documentation (the online book), About
//! SolidCraft (version, commit, build date, licences, attributions, fonts), the keyboard shortcuts
//! (read only), and Report an Issue, which opens a local editable report draft.
//! (read only), Messages (every status message of the run, #2763), and Report an Issue, which
//! opens a local editable report draft.
use egui::{RichText, vec2};
@@ -43,7 +44,7 @@ pub fn diagnostics(app: &SolveApp) -> String {
)
}
/// Run a Help menu item: `docs`, `about`, `shortcuts`, `report`, `crashes`.
/// Run a Help menu item: `docs`, `about`, `shortcuts`, `messages`, `report`, `crashes`.
pub fn run(app: &mut SolveApp, ctx: &egui::Context, item: &str) {
app.help.menu = false;
match item {
@@ -54,6 +55,7 @@ pub fn run(app: &mut SolveApp, ctx: &egui::Context, item: &str) {
app.keymap.read_only = true;
}
"crashes" => crate::crash_ui::open(app),
"messages" => app.messages.open = true,
"report" => {
let dialog = app.dialog.clone();
let error = dialog.as_ref().and_then(|d| d.error.clone()).or_else(|| app.preview.error.clone());
@@ -74,6 +76,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context, anchor: egui::Pos2) {
("docs", "Documentation"),
("about", "About SolidCraft"),
("shortcuts", "Keyboard Shortcuts"),
("messages", "Messages…"),
("report", "Report an Issue…"),
("crashes", "Crash Reports…"),
] {
@@ -95,6 +98,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context, anchor: egui::Pos2) {
}
about(app, ctx);
crate::crash_ui::show(app, ctx);
crate::messages::show(app, ctx);
}
fn about(app: &mut SolveApp, ctx: &egui::Context) {
+7 -1
View File
@@ -75,6 +75,7 @@ mod material_card_review;
mod measurement_ui_tests;
#[cfg(test)]
mod menu_tests;
pub mod messages;
#[cfg(test)]
mod pattern_arrow_tests;
#[cfg(test)]
@@ -326,6 +327,8 @@ pub struct SolveApp {
pub keymap: keymap::Keymap,
/// The Help menu and the About window.
pub help: help::HelpState,
/// Every status message of this run, for the Messages window ([`messages`], #2763).
pub messages: messages::Messages,
/// An editable local issue draft and optional captured app frame.
pub issue_report: issue_report::ReportState,
/// The Crash Reports window.
@@ -452,6 +455,7 @@ impl SolveApp {
sbox: shortcut_box::ShortcutBox::default(),
keymap: keymap::Keymap::default(),
help: help::HelpState::default(),
messages: messages::Messages::default(),
issue_report: issue_report::ReportState::default(),
crashes: crash_ui::CrashUi::default(),
updater: update::Updater::default(),
@@ -1015,7 +1019,9 @@ impl SolveApp {
}
pub fn set_status(&mut self, s: impl Into<String>, error: bool) {
self.status = Some((s.into(), now_ms(), error));
let (text, at) = (s.into(), now_ms());
self.messages.push(&text, error, at);
self.status = Some((text, at, error));
}
pub fn open_path(&mut self, path: &str) {
+203
View File
@@ -0,0 +1,203 @@
//! Messages (#2763): every status message of this run, kept so it can be read and copied after
//! the status chip has faded. Help › Messages… and a click on the chip open the window; the
//! control channel reads them as `ui.messages`.
use std::collections::VecDeque;
use egui::{RichText, vec2};
use serde_json::{Value, json};
use crate::SolveApp;
use crate::i18n::{format, tr};
use crate::theme::Tokens;
/// Messages kept (the oldest go first).
pub const KEEP: usize = 200;
/// The longest message kept, in characters (a longer one is cut, saying so).
const MAX_CHARS: usize = 4000;
/// One status message.
#[derive(Clone, Debug, PartialEq)]
pub struct Message {
pub text: String,
pub error: bool,
/// When it last came (ms since the Unix epoch).
pub at: f64,
/// How many times in a row it came.
pub count: u32,
}
#[derive(Default)]
pub struct Messages {
/// Oldest first.
list: VecDeque<Message>,
/// The window is open.
pub open: bool,
}
impl Messages {
/// Keep a message: the same one again in a row counts up instead.
pub fn push(&mut self, text: &str, error: bool, at: f64) {
if let Some(last) = self.list.back_mut()
&& last.text == text
&& last.error == error
{
last.count = last.count.saturating_add(1);
last.at = at;
return;
}
let text =
if text.chars().count() > MAX_CHARS { format!("{}…", text.chars().take(MAX_CHARS).collect::<String>()) } else { text.to_string() };
self.list.push_back(Message { text, error, at, count: 1 });
while self.list.len() > KEEP {
self.list.pop_front();
}
}
/// Oldest first.
pub fn iter(&self) -> impl DoubleEndedIterator<Item = &Message> + ExactSizeIterator {
self.list.iter()
}
pub fn clear(&mut self) {
self.list.clear();
}
/// The messages as text, oldest first, one per line: how long ago, `error:` for errors, the
/// text and the repeat count.
pub fn as_text(&self, now: f64) -> String {
self.list.iter().map(|m| format!("{}\t{}", ago(now, m.at), line(m))).collect::<Vec<_>>().join("\n")
}
}
/// A message as one line: `error:` for errors, and `(×n)` when it came more than once.
fn line(m: &Message) -> String {
let repeats = if m.count > 1 { format!(" (×{})", m.count) } else { String::new() };
format!("{}{}{repeats}", if m.error { "error: " } else { "" }, m.text)
}
/// How long ago `at` was, at `now` (both ms): seconds, minutes or hours.
fn ago(now: f64, at: f64) -> String {
let s = ((now - at) / 1000.0).max(0.0).floor();
let (id, n) = if s < 60.0 {
("messages.ago_s", s)
} else if s < 3600.0 {
("messages.ago_min", (s / 60.0).floor())
} else {
("messages.ago_h", (s / 3600.0).floor())
};
format(id, &[("n", &format!("{n:.0}"))])
}
/// `ui.messages`: `clear?: true` empties the list, `open?: bool` shows or hides the window; the
/// reply lists them, oldest first (`text`, `error`, `at` in ms since the epoch, `count`).
pub fn control(app: &mut SolveApp, p: &Value) -> Value {
if p.get("clear").and_then(Value::as_bool) == Some(true) {
app.messages.clear();
}
if let Some(open) = p.get("open").and_then(Value::as_bool) {
app.messages.open = open;
}
let list: Vec<Value> = app.messages.iter().map(|m| json!({"text": m.text, "error": m.error, "at": m.at, "count": m.count})).collect();
json!({ "messages": list, "open": app.messages.open })
}
/// The Messages window.
pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
if !app.messages.open {
return;
}
let t = Tokens::get();
let now = crate::now_ms();
let mut open = true;
crate::frame::window(ctx, tr("messages.title"), crate::frame::Width::Normal)
.id(egui::Id::new("sc_messages"))
.open(&mut open)
.default_size(vec2(460.0, 360.0))
.show(ctx, |ui| {
ui.horizontal(|ui| {
let copy = ui.add_enabled(app.messages.iter().len() > 0, egui::Button::new(tr("messages.copy_all")));
crate::scenario::publish_handle("messages:copy", copy.rect.center());
if copy.clicked() {
ctx.copy_text(app.messages.as_text(now));
}
let clear = ui.add_enabled(app.messages.iter().len() > 0, egui::Button::new(tr("messages.clear")));
crate::scenario::publish_handle("messages:clear", clear.rect.center());
if clear.clicked() {
app.messages.clear();
}
});
ui.separator();
if app.messages.iter().len() == 0 {
ui.label(RichText::new(tr("messages.none")).color(t.text_dim));
return;
}
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
for m in app.messages.iter().rev() {
ui.horizontal_top(|ui| {
ui.add_sized(vec2(70.0, 14.0), egui::Label::new(RichText::new(ago(now, m.at)).small().color(t.text_dim)));
let text = RichText::new(line(m)).color(if m.error { t.error } else { t.text });
ui.add(egui::Label::new(text).wrap().selectable(true));
});
}
});
});
if !open {
app.messages.open = false;
}
// The ages tick on while it is open.
ctx.request_repaint_after(std::time::Duration::from_secs(1));
}
#[cfg(test)]
mod tests {
use super::{KEEP, Messages};
#[test]
fn repeats_count_up_and_the_oldest_go_past_the_limit() {
let mut m = Messages::default();
m.push("Box done", false, 1000.0);
m.push("Box done", false, 2000.0);
m.push("`face` is required", true, 3000.0);
let got: Vec<(&str, bool, u32)> = m.iter().map(|x| (x.text.as_str(), x.error, x.count)).collect();
assert_eq!(got, [("Box done", false, 2), ("`face` is required", true, 1)]);
assert_eq!(m.as_text(63_000.0), "1 min ago\tBox done (×2)\n1 min ago\terror: `face` is required");
for i in 0..KEEP + 5 {
m.push(&format!("message {i}"), false, 0.0);
}
assert_eq!(m.iter().len(), KEEP);
assert_eq!(m.iter().next().map(|x| x.text.as_str()), Some("message 5"), "the oldest went first");
}
#[test]
fn a_very_long_message_is_cut() {
let mut m = Messages::default();
m.push(&"x".repeat(10_000), true, 0.0);
assert_eq!(m.iter().next().map(|x| x.text.chars().count()), Some(4001));
}
/// Status messages land in the list, a click on the chip and Help › Messages… open the window,
/// and `ui.messages` reads, opens and clears it.
#[test]
fn status_messages_are_kept_and_the_window_opens() {
use serde_json::json;
let mut h = crate::scenario::Harness::new();
h.app.home.open = false;
h.app.set_status("STEP export needs a solid body", true);
h.app.set_status("Box done", false);
h.frames(2);
let chip = crate::scenario::handle_at("status:chip").expect("the chip is drawn");
h.call("ui.click", json!({"x": chip.x, "y": chip.y}));
h.frames(2);
assert!(h.app.messages.open, "a click on the chip opens the messages");
assert!(crate::scenario::handle_at("messages:copy").is_some());
let out = h.call("ui.messages", json!({}));
let texts: Vec<&str> = out["result"]["messages"].as_array().into_iter().flatten().filter_map(|m| m["text"].as_str()).collect();
assert_eq!(texts, ["STEP export needs a solid body", "Box done"], "{out}");
assert_eq!(out["result"]["messages"][0]["error"], true);
let out = h.call("ui.messages", json!({"clear": true, "open": false}));
assert_eq!((out["result"]["messages"].as_array().map(Vec::len), out["result"]["open"].as_bool()), (Some(0), Some(false)));
crate::help::run(&mut h.app, &h.ctx.clone(), "messages");
assert!(h.app.messages.open, "Help › Messages… opens it too");
}
}
+2 -2
View File
@@ -297,7 +297,7 @@ pub fn open(app: &mut SolveApp, at: Pos2) -> bool {
fn open_with(app: &mut SolveApp, proj: &Proj, at: Pos2) -> bool {
let (rows, total) = rows_capped(app, proj, at);
if rows.is_empty() {
app.status = Some(("Nothing to select here".into(), crate::now_ms(), false));
app.set_status("Nothing to select here", false);
return false;
}
close(app);
@@ -488,7 +488,7 @@ pub fn cycle_click(app: &mut SolveApp, proj: &Proj, at: Pos2) -> bool {
let next = rows.iter().position(|r| crate::selection::same_item(&r.sel, &c.chosen)).map_or(0, |k| (k + 1) % rows.len());
let Some(row) = rows.get(next).cloned() else { return false };
apply(app, &row, false);
app.status = Some((format!("{} ({} of {})", row.label, next + 1, rows.len()), crate::now_ms(), false));
app.set_status(format!("{} ({} of {})", row.label, next + 1, rows.len()), false);
remember(app, c.at, Some(row.sel));
true
}
+26 -5
View File
@@ -139,7 +139,8 @@ pub struct DeviceMotion {
/// picker is open. Returns whether there was motion to hand over; it then asks for the next frame
/// itself.
pub fn navigate_frame(app: &mut SolveApp, ctx: &egui::Context, mapping: DriverMapping, axes: Axes, seconds: f64) -> bool {
if !app.preferences.space_mouse_enabled || app.home.open || app.file_picker_busy() || axes == Axes::default() {
// Only the window with focus: with two windows open, the cap moves the one being used, not both.
if !app.preferences.space_mouse_enabled || app.home.open || app.file_picker_busy() || axes == Axes::default() || !ctx.input(|i| i.focused) {
return false;
}
let speed = f64::from(app.preferences.space_mouse_speed);
@@ -177,6 +178,15 @@ mod tests {
crate::navigation::device_camera(cam, motion, seconds, height, !sketch, reverse_zoom);
}
/// A window that has run a frame, with or without focus. A context that has never run one
/// reads as unfocused, so the tests run one first, as the app always has.
fn window(focused: bool) -> egui::Context {
let ctx = egui::Context::default();
let mut output = ctx.run_ui(egui::RawInput { focused, ..Default::default() }, |_| {});
output.textures_delta.clear();
ctx
}
/// One frame: the 3D mouse hands its motion over, and the modelling viewport applies it.
fn frame(app: &mut SolveApp, ctx: &egui::Context, mapping: DriverMapping, axes: Axes, seconds: f64) -> bool {
let handed = navigate_frame(app, ctx, mapping, axes, seconds);
@@ -339,7 +349,7 @@ mod tests {
#[test]
fn a_frame_moves_the_view_and_keeps_the_next_frame_coming() {
let ctx = egui::Context::default();
let ctx = window(true);
let mut app = app();
let before = app.cam;
assert!(frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.02));
@@ -351,9 +361,20 @@ mod tests {
assert_eq!(app.cam.distance, still.distance);
}
#[test]
fn only_the_focused_window_moves() {
// Two windows side by side (#2077): the cap moves the one with focus and leaves the other.
let mut app = app();
let before = app.cam;
assert!(!frame(&mut app, &window(false), DriverMapping::default(), PUSH, 0.02));
assert_eq!(app.cam.distance, before.distance);
assert!(frame(&mut app, &window(true), DriverMapping::default(), PUSH, 0.02));
assert!(app.cam.distance < before.distance);
}
#[test]
fn an_open_file_picker_holds_the_view_until_it_closes() {
let ctx = egui::Context::default();
let ctx = window(true);
let mut app = app();
let slot: crate::picker_test_support::Slot = Default::default();
crate::picker_test_support::open(&mut app, &slot);
@@ -372,7 +393,7 @@ mod tests {
#[test]
fn a_long_gap_between_frames_moves_as_far_as_a_short_one() {
let ctx = egui::Context::default();
let ctx = window(true);
let (mut short, mut long) = (app(), app());
frame(&mut short, &ctx, DriverMapping::default(), PUSH, 0.05);
frame(&mut long, &ctx, DriverMapping::default(), PUSH, 30.0);
@@ -387,7 +408,7 @@ mod tests {
#[test]
fn navigation_off_the_start_page_and_a_hostile_speed_leave_the_view_alone() {
let ctx = egui::Context::default();
let ctx = window(true);
let mut off = app();
off.preferences.space_mouse_enabled = false;
let mut home = app();
+5
View File
@@ -2831,6 +2831,11 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
let r = Rect::from_min_size(pos, galley.size() + vec2(16.0, 8.0));
painter.rect_filled(r, 4.0, t.overlay);
painter.galley(pos + vec2(8.0, 4.0), galley, t.text);
// A click opens every message of the run, to read and copy (#2763).
crate::scenario::publish_handle("status:chip", r.center());
if ui.interact(r, egui::Id::new("sc_status_chip"), Sense::click()).on_hover_text(crate::i18n::tr("messages.chip_hint")).clicked() {
app.messages.open = true;
}
ui.ctx().request_repaint_after(std::time::Duration::from_millis(500));
} else {
app.status = None;
+4 -1
View File
@@ -62,7 +62,10 @@ body in `bodies` and the other in `against`, and `skip_within` leaves out pairs
occurrence (`"occurrence"`) or one placed component, its subcomponents included
(`"component"`): the parts of a bought component that touch by design. Distances are measured on
the exact faces and edges; the meshes only rule out pairs that are too far apart, and the pairs
left are checked in parallel. `inspect.interference` remains for the overlaps alone.
left are checked in parallel. `inspect.interference` remains for the overlaps alone: it clears
pairs whose meshes stay apart without intersecting them, intersects the rest in parallel, and
returns after `budget_s` seconds (default 240) at most, listing the pairs it had no time for as
not checked.
**Gear**, **Rack and Pinion** and **Screw** (on the **ASSEMBLE** panel) are motion links whose
ratio comes from the parts rather than a typed number:
+1
View File
@@ -63,6 +63,7 @@ Preferences (File › Preferences) hold the theme, the units of new designs, the
visual style and autosave. Graphics › Colour vision gives the colours that carry a meaning (sketch
states, axes, bends, analyses, icons) values for a weak red, green or blue sense: Protan, Deutan or
Tritan. In a mode, the faces Draft and Accessibility Analysis mark as failing are striped too.
Command messages and errors show for a few seconds in the status chip at the bottom left of the view. Click the chip, or choose Help › **Messages…**, for every message of the session: newest first, errors in red, each line selectable, with **Copy all** for a bug report.
Help › Keyboard Shortcuts lists every key, and File › Keyboard
Shortcuts changes them.
+1
View File
@@ -147,6 +147,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox.
| `ui.screenshot` | `path?` | PNG of the window (needs a presented frame: a minimised or fully covered window answers at once with `hidden: true` and an error; use `ui.render`) |
| `ui.render` | `path`, `width?`, `height?`, `grid?`, `axes?` | Render of the model with the current camera (no window needed), drawn on the app's GPU device with the viewport's pipelines (the reply's `renderer`: `gpu`, or `gpu-software` on a software adapter), in the window's theme (light or dark; `solidcraft-cli snapshot` keeps the light colours); cut by the section the viewport shows (`inspect.section`, an open Section Analysis dialog's preview, a sketch's Slice), with the cut face capped. The ground grid and the origin's axes are drawn as the window shows them (`ui.set` `showGrid` and `showOrigin`, `hiddenOrigin`); `grid` and `axes` (booleans) say otherwise for this render |
| `ui.confirm` | `accept?`: bool | answers the Delete confirmation (shown when a delete takes other features with it or makes some fail); without `accept`, what it lists |
| `ui.messages` | `clear?`: `true` (empty the list), `open?`: bool (show or hide the Messages window) | every status message of this run, oldest first (the last 200; a message repeated in a row is one entry with a `count`): `messages` `[{text, error, at, count}]` (`at` in ms since the Unix epoch), and whether the window is `open` (#2763) |
| `ui.documents` | `action?`: `new`, `switch`, `close`, `quit`; `index?`; `force?` (close without asking); `answer?`: `save`, `dont_save`, `cancel` (answers "save changes?") | the open designs (tabs): names, unsaved flags, the active one, a pending "save changes?" prompt, whether a quit is asking |
| `ui.file` | `path`; `insert?`: bool | starts an interactive background Open or Insert; poll `ui.inspect.file_busy` for completion; the window stays responsive |
| `ui.home` | `open?`: bool; `sample?`: index | the start page: show or hide it, open a built-in sample (once built); returns `open` and the recent designs |
+4
View File
@@ -28,6 +28,8 @@ FULL_FILES = ("Cargo.toml", "Cargo.lock")
IGNORED_PREFIXES = ("docs/", "packaging/")
# Root files that a crate embeds (include_str!), so they are not ignorable documentation.
EMBEDDED = {"ATTRIBUTION.md": "solidcraft-ui-egui"}
# Asset folders that only some packages read: the UI embeds the catalogs, xtask checks them.
EMBEDDED_PREFIXES = {"assets/locales/": ("solidcraft-ui-egui", "xtask")}
def load_metadata(path):
@@ -76,6 +78,8 @@ def select(meta, paths):
hit.add(by_dir[max(owners, key=len)])
elif path in EMBEDDED:
hit.add(EMBEDDED[path])
elif any(path.startswith(p) for p in EMBEDDED_PREFIXES):
hit.update(next(v for p, v in EMBEDDED_PREFIXES.items() if path.startswith(p)))
elif path.startswith(IGNORED_PREFIXES) or ("/" not in path and path.endswith(".md")):
continue
else:
+8
View File
@@ -71,6 +71,14 @@ class RealWorkspace(unittest.TestCase):
def test_docs_only_selects_nothing(self):
self.assertEqual(affected.select(self.meta, ["docs/book/src/dev/testing.md", "CONTRIBUTING.md"]), (False, []))
def test_translation_selects_the_ui_and_xtask_not_the_kernel(self):
full, pk = affected.select(self.meta, ["assets/locales/ja.json", "assets/locales/it.json"])
self.assertFalse(full)
self.assertIn("solidcraft-ui-egui", pk)
self.assertIn("xtask", pk)
self.assertNotIn("solidcraft-kernel", pk)
self.assertNotIn("solidcraft-engine", pk)
if __name__ == "__main__":
unittest.main()