diff --git a/assets/locales/pending/joint-find-limits.json b/assets/locales/pending/joint-find-limits.json new file mode 100644 index 000000000..0062eba86 --- /dev/null +++ b/assets/locales/pending/joint-find-limits.json @@ -0,0 +1,86 @@ +{ + "en": { + "cmd.joint_find_limits": "Find Joint Limits", + "joint.find_limits": "Find Limits", + "joint.find_limits_failed": "The search for the limits stopped with an error", + "joint.find_limits_hint": "Fill in the limits from where the parts this joint moves first touch another part, turning or sliding each way from where it is now. It runs on a copy: nothing changes until OK.", + "joint.find_limits_stale": "The joint or the design has changed since these limits were found: find them again", + "joint.finding_limits": "Finding limits…", + "joint.limit_contact": "{side} {value}: {a} touches {b}", + "joint.limit_limit": "{side} {value}: the limit of another value or joint", + "joint.limit_loop": "{side} {value}: a closed loop cannot close past it", + "joint.limit_range": "{side}: no contact within {range}, left as it was", + "joint.limit_turn": "{side} {value}: no contact within one turn", + "joint.limits_overlapping": "Already in each other here: {pairs}. They stop the search only if they go deeper." + }, + "ar": { + "cmd.joint_find_limits": "إيجاد حدود المفصل", + "joint.find_limits": "إيجاد الحدود", + "joint.find_limits_failed": "توقف البحث عن الحدود بسبب خطأ", + "joint.find_limits_hint": "يملأ الحدود من الموضع الذي تلمس فيه القطع التي يحرّكها هذا المفصل قطعةً أخرى لأول مرة، بالدوران أو الانزلاق في الاتجاهين من موضعه الحالي. يجري البحث على نسخة: لا يتغيّر شيء حتى الضغط على OK.", + "joint.find_limits_stale": "تغيّر المفصل أو التصميم منذ إيجاد هذه الحدود: ابحث عنها مرة أخرى", + "joint.finding_limits": "جارٍ إيجاد الحدود…", + "joint.limit_contact": "{side} {value}: {a} يلمس {b}", + "joint.limit_limit": "{side} {value}: حدّ قيمة أخرى أو مفصل آخر", + "joint.limit_loop": "{side} {value}: لا يمكن لحلقة مغلقة أن تنغلق بعده", + "joint.limit_range": "{side}: لا تلامس ضمن {range}، تُرك كما كان", + "joint.limit_turn": "{side} {value}: لا تلامس ضمن دورة واحدة", + "joint.limits_overlapping": "متداخلة بالفعل هنا: {pairs}. لا توقف البحث إلا إذا تداخلت أعمق." + }, + "he": { + "cmd.joint_find_limits": "מציאת גבולות מפרק", + "joint.find_limits": "מציאת גבולות", + "joint.find_limits_failed": "החיפוש אחר הגבולות נעצר עקב שגיאה", + "joint.find_limits_hint": "ממלא את הגבולות לפי המקום שבו החלקים שהמפרק מזיז נוגעים לראשונה בחלק אחר, בסיבוב או בהחלקה לשני הכיוונים מהמקום הנוכחי. החיפוש רץ על עותק: דבר אינו משתנה עד ללחיצה על OK.", + "joint.find_limits_stale": "המפרק או התכן השתנו מאז שהגבולות האלה נמצאו: חפשו אותם שוב", + "joint.finding_limits": "מחפש גבולות…", + "joint.limit_contact": "{side} {value}: {a} נוגע ב-{b}", + "joint.limit_limit": "{side} {value}: הגבול של ערך אחר או של מפרק אחר", + "joint.limit_loop": "{side} {value}: לולאה סגורה אינה יכולה להיסגר מעבר לכך", + "joint.limit_range": "{side}: אין מגע בטווח {range}, נשאר כפי שהיה", + "joint.limit_turn": "{side} {value}: אין מגע בסיבוב אחד", + "joint.limits_overlapping": "כבר חודרים זה לזה כאן: {pairs}. הם עוצרים את החיפוש רק אם יחדרו עמוק יותר." + }, + "ja": { + "cmd.joint_find_limits": "ジョイントの制限を検出", + "joint.find_limits": "制限を検出", + "joint.find_limits_failed": "制限の検出がエラーで停止しました", + "joint.find_limits_hint": "このジョイントが動かす部品が他の部品に最初に触れる位置から制限を入力します。現在の位置から両方向に回転またはスライドして調べます。コピー上で行うため、OK を押すまで何も変わりません。", + "joint.find_limits_stale": "制限を検出した後にジョイントまたは設計が変更されました。もう一度検出してください", + "joint.finding_limits": "制限を検出中…", + "joint.limit_contact": "{side} {value}: {a} が {b} に接触", + "joint.limit_limit": "{side} {value}: 別の値またはジョイントの制限", + "joint.limit_loop": "{side} {value}: これを超えると閉ループが閉じません", + "joint.limit_range": "{side}: {range} 以内に接触なし、そのままにしました", + "joint.limit_turn": "{side} {value}: 1 回転以内に接触なし", + "joint.limits_overlapping": "この位置ですでに重なっています: {pairs}。さらに深く入り込んだ場合にのみ検出が止まります。" + }, + "vi": { + "cmd.joint_find_limits": "Tìm giới hạn khớp nối", + "joint.find_limits": "Tìm giới hạn", + "joint.find_limits_failed": "Việc tìm giới hạn đã dừng do lỗi", + "joint.find_limits_hint": "Điền giới hạn từ vị trí mà các chi tiết do khớp nối này di chuyển lần đầu chạm vào một chi tiết khác, khi xoay hoặc trượt theo cả hai hướng từ vị trí hiện tại. Thực hiện trên một bản sao: không có gì thay đổi cho đến khi bấm OK.", + "joint.find_limits_stale": "Khớp nối hoặc thiết kế đã thay đổi kể từ khi tìm thấy các giới hạn này: hãy tìm lại", + "joint.finding_limits": "Đang tìm giới hạn…", + "joint.limit_contact": "{side} {value}: {a} chạm vào {b}", + "joint.limit_limit": "{side} {value}: giới hạn của một giá trị hoặc khớp nối khác", + "joint.limit_loop": "{side} {value}: vòng kín không thể khép lại quá điểm này", + "joint.limit_range": "{side}: không có tiếp xúc trong phạm vi {range}, giữ nguyên", + "joint.limit_turn": "{side} {value}: không có tiếp xúc trong một vòng quay", + "joint.limits_overlapping": "Đã lồng vào nhau tại đây: {pairs}. Chúng chỉ dừng việc tìm kiếm nếu lồng sâu hơn." + }, + "zh": { + "cmd.joint_find_limits": "查找接头限制", + "joint.find_limits": "查找限制", + "joint.find_limits_failed": "查找限制时出错停止", + "joint.find_limits_hint": "根据此接头移动的零件首次接触其他零件的位置填写限制,从当前位置向两个方向旋转或滑动。在副本上进行:按“确定”前不会更改任何内容。", + "joint.find_limits_stale": "找到这些限制后接头或设计已更改:请重新查找", + "joint.finding_limits": "正在查找限制…", + "joint.limit_contact": "{side} {value}:{a} 接触 {b}", + "joint.limit_limit": "{side} {value}:另一个值或接头的限制", + "joint.limit_loop": "{side} {value}:超过此处闭环无法闭合", + "joint.limit_range": "{side}:{range} 内无接触,保持不变", + "joint.limit_turn": "{side} {value}:一圈内无接触", + "joint.limits_overlapping": "此处已相互重叠:{pairs}。只有更深入时才会停止查找。" + } +} diff --git a/crates/engine/src/cmd/contact_sweep.rs b/crates/engine/src/cmd/contact_sweep.rs index e9a3593a2..826cb8da3 100644 --- a/crates/engine/src/cmd/contact_sweep.rs +++ b/crates/engine/src/cmd/contact_sweep.rs @@ -94,6 +94,7 @@ fn contact_mesh(body: &solidcraft_doc::ModelBody) -> Result { /// A member of a contact set: (occurrence id, name). pub(super) type Member = (u64, String); +#[derive(Clone)] pub(super) struct ContactGeometry { bodies: Vec, /// Body indices, and the set members (occurrence id, name) they are under. @@ -211,6 +212,12 @@ impl ContactGeometry { ContactGeometry { bodies: self.bodies.clone(), pairs: taken, step: self.step } } + /// The diagonal of the box the bodies fill in `s`: past it, a part moving in a straight + /// line meets nothing it has not met. + pub(super) fn reach(&self, s: &Session) -> Result { + Ok(self.bounds(s)?.size().len()) + } + /// How many mesh points are placed for each check. pub(super) fn vertex_count(&self) -> usize { self.bodies.iter().map(|b| b.mesh.positions.len()).fold(0, usize::saturating_add) @@ -315,38 +322,12 @@ impl ContactGeometry { let meshes = self.placed(s)?; // Each mesh's box once, not once per pair it is in. let boxes: Vec = meshes.iter().map(Mesh::bounds).collect(); - for (a, b, oa, ob) in &self.pairs { + for (i, (_, _, oa, ob)) in self.pairs.iter().enumerate() { // Members already found colliding need no more of their bodies tested. if found.contains(&(oa.0.min(ob.0), oa.0.max(ob.0))) { continue; } - let (Some(ma), Some(mb), Some(ba), Some(bb)) = (meshes.get(*a), meshes.get(*b), self.bodies.get(*a), self.bodies.get(*b)) else { - return Err(limit("invalid contact geometry pair")); - }; - let (Some(aabb), Some(bbb)) = (boxes.get(*a), boxes.get(*b)) else { - return Err(limit("invalid contact geometry pair")); - }; - if aabb.max.x < bbb.min.x - || bbb.max.x < aabb.min.x - || aabb.max.y < bbb.min.y - || bbb.max.y < aabb.min.y - || aabb.max.z < bbb.min.z - || bbb.max.z < aabb.min.z - { - continue; - } - let cost = ma - .positions - .len() - // 4 sample points and 3 edges to probe per triangle of `a` against each triangle of `b` (#3323), and the other way round. - .saturating_add(ma.triangles.len().saturating_mul(7)) - .saturating_mul(mb.triangles.len()) - .saturating_add(mb.positions.len().saturating_add(mb.triangles.len().saturating_mul(7)).saturating_mul(ma.triangles.len())); - *work = work.saturating_add(cost); - if *work > budget { - return Err(limit("motion exceeds contact sweep collision budget; simplify the contact set or use smaller increments")); - } - if let Some(depth) = super::mesh_overlap(ma, mb, 1e-4 * ba.size.max(bb.size).max(1.0)) { + if let Some(depth) = self.depth(i, &meshes, &boxes, work, budget)? { found.insert((oa.0.min(ob.0), oa.0.max(ob.0))); out.push((oa.clone(), ob.clone(), depth)); if !all { @@ -356,6 +337,66 @@ impl ContactGeometry { } Ok(out) } + + /// How deep the bodies of each pair pass into each other in `s` (0 where they don't), in + /// the order of the pairs. `work` adds up the cost, refused past `budget`. + pub(super) fn depths(&self, s: &Session, work: &mut usize, budget: usize) -> Result> { + let meshes = self.placed(s)?; + let boxes: Vec = meshes.iter().map(Mesh::bounds).collect(); + (0..self.pairs.len()).map(|i| Ok(self.depth(i, &meshes, &boxes, work, budget)?.unwrap_or(0.0))).collect() + } + + /// The set members pair `i` is between. + pub(super) fn members(&self, i: usize) -> Option<(Member, Member)> { + self.pairs.get(i).map(|(_, _, a, b)| (a.clone(), b.clone())) + } + + /// How far the meshes of pair `i` may stray from their faces (see [`ContactGeometry::chord`]). + pub(super) fn pair_chord(&self, i: usize) -> f64 { + let chord = |b: usize| self.bodies.get(b).map_or(0.0, |b| b.chord); + self.pairs.get(i).map_or(0.0, |(a, b, _, _)| chord(*a).max(chord(*b))) + } + + /// Pair `i` alone (with the same bodies). + pub(super) fn only(&self, i: usize) -> ContactGeometry { + ContactGeometry { bodies: self.bodies.clone(), pairs: self.pairs.get(i).cloned().into_iter().collect(), step: self.step } + } + + /// How deep the bodies of pair `i` (placed as `meshes`, in `boxes`) pass into each other, + /// when more than a touch. + fn depth(&self, i: usize, meshes: &[Mesh], boxes: &[Aabb3], work: &mut usize, budget: usize) -> Result> { + let Some((a, b, _, _)) = self.pairs.get(i) else { return Err(limit("invalid contact geometry pair")) }; + let (Some(ma), Some(mb), Some(ba), Some(bb)) = (meshes.get(*a), meshes.get(*b), self.bodies.get(*a), self.bodies.get(*b)) else { + return Err(limit("invalid contact geometry pair")); + }; + let (Some(aabb), Some(bbb)) = (boxes.get(*a), boxes.get(*b)) else { + return Err(limit("invalid contact geometry pair")); + }; + // Boxes apart, or only touching (parts end to end): `mesh_overlap` finds nothing there, + // so it costs nothing (#5968). + let tol = 1e-4 * ba.size.max(bb.size).max(1.0); + if aabb.max.x < bbb.min.x + tol + || bbb.max.x < aabb.min.x + tol + || aabb.max.y < bbb.min.y + tol + || bbb.max.y < aabb.min.y + tol + || aabb.max.z < bbb.min.z + tol + || bbb.max.z < aabb.min.z + tol + { + return Ok(None); + } + let cost = ma + .positions + .len() + // 4 sample points and 3 edges to probe per triangle of `a` against each triangle of `b` (#3323), and the other way round. + .saturating_add(ma.triangles.len().saturating_mul(7)) + .saturating_mul(mb.triangles.len()) + .saturating_add(mb.positions.len().saturating_add(mb.triangles.len().saturating_mul(7)).saturating_mul(ma.triangles.len())); + *work = work.saturating_add(cost); + if *work > budget { + return Err(limit("motion exceeds contact sweep collision budget; simplify the contact set or use smaller increments")); + } + Ok(super::mesh_overlap(ma, mb, tol)) + } } /// How near two set members come: the bodies under them nearest each other. diff --git a/crates/engine/src/cmd/motion.rs b/crates/engine/src/cmd/motion.rs index f1c5b7448..0cdeda6ea 100644 --- a/crates/engine/src/cmd/motion.rs +++ b/crates/engine/src/cmd/motion.rs @@ -12,8 +12,12 @@ use solidcraft_kernel::Body; use super::CommandSpec; use super::joints::{cannot_move, effective_values, joint_id, occurrence_id, place_holding, value}; use crate::params::{bad, bool_, str_, vec3}; +use crate::schema::motion::{FindLimitsParams, FindLimitsResult}; +use crate::schema::{TypedContract, output_schema_for}; use crate::{EngineError, Result, Session}; +const FIND_LIMITS_CONTRACT: TypedContract = TypedContract::new(); + #[path = "motion_analysis.rs"] mod analysis; #[path = "motion_animation.rs"] @@ -101,6 +105,12 @@ pub static COMMANDS: &[CommandSpec] = &[ .noundo() .params(analysis::INTERFERENCE_DOC), CommandSpec::new("joint.sweep", "Sweep Joint", sweep::sweep).icon("interference").params(sweep::SWEEP_DOC), + CommandSpec::new("joint.find_limits", "Find Joint Limits", crate::checked!("joint.find_limits", sweep::find_limits)) + .icon("interference") + .noundo() + .contract(&FIND_LIMITS_CONTRACT) + .output(output_schema_for::) + .params(sweep::FIND_LIMITS_DOC), CommandSpec::new("motion.list", "List Motion Studies", list_studies).icon("list").noundo(), CommandSpec::new("motion.delete", "Delete Motion Study", delete_study).icon("delete").params("study"), CommandSpec::new("explode.create", "Exploded View", explode_create).at("SOLID", "ASSEMBLE").icon("explode").enabled(has_parts_to_explode).params( diff --git a/crates/engine/src/cmd/motion_sweep.rs b/crates/engine/src/cmd/motion_sweep.rs index faca1f5c8..22541ddb5 100644 --- a/crates/engine/src/cmd/motion_sweep.rs +++ b/crates/engine/src/cmd/motion_sweep.rs @@ -2,19 +2,23 @@ //! toward `to` on a copy of the design (closed loops following on their branch), measures the //! gaps between parts at each sample and bisects the first contact down to `refine`, so a hinge, //! door or linkage answers how far it opens, what stops it and how much room each part has. +//! `joint.find_limits` sweeps each value both ways from where it is, for the joint dialog's Find +//! Limits. use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde_json::{Value, json}; use solidcraft_doc::Document; +use solidcraft_doc::joints::JointKind; use solidcraft_geom::Vec3; use super::analysis::checked_pairs; use super::contact_sweep::{ContactGeometry, Gap}; use super::{drive_with_contact, joint_id, value}; use crate::params::{bad, bool_}; -use crate::{Result, Session}; +use crate::schema::motion::{FindLimitsResult, FoundLimits, Overlap, Stop, Why}; +use crate::{EngineError, Result, Session}; pub const SWEEP_DOC: &str = "joint: id|name; from, to: its value the sweep runs between (degrees for angles, mm for distances, \ or expressions); index? (which value, default 0); step? (between samples, in the joint's unit; default: fine enough that \ @@ -31,12 +35,29 @@ pub const SWEEP_DOC: &str = "joint: id|name; from, to: its value the sweep runs on its frame: these stop it only once they pass into each other deeper than they start), applied. The parts are tested at the samples and through the bisection; the motion is on a copy (closed loops \ follow, contact sets do not stop it)"; +pub const FIND_LIMITS_DOC: &str = "joint: id|name; index? (one value; default every value); refine?, step?, occurrences?, \ + against?, contact_sets? (as joint.sweep) → values: [{index, dof, unit, value (now), min, max, min_by, max_by, range}], \ + each value swept both ways from where it is, its own limits ignored, closed loops following; each side stops at the \ + first contact (bisected to `refine`), where a loop cannot close, or at another limit (another value's, or another joint's through a motion link): min_by/max_by {a, b, at} | \ + \"loop\" | \"limit\" | \"turn\" (an angle with no contact within a turn: a turn from the other side, or ±180° from \ + now when nothing is met at all) | \"range\" (a distance with no contact within the parts' reach: min/max null); \ + touching_at_start, overlapping_at_start: [{a, b, depth_mm}] (already passing into each other: they stop it only going \ + deeper), refine_mm, gap_method, gap_tolerance_mm, pairs (0: no two parts to check, so nothing is swept). The design is \ + not changed"; + /// Most samples a sweep takes before its bisection: each is a solve. const MAX_SAMPLES: usize = 4096; /// Most bisection steps: each halves the bracket around the first contact. const MAX_BISECTIONS: usize = 64; /// Most gap work over a whole sweep (see `ContactGeometry::gaps`). const MAX_WORK: usize = 500_000_000; +/// Most gap work each side of a limit search takes: a whole turn of curved pins passing into each +/// other costs about 20 M a sample, some 500 samples a turn (a few seconds). A 32-bit build, the +/// web, takes half what its `usize` holds, so the work it adds up can still pass it. +const FIND_WORK: usize = { + let most = MAX_WORK.saturating_mul(40); + if most > usize::MAX / 2 { usize::MAX / 2 } else { most } +}; /// The nearest a part came to another along the sweep. struct Nearest { @@ -45,23 +66,86 @@ struct Nearest { to: String, } -pub(super) fn sweep(s: &mut Session, p: &Value) -> Result { - let cmd = "joint.sweep"; +/// One sweep of a joint value. +#[derive(Clone, Copy)] +struct Sweep { + id: u64, + index: usize, + from: f64, + to: f64, + step: Option, + refine: f64, + report_gaps: bool, + /// The gap work it may take. + budget: usize, + /// The value's own limit left out (the copy only). + free: bool, +} + +/// What a sweep found. +struct Swept { + /// The last value clear of contact (or where a loop or limit stopped it), and what stopped + /// it; `None`: it reached `to`. + stop: Option<(f64, Stop)>, + samples: Vec, + nearest: BTreeMap, + touching: Vec<[String; 2]>, + /// Pairs of parts passing into each other at the start deeper than a touch: (a, b, mm). + overlapping: Vec<(String, String, f64)>, + pairs: usize, + chord: f64, + /// The design where it stopped. + doc: Arc, +} + +/// The joint a command sweeps: its id, name and kind (a rigid joint is refused). +fn swept_joint(s: &Session, p: &Value, cmd: &str) -> Result<(u64, String, JointKind)> { let id = joint_id(s, p.get("joint"), cmd)?; let joint = s.doc.assembly.joints.iter().find(|j| j.id == id).ok_or_else(|| bad(cmd, "joint"))?; - let (kind, name) = (joint.kind, joint.name.clone()); - let dofs = kind.dofs().len(); - if dofs == 0 { + if joint.kind.dofs().is_empty() { return Err(bad(cmd, "a rigid joint does not move")); } - let index = match p.get("index") { - None | Some(Value::Null) => 0, + Ok((id, joint.name.clone(), joint.kind)) +} + +/// `index`, below `dofs` (`None`: not given). +fn value_index(p: &Value, dofs: usize, cmd: &str) -> Result> { + match p.get("index") { + None | Some(Value::Null) => Ok(None), Some(v) => v .as_u64() .and_then(|i| usize::try_from(i).ok()) .filter(|i| *i < dofs) - .ok_or_else(|| bad(cmd, format!("`index` must be below {dofs}, the joint's value count")))?, - }; + .map(Some) + .ok_or_else(|| bad(cmd, format!("`index` must be below {dofs}, the joint's value count"))), + } +} + +/// A number above 0, at most `max` (`None`: not given). +fn positive(p: &Value, key: &str, max: f64, cmd: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => v + .as_f64() + .filter(|x| x.is_finite() && *x > 0.0 && *x <= max) + .map(Some) + .ok_or_else(|| bad(cmd, format!("`{key}` must be a number above 0, at most {max}"))), + } +} + +/// The parts the command checks, refused when there are no two to check against each other. +fn pairs_to_check(s: &Session, p: &Value, cmd: &str) -> Result { + let geometry = checked_pairs(s, p, cmd)?; + if !geometry.has_pairs() { + return Err(bad(cmd, "no pairs of parts to check: list two or more `occurrences` with bodies, or give `against`")); + } + Ok(geometry) +} + +pub(super) fn sweep(s: &mut Session, p: &Value) -> Result { + let cmd = "joint.sweep"; + let (id, name, kind) = swept_joint(s, p, cmd)?; + let index = value_index(p, kind.dofs().len(), cmd)?.unwrap_or(0); let angle = kind.is_angle(index); // Shown in degrees for angles, mm for distances. let shown = |v: f64| if angle { v.to_degrees() } else { v }; @@ -70,29 +154,152 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result { None => Err(bad(cmd, format!("give `from` and `to`: the joint's values the sweep runs between (no `{key}`)"))), }; let (from, to) = (end("from")?, end("to")?); - let positive = |key: &str, max: f64| -> Result> { - match p.get(key) { - None | Some(Value::Null) => Ok(None), - Some(v) => v - .as_f64() - .filter(|x| x.is_finite() && *x > 0.0 && *x <= max) - .map(Some) - .ok_or_else(|| bad(cmd, format!("`{key}` must be a number above 0, at most {max}"))), - } - }; - let refine = positive("refine", 1e3)?.unwrap_or(0.01); - let step = positive("step", 1e9)?.map(|x| if angle { x.to_radians() } else { x }); + let refine = positive(p, "refine", 1e3, cmd)?.unwrap_or(0.01); + let step = positive(p, "step", 1e9, cmd)?.map(|x| if angle { x.to_radians() } else { x }); let report_gaps = bool_(p, "report_gaps").unwrap_or(false); let apply = bool_(p, "apply").unwrap_or(false); + let geometry = pairs_to_check(s, p, cmd)?; + let sweep = Sweep { id, index, from, to, step, refine, report_gaps, budget: MAX_WORK, free: false }; + let r = run(s, geometry, sweep, cmd)?; - let mut geometry = checked_pairs(s, p, cmd)?; - if !geometry.has_pairs() { - return Err(bad(cmd, "no pairs of parts to check: list two or more `occurrences` with bodies, or give `against`")); + let applied = apply && !Arc::ptr_eq(&r.doc, &s.doc); + if applied { + let mut doc = (*r.doc).clone(); + doc.assembly.contact_enabled = s.doc.assembly.contact_enabled; + *s.doc_mut() = doc; } + let by = |stop: &Stop| serde_json::to_value(stop).map_err(|e| EngineError::Other(e.to_string())); + let mut out = json!({ + "joint": id, "name": name, "index": index, "unit": if angle { "deg" } else { "mm" }, + "from": shown(from), "to": shown(to), + "stopped_at": r.stop.as_ref().map(|(v, _)| shown(*v)), + "stopped_by": r.stop.as_ref().map(|(_, stop)| by(stop)).transpose()?, + "samples": r.samples, + "refine_mm": refine, + "gap_method": "mesh", "gap_tolerance_mm": r.chord, + "pairs": r.pairs, + "touching_at_start": r.touching, + "applied": applied, + }); + if report_gaps { + out["min_gap"] = + r.nearest.into_iter().map(|(k, g)| (k, json!({"mm": g.mm, "at_value": g.at, "to": g.to}))).collect::>().into(); + } + Ok(out) +} + +pub(super) fn find_limits(s: &mut Session, p: &Value) -> Result { + let cmd = "joint.find_limits"; + // Every search is on a copy: the design is only read. + let s: &Session = s; + let (id, name, kind) = swept_joint(s, p, cmd)?; + let indices: Vec = match value_index(p, kind.dofs().len(), cmd)? { + Some(i) => vec![i], + None => (0..kind.dofs().len()).collect(), + }; + let refine = positive(p, "refine", 1e3, cmd)?.unwrap_or(0.01); + let step = positive(p, "step", 1e9, cmd)?; + // No two parts to check (the joint turns the only part with bodies): nothing can be met, but + // a closed loop or a limit can still stop an angle, swept a degree at a time; a distance has + // nothing to search over. Parts the call names that make no pair are refused, as + // `joint.sweep` refuses them. + let named = p.get("occurrences").is_some_and(|v| !v.is_null()) || bool_(p, "contact_sets").unwrap_or(false); + let geometry = if named { pairs_to_check(s, p, cmd)? } else { checked_pairs(s, p, cmd)? }; + let paired = geometry.has_pairs(); + let now = s.doc.assembly.joints.iter().find(|j| j.id == id).map(|j| j.values.clone()).unwrap_or_default(); + // A distance is searched as far as the parts reach: past it, a straight move meets nothing new. + let reach = if paired { geometry.reach(s)? } else { 0.0 }; + if paired && (!reach.is_finite() || reach <= 0.0) { + return Err(bad(cmd, "the parts have no size to search over")); + } + let turn = std::f64::consts::TAU; + let mut values = Vec::with_capacity(indices.len()); + let mut first: Option = None; + for index in indices { + let angle = kind.is_angle(index); + let shown = |v: f64| if angle { v.to_degrees() } else { v }; + let c = now.get(index).copied().unwrap_or(0.0); + if !c.is_finite() { + return Err(bad(cmd, "the joint's value is not a number")); + } + let range = if angle { turn } else { reach }; + let step = match step { + Some(x) => Some(if angle { x.to_radians() } else { x }), + None if !paired => Some(1f64.to_radians()), + None => None, + }; + let side = |to: f64| { + if !angle && !paired { + return Ok(None); + } + let sweep = Sweep { id, index, from: c, to, step, refine, report_gaps: false, budget: FIND_WORK, free: true }; + Ok::<_, EngineError>(Some(run(s, geometry.clone(), sweep, cmd)?)) + }; + // (value, what stopped it) for each side; `None` value: no limit that side. An angle is + // searched a turn up, then down to a turn below where that stopped: a span of at most a + // turn, each side checked (a motion link can make the way down differ from the way up). + let up = side(c + range)?; + let up_stop = up.as_ref().and_then(|u| u.stop.clone()); + let down = side(if angle { up_stop.as_ref().map_or(c, |(u, _)| *u) - turn } else { c - range })?.and_then(|d| d.stop); + let turned = |v: f64| (Some(v), Stop::Other(Why::Turn)); + let (min, max) = match (angle, up_stop, down) { + (true, None, None) => (turned(c - turn / 2.0), turned(c + turn / 2.0)), + (true, None, Some((d, by))) => ((Some(d), by), turned(d + turn)), + (true, Some((u, by)), None) => (turned(u - turn), (Some(u), by)), + (_, up, down) => { + let found = |stop: Option<(f64, Stop)>| stop.map_or((None, Stop::Other(Why::Range)), |(v, by)| (Some(v), by)); + (found(down), found(up)) + } + }; + values.push(FoundLimits { + index, + dof: kind.dofs().get(index).copied().unwrap_or("value").to_string(), + unit: if angle { "deg" } else { "mm" }.to_string(), + value: shown(c), + min: min.0.map(shown), + max: max.0.map(shown), + min_by: min.1, + max_by: max.1, + range: shown(range), + }); + if first.is_none() { + first = up; + } + } + let reply = FindLimitsResult { + joint: id, + name, + values, + refine_mm: refine, + gap_method: "mesh".into(), + gap_tolerance_mm: first.as_ref().map_or(0.0, |f| f.chord), + pairs: first.as_ref().map_or(0, |f| f.pairs), + touching_at_start: first.as_ref().map(|f| f.touching.clone()).unwrap_or_default(), + overlapping_at_start: first + .map(|f| f.overlapping) + .unwrap_or_default() + .into_iter() + .map(|(a, b, depth_mm)| Overlap { a, b, depth_mm }) + .collect(), + param_warnings: Vec::new(), + }; + serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) +} + +/// Drive the value `sw` names from `sw.from` toward `sw.to` on a copy of `s`, checking the pairs +/// of `geometry` at each sample, and bisect the first contact. +fn run(s: &Session, mut geometry: ContactGeometry, sw: Sweep, cmd: &str) -> Result { + let Sweep { id, index, from, to, step, refine, report_gaps, budget, free } = sw; + let (dofs, angle) = + s.doc.assembly.joints.iter().find(|j| j.id == id).map(|j| (j.kind.dofs().len(), j.kind.is_angle(index))).ok_or_else(|| bad(cmd, "joint"))?; + let shown = |v: f64| if angle { v.to_degrees() } else { v }; // On a copy, played from where the parts are placed; contact sets do not stop it. let mut t = s.scratch(); t.pending_moves.clear(); t.doc_mut().assembly.contact_enabled = false; + if free && let Some(limit) = t.doc_mut().assembly.joints.iter_mut().find(|j| j.id == id).and_then(|j| j.limits.get_mut(index)) { + *limit = None; + } let given = BTreeSet::from([(id, index)]); let drive_to = |t: &mut Session, v: f64| -> Result { let mut q = t.doc.assembly.joints.iter().find(|j| j.id == id).map(|j| j.values.clone()).unwrap_or_default(); @@ -118,17 +325,26 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result { let key = |x: u64, y: u64| (x.min(y), x.max(y)); // Pairs touching where the sweep starts (parts joined face to face, a door on its frame) // stop it only when they pass into each other, deeper than they start (by more than their - // meshes can be off): a door resting on its frame cannot sweep through it. - let start: Vec = geometry.gaps(&t, touch, &mut work, MAX_WORK)?; + // meshes can be off): a door resting on its frame cannot sweep through it. Each pair of their + // bodies is held to its own depth: pins already in each other don't hide arms of the same + // parts meeting later, and plates that only come flush (parts end to end) never stop it. + let start: Vec = geometry.gaps(&t, touch, &mut work, budget)?; let touching: BTreeSet<(u64, u64)> = start.iter().map(|g| key(g.a.0, g.b.0)).collect(); - let touching_names: Vec = start.iter().map(|g| json!([g.a.1, g.b.1])).collect(); + let touching_names: Vec<[String; 2]> = start.iter().map(|g| [g.a.1.clone(), g.b.1.clone()]).collect(); let resting = geometry.take_pairs(|x, y| touching.contains(&key(x, y))); - let rest_depth: BTreeMap<(u64, u64), f64> = if resting.has_pairs() { - resting.hits(&t, &mut work, MAX_WORK, true)?.into_iter().map(|(a, b, d)| (key(a.0, b.0), d)).collect() - } else { - BTreeMap::new() - }; - let margin = touch.max(2.0 * resting.chord()); + let rest_depth: Vec = if resting.has_pairs() { resting.depths(&t, &mut work, budget)? } else { Vec::new() }; + // A pair of bodies' own margin: flat faces against flat faces are exact. + let margin = |i: usize| touch.max(2.0 * resting.pair_chord(i)); + // Parts already passing into each other, deeper than a touch: the deepest of their bodies. + let mut overlapping: BTreeMap<(u64, u64), (String, String, f64)> = BTreeMap::new(); + for (i, depth) in rest_depth.iter().enumerate() { + if *depth > margin(i) + && let Some((a, b)) = resting.members(i) + { + let entry = overlapping.entry(key(a.0, b.0)).or_insert((a.1, b.1, 0.0)); + entry.2 = entry.2.max(*depth); + } + } // The samples run to where the joint gets: a limit or a loop can stop it short of `to`, and // the default count is for the motion up to there. One more drive toward `to` then finds @@ -145,7 +361,7 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result { let mut end = t.scratch(); drive_to(&mut end, to)?; let n = geometry.samples(&t, &end).map_err(|e| match e { - crate::EngineError::BadParams { msg, .. } => bad(cmd, format!("{msg} (or give a `step`)")), + EngineError::BadParams { msg, .. } => bad(cmd, format!("{msg} (or give a `step`)")), e => e, })?; let got = reached(&end); @@ -163,7 +379,7 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result { samples.push(json!({"value": shown(v)})); return Ok(()); } - let gaps = geometry.gaps(t, f64::INFINITY, work, MAX_WORK)?; + let gaps = geometry.gaps(t, f64::INFINITY, work, budget)?; match gaps.first() { Some(g) => samples.push(json!({"value": shown(v), "min_gap_mm": g.mm, "pair": [g.a.1, g.b.1]})), None => samples.push(json!({"value": shown(v), "min_gap_mm": null, "pair": null})), @@ -178,24 +394,23 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result { Ok(()) }; let contact = |t: &Session, work: &mut usize, geometry: &ContactGeometry| -> Result> { - if let Some(g) = geometry.gaps(t, touch, work, MAX_WORK)?.into_iter().next() { + if let Some(g) = geometry.gaps(t, touch, work, budget)?.into_iter().next() { return Ok(Some(g)); } if !resting.has_pairs() { return Ok(None); } - let deeper = - resting.hits(t, work, MAX_WORK, true)?.into_iter().find(|(a, b, d)| *d > rest_depth.get(&key(a.0, b.0)).copied().unwrap_or(0.0) + margin); - let Some((a, b, _)) = deeper else { return Ok(None) }; - // Where: the nearest points of that pair (passing into each other, at no gap). - let k = key(a.0, b.0); - let at = resting.gaps(t, touch, work, MAX_WORK)?.into_iter().find(|g| key(g.a.0, g.b.0) == k).map_or((Vec3::ZERO, Vec3::ZERO), |g| g.at); + let depths = resting.depths(t, work, budget)?; + let deeper = depths.iter().enumerate().find(|(i, d)| **d > rest_depth.get(*i).copied().unwrap_or(0.0) + margin(*i)).map(|(i, _)| i); + let Some((i, (a, b))) = deeper.and_then(|i| resting.members(i).map(|m| (i, m))) else { return Ok(None) }; + // Where: the nearest points of those bodies (passing into each other, at no gap). + let at = resting.only(i).gaps(t, touch, work, budget)?.into_iter().next().map_or((Vec3::ZERO, Vec3::ZERO), |g| g.at); Ok(Some(Gap { a, b, mm: 0.0, at })) }; record(&t, from, &mut work, &geometry)?; let (mut lo_doc, mut lo_v): (Arc, f64) = (t.doc.clone(), from); - let mut stop: Option<(f64, Value)> = None; + let mut stop: Option<(f64, Stop)> = None; for target in targets { let r = drive_to(&mut t, target)?; let v = reached(&t); @@ -217,7 +432,7 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result { } t.doc = lo_doc.clone(); let at = (hit.at.0 + hit.at.1) * 0.5; - stop = Some((lo_v, json!({"a": hit.a.1, "b": hit.b.1, "at": [at.x, at.y, at.z]}))); + stop = Some((lo_v, Stop::Contact { a: hit.a.1, b: hit.b.1, at: [at.x, at.y, at.z] })); break; } // (The drive on toward `to` past a limit stays where the last sample was.) @@ -225,37 +440,24 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result { record(&t, v, &mut work, &geometry)?; } if r["stopped_by_loop"].is_object() { - stop = Some((v, json!("loop"))); + stop = Some((v, Stop::Other(Why::Loop))); break; } if (v - target).abs() > 1e-9 { - stop = Some((v, json!("limit"))); + stop = Some((v, Stop::Other(Why::Limit))); break; } (lo_doc, lo_v) = (t.doc.clone(), v); } - - let applied = apply && !Arc::ptr_eq(&t.doc, &s.doc); - if applied { - let mut doc = (*t.doc).clone(); - doc.assembly.contact_enabled = s.doc.assembly.contact_enabled; - *s.doc_mut() = doc; - } - let mut out = json!({ - "joint": id, "name": name, "index": index, "unit": if angle { "deg" } else { "mm" }, - "from": shown(from), "to": shown(to), - "stopped_at": stop.as_ref().map(|(v, _)| shown(*v)), - "stopped_by": stop.map(|(_, by)| by), - "samples": samples, - "refine_mm": refine, - "gap_method": "mesh", "gap_tolerance_mm": geometry.chord(), - "pairs": geometry.pair_count() + resting.pair_count(), - "touching_at_start": touching_names, - "applied": applied, - }); - if report_gaps { - out["min_gap"] = - nearest.into_iter().map(|(k, g)| (k, json!({"mm": g.mm, "at_value": g.at, "to": g.to}))).collect::>().into(); - } - Ok(out) + let pairs = geometry.pair_count() + resting.pair_count(); + Ok(Swept { + stop, + samples, + nearest, + touching: touching_names, + overlapping: overlapping.into_values().collect(), + pairs, + chord: geometry.chord(), + doc: t.doc, + }) } diff --git a/crates/engine/src/cmd/motion_sweep_tests.rs b/crates/engine/src/cmd/motion_sweep_tests.rs index 4802100d2..88e84882e 100644 --- a/crates/engine/src/cmd/motion_sweep_tests.rs +++ b/crates/engine/src/cmd/motion_sweep_tests.rs @@ -1,6 +1,8 @@ //! `joint.sweep` against stops worked out by hand: a door swinging into a block, the four-bar's //! rocker meeting a stop and a Watt six-bar's output link meeting one, each checked against the //! linkage solved with circle intersections and a separating-axis test of the parts' outlines. +//! `joint.find_limits` against the same stops met both ways, a slider, the four-bar's toggles +//! and the Hinge Assembly sample. use serde_json::{Value, json}; use solidcraft_geom::Vec3; @@ -305,3 +307,174 @@ fn a_watt_six_bar_output_meets_a_stop() { let names = [r["stopped_by"]["a"].as_str(), r["stopped_by"]["b"].as_str()]; assert!(names.contains(&Some("Output:1")) && names.contains(&Some("Stop:1")), "{r}"); } + +/// The limits `joint.find_limits` found for the joint's first value: (min, max, min_by, max_by). +fn limits(r: &Value) -> (f64, f64, Value, Value) { + let v = &r["values"][0]; + (num(&v["min"]), num(&v["max"]), v["min_by"].clone(), v["max_by"].clone()) +} + +/// A stop (or overlap) between parts `a` and `b`. +fn by_parts(by: &Value, a: &str, b: &str) -> bool { + let names = [by["a"].as_str(), by["b"].as_str()]; + names.contains(&Some(a)) && names.contains(&Some(b)) +} + +/// Opened, the door meets the block as in `a_door_swings_until_it_meets_the_block`; closed the +/// other way round, the face through its hinge line reaches the block's corner (60, 50) first, +/// a turn back. Its own limits are left out of the search, and the design is not changed. +#[test] +fn find_limits_meets_the_block_both_ways_round() { + let mut s = door(); + run(&mut s, "joint.limits", json!({"joint": "Hinge", "min": -30, "max": 10})); + let corner = |x: f64, y: f64| y.atan2(x) - (4.0 / x.hypot(y)).asin(); + let max = [(60.0, 30.0), (80.0, 30.0), (60.0, 50.0), (80.0, 50.0)].iter().map(|(x, y)| corner(*x, *y)).fold(f64::INFINITY, f64::min).to_degrees(); + let min = 50f64.atan2(60.0).to_degrees() - 360.0; + let before = s.doc.clone(); + let r = run(&mut s, "joint.find_limits", json!({"joint": "Hinge", "refine": 0.001})); + assert_eq!(*s.doc, *before, "the search leaves the design as it was"); + let (lo, hi, lo_by, hi_by) = limits(&r); + assert!((hi - max).abs() < 0.01 && hi <= max + 1e-9, "max {hi}°, the block is met at {max}°: {r}"); + assert!((lo - min).abs() < 0.01 && lo >= min - 1e-9, "min {lo}°, the block is met at {min}°: {r}"); + assert!(by_parts(&lo_by, "Door:1", "Block:1") && by_parts(&hi_by, "Door:1", "Block:1"), "{r}"); + assert_eq!((r["values"][0]["unit"].as_str(), num(&r["values"][0]["value"]), num(&r["values"][0]["range"])), (Some("deg"), 0.0, 360.0)); + assert!(r["touching_at_start"].as_array().is_some_and(Vec::is_empty) && r["overlapping_at_start"].as_array().is_some_and(Vec::is_empty), "{r}"); +} + +/// A door that meets nothing on a whole turn either way gets a turn, half each way from where +/// it is: alone (nothing to meet, nothing swept) and with a lamp above it. +#[test] +fn find_limits_of_a_door_that_meets_nothing_spans_a_turn() { + let mut s = Session::default(); + block(&mut s, "Door", [0.0, 0.0, 0.0], [100.0, 4.0, 50.0]); + run( + &mut s, + "joint.create", + json!({"type": "revolute", "a": {"occurrence": 0, "point": [0, 0, 0]}, "b": {"occurrence": "Door", "point": [0, 0, 0]}, "flip": true, "name": "Hinge"}), + ); + run(&mut s, "joint.drive", json!({"joint": "Hinge", "value": 30})); + for lamp in [false, true] { + if lamp { + block(&mut s, "Lamp", [0.0, 0.0, 80.0], [20.0, 20.0, 20.0]); + } + let r = run(&mut s, "joint.find_limits", json!({"joint": "Hinge"})); + let (lo, hi, lo_by, hi_by) = limits(&r); + assert!((lo + 150.0).abs() < 1e-6 && (hi - 210.0).abs() < 1e-6, "{lo}° … {hi}°"); + assert_eq!((lo_by, hi_by, num(&r["pairs"])), (json!("turn"), json!("turn"), if lamp { 1.0 } else { 0.0 }), "{r}"); + } +} + +/// A slider pushed into a wall stops where they meet; the other way it meets nothing within the +/// parts' reach, and that side has no limit. +#[test] +fn find_limits_of_a_slider_leaves_a_free_side_open() { + let mut s = Session::default(); + block(&mut s, "Slide", [0.0, 0.0, 0.0], [10.0, 10.0, 10.0]); + block(&mut s, "Wall", [50.0, -20.0, -20.0], [10.0, 50.0, 50.0]); + let at = |o: &str| json!({"occurrence": o, "point": [0, 0, 0], "z": [1, 0, 0]}); + run(&mut s, "joint.create", json!({"type": "slider", "a": at("Wall"), "b": at("Slide"), "flip": true, "name": "Rail"})); + let id = occ(&s, "Wall"); + run(&mut s, "occurrence.ground", json!({"occurrence": id, "grounded": true})); + let r = run(&mut s, "joint.find_limits", json!({"joint": "Rail", "refine": 0.001})); + let v = &r["values"][0]; + // The joint's value grows one way or the other along X: the wall is met 40 mm away. + let (closed, open) = if v["max"].is_null() { ("min", "max") } else { ("max", "min") }; + assert!((num(&v[closed]).abs() - 40.0).abs() < 0.002 && num(&v[closed]).abs() <= 40.0 + 1e-9, "{r}"); + assert!(by_parts(&v[format!("{closed}_by")], "Slide:1", "Wall:1"), "{r}"); + assert!(v[open].is_null() && v[format!("{open}_by")] == "range", "{r}"); + assert_eq!(v["unit"], "mm"); + assert!(num(&v["range"]) > 60.0, "the parts reach past the wall: {r}"); +} + +/// The four-bar's rocker swings between its toggles, where the loop can no longer close (|Q| = +/// 70 and |Q| = 30, about 69.3° and 139.2° from the ground line): both sides stop there. +#[test] +fn find_limits_of_a_four_bar_rocker_stops_at_its_toggles() { + let (mut s, _, q0) = four_bar(); + let start = q0.y.atan2(q0.x - 45.0).to_degrees(); + // |Q|² = 45² + 40² + 2·45·40·cos φ. + let toggle = |q: f64| ((q * q - 3625.0) / 3600.0).acos().to_degrees() - start; + let r = run(&mut s, "joint.find_limits", json!({"joint": "Rocker", "occurrences": ["Rocker"], "against": ["Ground"]})); + let (lo, hi, lo_by, hi_by) = limits(&r); + assert_eq!((lo_by, hi_by), (json!("loop"), json!("loop")), "{r}"); + assert!(hi > toggle(30.0) - 1.0 && hi <= toggle(30.0) + 1e-6, "max {hi}°, the loop closes up to {}°", toggle(30.0)); + assert!(lo < toggle(70.0) + 1.0 && lo >= toggle(70.0) - 1e-6, "min {lo}°, the loop closes down to {}°", toggle(70.0)); +} + +/// The Hinge Assembly sample (#5968): its leaves sit end to end along the pin, mated face to face +/// at the pin's end, so they touch across that end and meet nothing else on a whole turn either +/// way. A whole turn each way is what `joint.sweep` ran out of work on (from 60° to 360°); the +/// search has the room for it. +#[test] +fn find_limits_of_the_hinge_sample_spans_a_turn() { + let sample = crate::sample::samples().into_iter().find(|x| x.name == "Hinge Assembly").expect("the hinge sample"); + let mut s = Session::default(); + s.run_script(&(sample.script)()).unwrap_or_else(|e| panic!("{e}")); + let r = run(&mut s, "joint.find_limits", json!({"joint": "Hinge"})); + let (lo, hi, lo_by, hi_by) = limits(&r); + assert!((lo + 120.0).abs() < 1e-6 && (hi - 240.0).abs() < 1e-6, "{lo}° … {hi}°: {r}"); + assert_eq!((lo_by, hi_by), (json!("turn"), json!("turn")), "{r}"); + let touching = r["touching_at_start"].as_array().cloned().unwrap_or_default(); + assert!(touching.len() == 1 && touching[0].as_array().is_some_and(|p| p.contains(&json!("Leaf A:1")) && p.contains(&json!("Leaf B:1"))), "{r}"); + assert!(r["overlapping_at_start"].as_array().is_some_and(Vec::is_empty), "{r}"); + // The same whole turn fits `joint.sweep`'s own work now (pairs whose boxes only touch cost + // nothing), where it ran out going from 60° to 0° two degrees at a time. + let r = run(&mut s, "joint.sweep", json!({"joint": "Hinge", "from": 60, "to": 0, "step": 2})); + assert!(r["stopped_by"].is_null(), "{r}"); +} + +/// Two parts of two bodies each: a post with a pin of radius 5 on Z and a stop block at +/// (40…50, 10…20), and an arm turning about Z with a pin of radius 3 inside the post's (the pins +/// are in each other where it starts, as deep wherever the arm turns) and a 4 mm plate from x 10 +/// to 60. The plate's faces, 2 mm off the axis, meet the block's corners as the door's do: the +/// pins in each other must not hide that. +#[test] +fn find_limits_sees_arms_meet_behind_pins_already_in_each_other() { + let mut s = Session::default(); + for (name, corner, size, radius) in [("Post", [40.0, 10.0, 0.0], [10.0, 10.0, 20.0], 5), ("Arm", [10.0, -2.0, 0.0], [50.0, 4.0, 20.0], 3)] { + block(&mut s, name, corner, size); + run(&mut s, "solid.cylinder", json!({"base": [0, 0, 0], "axis": [0, 0, 1], "radius": radius, "height": 20, "operation": "new"})); + } + run(&mut s, "component.activate", json!({"component": "root"})); + let post = occ(&s, "Post"); + run(&mut s, "occurrence.ground", json!({"occurrence": post, "grounded": true})); + let at = |o: &str| json!({"occurrence": o, "point": [0, 0, 0], "z": [0, 0, 1]}); + run(&mut s, "joint.create", json!({"type": "revolute", "a": at("Post"), "b": at("Arm"), "flip": true, "name": "Swing"})); + let corners = [(40.0f64, 10.0f64), (50.0, 10.0), (40.0, 20.0), (50.0, 20.0)]; + let max = corners.iter().map(|(x, y)| y.atan2(*x) - (2.0 / x.hypot(*y)).asin()).fold(f64::INFINITY, f64::min).to_degrees(); + let min = corners.iter().map(|(x, y)| y.atan2(*x) + (2.0 / x.hypot(*y)).asin()).fold(f64::NEG_INFINITY, f64::max).to_degrees() - 360.0; + let r = run(&mut s, "joint.find_limits", json!({"joint": "Swing", "refine": 0.001})); + let (lo, hi, lo_by, hi_by) = limits(&r); + // The joint's value may grow either way round Z. + let near = |a: f64, b: f64| (a - b).abs() < 0.05; + assert!((near(hi, max) && near(lo, min)) || (near(hi, -min) && near(lo, -max)), "{lo}° … {hi}°, the block is met at {max}° and {min}°: {r}"); + assert!(by_parts(&lo_by, "Arm:1", "Post:1") && by_parts(&hi_by, "Arm:1", "Post:1"), "{r}"); + let overlapping = r["overlapping_at_start"].as_array().cloned().unwrap_or_default(); + assert!(overlapping.len() == 1 && by_parts(&overlapping[0], "Arm:1", "Post:1") && num(&overlapping[0]["depth_mm"]) > 1.0, "{r}"); +} + +#[test] +fn find_limits_refuses_what_it_cannot_do() { + let mut s = door(); + for p in [ + json!({}), + json!({"joint": "Nope"}), + json!({"joint": 5.5}), + json!({"joint": "Hinge", "index": 1}), + json!({"joint": "Hinge", "index": -1}), + json!({"joint": "Hinge", "refine": 0}), + json!({"joint": "Hinge", "refine": 1e9}), + json!({"joint": "Hinge", "refine": "nan"}), + json!({"joint": "Hinge", "step": 0}), + json!({"joint": "Hinge", "step": -1}), + json!({"joint": "Hinge", "step": 1e-9}), + json!({"joint": "Hinge", "occurrences": ["Door"]}), + json!({"joint": "Hinge", "against": ["Block"]}), + json!({"joint": "Hinge", "occurrences": ["Door"], "against": ["Door"]}), + json!({"joint": "Hinge", "occurrences": ["Door", "Block"], "contact_sets": true}), + ] { + assert!(s.execute("joint.find_limits", &p).is_err(), "{p}"); + } + run(&mut s, "joint.as_built", json!({"type": "rigid", "a": "Block", "b": "Door", "name": "Lock"})); + assert!(s.execute("joint.find_limits", &json!({"joint": "Lock"})).is_err(), "a rigid joint does not move"); +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index c58be27f7..e4ef29e95 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -62,6 +62,7 @@ pub mod file; pub mod inspect; pub mod joints; pub mod mass_properties; +pub mod motion; pub mod print_face; pub mod render; pub mod render_lights; diff --git a/crates/engine/src/schema/motion.rs b/crates/engine/src/schema/motion.rs new file mode 100644 index 000000000..87ad20186 --- /dev/null +++ b/crates/engine/src/schema/motion.rs @@ -0,0 +1,166 @@ +//! Contracts and result types for the commands in `cmd/motion.rs`. + +use std::borrow::Cow; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; + +/// Find where each value of a joint can go before the parts it moves touch another body. The +/// design is not changed. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct FindLimitsParams { + pub joint: JointRef, + /// Which value (0 for a revolute's angle). Default: every value of the joint. + #[serde(default)] + pub index: Option, + /// mm: each stop is bisected until no part moves more than this between the last clear value + /// and the touching one (above 0, at most 1000). Default: 0.01. + #[serde(default)] + pub refine: Option, + /// Between samples, in the value's unit (degrees for angles, mm for distances; above 0). + /// Default: fine enough that no part passes through another between two. + #[serde(default)] + pub step: Option, + /// The parts checked against each other. Default: every occurrence. + #[serde(default, deserialize_with = "super::present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "Vec")] + pub occurrences: Option>, + /// The parts that stay: each of `occurrences` is checked only against these. + #[serde(default)] + pub against: Option>, + /// Check the pairs of the design's contact sets instead (not with `occurrences`). + #[serde(default)] + pub contact_sets: Option, +} + +/// A joint by its id (a number) or its name. +#[derive(Debug)] +pub struct JointRef; + +impl<'de> Deserialize<'de> for JointRef { + fn deserialize>(d: D) -> Result { + match Value::deserialize(d)? { + Value::Number(_) | Value::String(_) => Ok(JointRef), + _ => Err(D::Error::custom("must be an id or a name")), + } + } +} + +impl JsonSchema for JointRef { + fn schema_name() -> Cow<'static, str> { + "JointRef".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"description": "A joint's id (a number) or its name.", "type": ["number", "string"]}) + } +} + +/// An occurrence by its id (a number) or its name. +#[derive(Debug)] +pub struct PartRef; + +impl<'de> Deserialize<'de> for PartRef { + fn deserialize>(d: D) -> Result { + match Value::deserialize(d)? { + Value::Number(_) | Value::String(_) => Ok(PartRef), + _ => Err(D::Error::custom("an occurrence must be an id or a name")), + } + } +} + +impl JsonSchema for PartRef { + fn schema_name() -> Cow<'static, str> { + "PartRef".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"description": "An occurrence's id (a number) or its name.", "type": ["number", "string"]}) + } +} + +/// What stopped one side of a sweep. +#[derive(Clone, Debug, PartialEq, Serialize, JsonSchema)] +#[serde(untagged)] +pub enum Stop { + /// Two parts touch. + Contact { + a: String, + b: String, + /// Where they touch (world, mm). + at: [f64; 3], + }, + /// `loop`: a closed loop can no longer close; `limit`: the limit of another of the joint's + /// values, or of another joint through a motion link; `turn`: no contact within one turn, so the side is a turn from the other; + /// `range`: no contact within the parts' reach (a distance), so the side has no limit. + Other(Why), +} + +/// Why a side stopped short of contact. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, JsonSchema)] +#[serde(rename_all = "lowercase")] +pub enum Why { + Loop, + Limit, + Turn, + Range, +} + +/// One value's limits. +#[derive(Debug, Serialize, JsonSchema)] +pub struct FoundLimits { + /// Which value of the joint. + pub index: usize, + /// Its name (angle, distance, …). + pub dof: String, + /// `deg` or `mm`. + pub unit: String, + /// Where it is now, which the search starts from. + pub value: f64, + /// The lowest value clear of contact, or `null` (`min_by` is `range`). + pub min: Option, + /// The highest value clear of contact, or `null` (`max_by` is `range`). + pub max: Option, + pub min_by: Stop, + pub max_by: Stop, + /// How far each way the search went: a turn (360) for an angle, the parts' reach for a + /// distance. + pub range: f64, +} + +/// Two parts already passing into each other where the search starts. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Overlap { + pub a: String, + pub b: String, + /// How deep (mm). + pub depth_mm: f64, +} + +/// What `joint.find_limits` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct FindLimitsResult { + pub joint: u64, + pub name: String, + pub values: Vec, + pub refine_mm: f64, + /// `mesh`: distances between the parts' tessellations. + pub gap_method: String, + /// How far those can be off: 0 when every face is flat. + pub gap_tolerance_mm: f64, + /// How many pairs of parts are checked. + pub pairs: usize, + /// Pairs of parts touching where the search starts: they stop it only once they pass into + /// each other deeper than they start. + pub touching_at_start: Vec<[String; 2]>, + /// Pairs of those already passing into each other, deeper than a touch. + pub overlapping_at_start: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "motion_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/motion_tests.rs b/crates/engine/src/schema/motion_tests.rs new file mode 100644 index 000000000..e7135a8bc --- /dev/null +++ b/crates/engine/src/schema/motion_tests.rs @@ -0,0 +1,59 @@ +use serde_json::{Value, json}; + +use super::{FindLimitsParams, FindLimitsResult}; +use crate::Session; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["against", "contact_sets", "index", "joint", "occurrences", "refine", "step"]); +} + +#[test] +fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[ + ("joint.find_limits", json!({"joint": true})), + ("joint.find_limits", json!({"joint": null})), + ("joint.find_limits", json!({"joint": "Hinge"})), + ]); +} + +/// A 100 × 4 × 50 door hinged about Z at the origin, a block in its way and a slider beside it. +fn door() -> Session { + let mut s = Session::default(); + for (name, corner, size) in [("Door", [0, 0, 0], [100, 4, 50]), ("Block", [60, 30, 0], [20, 20, 50]), ("Slide", [0, -40, 0], [10, 10, 10])] { + for (id, p) in [ + ("component.activate", json!({"component": "root"})), + ("component.create", json!({"name": name, "grounded": false})), + ("solid.box", json!({"length": size[0], "width": size[1], "height": size[2], "corner": corner})), + ] { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")); + } + } + for p in [ + json!({"type": "revolute", "a": {"occurrence": 0, "point": [0, 0, 0]}, "b": {"occurrence": "Door", "point": [0, 0, 0]}, "flip": true, "name": "Hinge"}), + json!({"type": "slider", "a": {"occurrence": 0, "point": [0, -40, 0], "z": [1, 0, 0]}, "b": {"occurrence": "Slide", "point": [0, -40, 0], "z": [1, 0, 0]}, "flip": true, "name": "Rail"}), + ] { + s.execute("joint.create", &p).unwrap_or_else(|e| panic!("{e}")); + } + s +} + +#[test] +fn replies_match_the_output_schema() { + let schema = output_schema_for::(); + let schema = schema.as_value(); + let mut s = door(); + s.param_check = ParamCheck::Warn; + for p in [json!({"joint": "Hinge"}), json!({"joint": "Rail", "index": 0, "refine": 0.1, "occurrences": ["Slide", "Door"]})] { + let r = s.execute("joint.find_limits", &p).unwrap_or_else(|e| panic!("{e}")); + assert!(r.get("param_warnings").is_none(), "{r}"); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + } + // A misspelt key still runs in warn, and says so. + let r = s.execute("joint.find_limits", &json!({"joint": "Hinge", "refin": 0.1})).unwrap_or_else(|e| panic!("{e}")); + assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()) && conforms(schema, schema, &r), "{r}"); + let required: Vec<&str> = schema.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect(); + assert!(!required.contains(&"param_warnings")); +} diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index 5110404de..bcda5c8c0 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -131,6 +131,32 @@ pub enum Asm { /// The snap under the cursor, remembered for the selection it was found for. pub type Hover = Option<(Sel, Option)>; +/// A search off the window thread: where it leaves its reply, and what it searched. +#[derive(Clone, Debug)] +pub struct Search { + reply: std::sync::Arc>>>, + searched: Searched, +} + +/// The design and the joint (the commands OK would run for it) a search was for. +#[derive(Clone, Debug)] +pub struct Searched { + design: std::sync::Weak, + joint: Vec<(String, Value)>, +} + +impl Searched { + fn now(app: &SolveApp, f: &JointForm, inputs: &[SelInput]) -> Result { + Ok(Searched { design: std::sync::Arc::downgrade(&app.session.doc), joint: edit_commands(app, f, inputs)? }) + } + + /// Whether the design and the dialog's joint are still the ones searched. + fn current(&self, app: &SolveApp, f: &JointForm, inputs: &[SelInput]) -> bool { + self.design.upgrade().is_some_and(|d| std::sync::Arc::ptr_eq(&d, &app.session.doc)) + && edit_commands(app, f, inputs).is_ok_and(|now| now == self.joint) + } +} + /// The Joint and As-built Joint dialogs. #[derive(Clone, Debug)] pub struct JointForm { @@ -150,6 +176,14 @@ pub struct JointForm { pub offset: [String; 3], /// Per joint value: limited, minimum, maximum. pub limits: Vec<(bool, String, String)>, + /// Find Limits: the search under way (`joint.find_limits`'s reply lands here). + pub search: Option, + /// What Find Limits found for each value (a line under its rows). + pub found: Vec, + /// What the last search said about them all: parts already in each other, or why it failed. + pub found_note: Option, + /// The design and the joint (as the dialog had it) the found limits are for. + pub searched: Option, pub animate: bool, /// Animation phase, 0…1. pub phase: f64, @@ -168,6 +202,10 @@ impl JointForm { angle_shown: "0 deg".into(), offset: std::array::from_fn(|_| crate::length_input::default(doc, "0")), limits: Vec::new(), + search: None, + found: Vec::new(), + found_note: None, + searched: None, animate: false, phase: 0.0, hover: None, @@ -708,7 +746,13 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Asm, inputs: &mut [Se form_row(ui, "Motion", |ui| { ui.label(""); }); + let was = f.kind; choice_row(ui, "Type", "jt_type", &mut f.kind, &TYPE_LABELS); + if f.kind != was { + // What Find Limits found was for the other type's values. + (f.search, f.found_note, f.searched) = (None, None, None); + f.found.clear(); + } f.fit_limits(&app.session.doc); if !f.as_built { enter |= expr_row(ui, "Angle", &mut f.angle); @@ -734,6 +778,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Asm, inputs: &mut [Se } }); crate::ui_kit::section(ui, "joint_limits", "Limits", false, |ui| { + let found = f.found.clone(); for (i, (on, lo, hi)) in f.limits.iter_mut().enumerate() { let name = kind.dofs().get(i).copied().unwrap_or("value"); form_row(ui, &format!("{} limits", capital(name)), |ui| { @@ -743,6 +788,16 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Asm, inputs: &mut [Se enter |= expr_row(ui, " Minimum", lo); enter |= expr_row(ui, " Maximum", hi); } + if let Some(note) = found.get(i).filter(|n| !n.is_empty()) { + ui.vertical(|ui| { + for line in note.lines() { + ui.add(egui::Label::new(RichText::new(line).size(t.font_small).color(t.text_dim)).wrap()); + } + }); + } + } + if let Some(id) = f.editing { + find_limits_row(app, ui, f, id, inputs); } }); } else { @@ -931,6 +986,192 @@ fn capital(s: &str) -> String { c.next().map(|f| f.to_uppercase().collect::() + c.as_str()).unwrap_or_default() } +/// The Limits section's Find Limits row: the button, or the search under way with Cancel; and +/// what the last search said about all the values. +fn find_limits_row(app: &mut SolveApp, ui: &mut egui::Ui, f: &mut JointForm, id: u64, inputs: &[SelInput]) { + let t = Tokens::get(); + if let Some(search) = &f.search { + // A poisoned lock: the search's thread panicked. + let reply = search.reply.lock().map(|mut r| r.take()).unwrap_or_else(|_| Some(Err(crate::i18n::tr("joint.find_limits_failed").to_string()))); + match reply { + Some(reply) => { + // Found for a design changed since (by a script, the control channel, undo), or + // a joint the dialog has changed since (its sides, flip, angle or offset): dropped. + let searched = search.searched.clone(); + f.search = None; + if searched.current(app, f, inputs) { + f.searched = Some(searched); + fill_limits(&app.session.doc, f, reply); + } else { + f.found_note = Some(crate::i18n::tr("joint.find_limits_stale").to_string()); + } + // The rows above were drawn before this: once more, with what was found. + ui.ctx().request_repaint(); + } + None => ui.ctx().request_repaint_after(std::time::Duration::from_millis(100)), + } + } + // What it found stops applying once the joint or the design changes: its notes go, and the + // dialog says so (the values filled in stay, to keep or edit). + if f.search.is_none() + && let Some(searched) = &f.searched + && !searched.current(app, f, inputs) + { + f.searched = None; + f.found.clear(); + f.found_note = Some(crate::i18n::tr("joint.find_limits_stale").to_string()); + } + form_row(ui, "", |ui| { + if f.search.is_some() { + ui.horizontal(|ui| { + ui.add(egui::Spinner::new().size(t.font_small)); + ui.label(RichText::new(crate::i18n::tr("joint.finding_limits")).color(t.text_dim)); + if crate::ui_kit::button(ui, crate::i18n::tr("ui.cancel"), crate::ui_kit::Button::Normal).clicked() { + // Its thread finishes within its work budget; the reply is left unread. + f.search = None; + } + }); + } else if crate::ui_kit::button(ui, crate::i18n::tr("joint.find_limits"), crate::ui_kit::Button::Normal) + .on_hover_text(crate::i18n::tr("joint.find_limits_hint")) + .clicked() + { + find_limits(app, f, id, inputs); + } + }); + if let Some(note) = &f.found_note { + ui.vertical(|ui| { + ui.add(egui::Label::new(RichText::new(note).color(t.warning)).wrap()); + }); + } +} + +/// The commands OK would run for the joint as the dialog has it (its sides as picked in +/// `inputs`), but its limits (what Find Limits fills in). +fn edit_commands(app: &SolveApp, f: &JointForm, inputs: &[SelInput]) -> Result, String> { + let edit = Dialog::new(Kind::Assembly(Asm::Joint(Box::new(f.clone()))), inputs.to_vec()); + Ok(crate::dialogs::apply_commands(app, &edit)?.into_iter().filter(|(id, _)| id != "joint.limits").collect()) +} + +/// Find Limits: on a copy of the design, the joint as the dialog has it now (its type and +/// alignment, as OK would leave them), then `joint.find_limits` on it. Off the window thread +/// when the app runs commands there, else at once. +fn find_limits(app: &SolveApp, f: &mut JointForm, id: u64, inputs: &[SelInput]) { + (f.found_note, f.search, f.searched) = (None, None, None); + f.found.clear(); + let searched = match Searched::now(app, f, inputs) { + Ok(s) => s, + Err(e) => { + f.found_note = Some(e); + return; + } + }; + // A joint OK would refuse (an expression that doesn't read) says so at once, before any search. + let mut probe = app.session.scratch(); + if let Some(e) = searched.joint.iter().find_map(|(id, p)| probe.execute(id, p).err()) { + f.found_note = Some(e.to_string()); + return; + } + let mut commands = searched.joint.clone(); + commands.push(("joint.find_limits".into(), json!({ "joint": id }))); + // The search's reply, or the first command that failed. + fn reply(replies: Vec>) -> Result { + let mut last = Err(String::new()); + for r in replies { + last = Ok(r.map_err(|e| e.to_string())?); + } + last + } + #[cfg(not(target_arch = "wasm32"))] + if app.apply_off_thread.is_some() { + let search = Search { reply: Default::default(), searched: searched.clone() }; + let (ahead, out, list) = (app.session.ahead(), search.reply.clone(), commands.clone()); + let spawned = std::thread::Builder::new().name("find limits".into()).spawn(move || { + let r = reply(ahead.replies(&list)); + if let Ok(mut slot) = out.lock() { + *slot = Some(r); + } + }); + if spawned.is_ok() { + f.search = Some(search); + return; + } + } + f.searched = Some(searched); + fill_limits(&app.session.doc, f, reply(app.session.ahead().replies(&commands))); +} + +/// Fill the limits rows from `joint.find_limits`'s reply: each side found, rounded inward (a +/// tenth of a degree, a hundredth of the design's length unit), and its row ticked once both +/// are; a side with nothing to meet keeps what it had. A line under each row says what stopped +/// each side. +fn fill_limits(doc: &solidcraft_engine::doc::Document, f: &mut JointForm, reply: Result) { + let r = match reply { + Ok(r) => r, + Err(e) => { + (f.found_note, f.searched) = (Some(e), None); + return; + } + }; + let kind = f.joint_kind(); + let unit = crate::length_input::unit(doc).to_string(); + let scale = solidcraft_engine::doc::expr::unit_info(&unit).map(|(_, scale)| scale).filter(|s| *s > 0.0).unwrap_or(1.0); + f.found = vec![String::new(); f.limits.len()]; + for v in r["values"].as_array().into_iter().flatten() { + let Some(i) = v["index"].as_u64().and_then(|i| usize::try_from(i).ok()) else { continue }; + let (Some(row), Some(note)) = (f.limits.get_mut(i), f.found.get_mut(i)) else { continue }; + let angle = kind.is_angle(i); + // A side as the dialog shows it: rounded toward the joint's value, so it stays clear; as + // found where rounding would pass the joint's value (a stop nearer than the rounding). + let (min, max) = (v["min"].as_f64().filter(|x| x.is_finite()), v["max"].as_f64().filter(|x| x.is_finite())); + let now = v["value"].as_f64().filter(|x| x.is_finite()); + let step = if angle { 0.1 } else { 0.01 * scale }; + let lo = min.map(|x| Some((x / step - 1e-6).ceil() * step).filter(|r| now.is_none_or(|c| *r <= c)).unwrap_or(x)); + let hi = max.map(|x| Some((x / step + 1e-6).floor() * step).filter(|r| now.is_none_or(|c| *r >= c)).unwrap_or(x)); + let (lo, hi) = if lo.zip(hi).is_some_and(|(lo, hi)| lo > hi) { (min, max) } else { (lo, hi) }; + let shown = |x: f64| { + if angle { (num(x, "deg"), format!("{}°", crate::dialogs_coupling::trim(x))) } else { (num(x / scale, &unit), num(x / scale, &unit)) } + }; + let (min, max) = (lo.map(shown), hi.map(shown)); + let mut lines = Vec::new(); + for (label, found, by) in [("Minimum", &min, &v["min_by"]), ("Maximum", &max, &v["max_by"])] { + let which = crate::i18n::tr_label(label); + let value = found.as_ref().map(|(_, shown)| shown.as_str()).unwrap_or_default(); + lines.push(match by.as_str() { + Some("loop") => crate::i18n::format("joint.limit_loop", &[("side", which), ("value", value)]), + Some("limit") => crate::i18n::format("joint.limit_limit", &[("side", which), ("value", value)]), + Some("turn") => crate::i18n::format("joint.limit_turn", &[("side", which), ("value", value)]), + Some(_) => { + // Down to a tenth, so it never claims more than was searched. + let range = (v["range"].as_f64().filter(|x| x.is_finite()).unwrap_or(0.0) / scale * 10.0).floor() / 10.0; + crate::i18n::format("joint.limit_range", &[("side", which), ("range", &num(range, &unit))]) + } + None => { + let (a, b) = (by["a"].as_str().unwrap_or_default(), by["b"].as_str().unwrap_or_default()); + crate::i18n::format("joint.limit_contact", &[("side", which), ("value", value), ("a", a), ("b", b)]) + } + }); + } + *note = lines.join("\n"); + // A side with nothing to meet has no limit to fill in: the row keeps what it had. + row.0 |= min.is_some() && max.is_some(); + if let Some((lo, _)) = min { + row.1 = lo; + } + if let Some((hi, _)) = max { + row.2 = hi; + } + } + let overlapping: Vec = r["overlapping_at_start"] + .as_array() + .into_iter() + .flatten() + .map(|o| format!("{} / {}", o["a"].as_str().unwrap_or_default(), o["b"].as_str().unwrap_or_default())) + .collect(); + if !overlapping.is_empty() { + f.found_note = Some(crate::i18n::format("joint.limits_overlapping", &[("pairs", &overlapping.join(", "))])); + } +} + /// Run the check (overlaps, pairs closer than the clearance, each body's nearest neighbour) and /// find the overlapping volumes (world placement) to show in red. fn interference(app: &mut SolveApp, picked: &[Sel], clearance: &str) -> (Value, Vec) { diff --git a/crates/ui-egui/src/dialogs_assembly_tests.rs b/crates/ui-egui/src/dialogs_assembly_tests.rs index 04510a3cf..a8829079e 100644 --- a/crates/ui-egui/src/dialogs_assembly_tests.rs +++ b/crates/ui-egui/src/dialogs_assembly_tests.rs @@ -1231,3 +1231,100 @@ fn components_from_bodies_dialog_select_all_cancel_and_ok() { h.app.run("edit.undo", json!({})).unwrap(); assert_eq!(h.app.session.doc, before, "the dialog applies one undoable command"); } + +/// Edit Joint's Find Limits on a door hinged at the origin with a block in its way: clicked in +/// the Limits section, it fills both limits from where the door meets the block each way round +/// (rounded toward the door's value, so they stay clear), says what stopped each side under the +/// row, and OK keeps them. The design is not changed until then. +#[test] +fn find_limits_fills_the_limits_from_where_the_door_meets_the_block() { + let mut s = Session::default(); + for (name, corner, size) in [("Door", [0, 0, 0], [100, 4, 50]), ("Block", [60, 30, 0], [20, 20, 50])] { + for (id, p) in [ + ("component.activate", json!({"component": "root"})), + ("component.create", json!({"name": name, "grounded": false})), + ("solid.box", json!({"length": size[0], "width": size[1], "height": size[2], "corner": corner})), + ] { + s.execute(id, &p).unwrap(); + } + } + let hinge = json!({"type": "revolute", "a": {"occurrence": 0, "point": [0, 0, 0]}, "b": {"occurrence": "Door", "point": [0, 0, 0]}, "flip": true, "name": "Hinge"}); + s.execute("joint.create", &hinge).unwrap(); + let mut app = SolveApp::new(s, Services::default()); + let id = app.session.doc.assembly.joints[0].id; + app.dialog = edit_joint(&app, id); + let before = app.session.doc.clone(); + let ctx = crate::fonts::test_context(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0)); + let frame = |app: &mut SolveApp, events: Vec| { + let input = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| crate::dialogs::show(app, ui.ctx())); + // Nothing is painted: drop the texture changes (an unapplied delta panics on drop). + out.textures_delta.clear(); + out + }; + let click = |app: &mut SolveApp, text: &str| { + // The auto-sized dialog takes a few frames to settle. + for _ in 0..3 { + frame(app, vec![]); + } + let out = frame(app, vec![]); + let at = text_at(&out, text).unwrap_or_else(|| panic!("no `{text}` to click")); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, vec![egui::Event::PointerMoved(at)]); + frame(app, vec![button(true)]); + frame(app, vec![button(false)]); + }; + click(&mut app, &crate::i18n::tr_label("Limits").to_uppercase()); + click(&mut app, crate::i18n::tr("joint.find_limits")); + assert_eq!(*app.session.doc, *before, "nothing changes until OK"); + let Some(Kind::Assembly(Asm::Joint(f))) = app.dialog.as_ref().map(|d| &d.kind) else { panic!("the dialog stays open") }; + // The door's face 4 mm off its hinge line meets the block's corner (80, 30) opening, and the + // face through its hinge line the corner (60, 50) a turn back the other way. + let max = (30f64.atan2(80.0) - (4.0 / 80f64.hypot(30.0)).asin()).to_degrees(); + let min = 50f64.atan2(60.0).to_degrees() - 360.0; + let (lo, hi) = (((min * 10.0) - 1e-6).ceil() / 10.0, ((max * 10.0) + 1e-6).floor() / 10.0); + assert_eq!(f.limits[0], (true, num(lo, "deg"), num(hi, "deg")), "{:?}", f.found); + assert!(f.found[0].contains("Door:1") && f.found[0].contains("Block:1") && f.found[0].lines().count() == 2, "{:?}", f.found); + assert!(f.found_note.is_none(), "{:?}", f.found_note); + let d = app.dialog.as_ref().unwrap(); + for (id, p) in apply_commands(&app, d).unwrap() { + app.run(&id, p).unwrap(); + } + let (a, b) = app.session.doc.assembly.joints[0].limits[0].unwrap(); + assert!((a.to_degrees() - lo).abs() < 1e-9 && (b.to_degrees() - hi).abs() < 1e-9, "{a} {b}"); +} + +/// The search runs on the joint as the dialog has it, not as saved: a door edited to swing the +/// other way (flipped) before Find Limits gets that door's limits, which OK then applies with it. +/// A slider whose way out is free leaves that side's field as it was and the row unticked. +#[test] +fn find_limits_searches_the_joint_as_edited_and_leaves_a_free_side() { + let mut app = two_boxes(); + let (a, b) = (occ(&app, "A"), occ(&app, "B")); + app.run("joint.create", json!({"type": "slider", "a": {"occurrence": a, "face": [20, 10, 5]}, "b": {"occurrence": b, "face": [30, 10, 5]}})) + .unwrap(); + let id = app.session.doc.assembly.joints[0].id; + let mut d = edit_joint(&app, id).unwrap(); + let Kind::Assembly(Asm::Joint(f)) = &mut d.kind else { panic!("no edit") }; + let untouched = f.limits[0].clone(); + // With the sides as the dialog opened on them (Edit Joint's side picks). + assert_eq!(d.inputs.len(), 2); + find_limits(&app, f, id, &d.inputs); + // B slides into A one way (they touch face to face already: it can't go further) and away + // from it the other, where nothing is in its way. + assert_eq!(f.limits[0].0, untouched.0, "one side found: the row stays as it was: {:?}", f.found); + assert!(f.limits[0].1 == untouched.1 || f.limits[0].2 == untouched.2, "{:?} {:?}", f.limits, f.found); + assert!(f.found[0].contains(crate::i18n::tr_label("Minimum")) && f.found[0].contains(crate::i18n::tr_label("Maximum")), "{:?}", f.found); + assert!(f.found_note.is_none(), "{:?}", f.found_note); + // Edited after the search, the joint is no longer the one searched (its notes then go). + let searched = f.searched.clone().expect("what was searched"); + assert!(searched.current(&app, f, &d.inputs)); + f.flip = !f.flip; + assert!(!searched.current(&app, f, &d.inputs), "a flipped joint is not the one searched"); + f.flip = !f.flip; + // A form that can't be applied says why instead. + f.offset[2] = "nonsense".into(); + find_limits(&app, f, id, &d.inputs); + assert!(f.found_note.is_some() && f.found.is_empty(), "{:?}", f.found_note); +} diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index 512d56bd6..4447479e7 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -383,6 +383,25 @@ listed in `touching_at_start` and stop the sweep only once they pass into each o they start. The sweep runs on a copy (closed loops follow, contact sets don't stop it) and leaves the design as it was unless `apply` is true. +**Find Limits.** In **Edit Joint**, the **Limits** section's **Find Limits** button fills in each +value's Minimum and Maximum from where the parts the joint moves first touch another part, +turning or sliding each way from where the joint is now, and ticks its limits. It searches the +joint as the dialog has it (a type, flip or offset changed but not yet applied included), on a +copy: nothing changes until **OK**, so the values can still be rounded or edited. They are +rounded toward the joint's value (a tenth of a degree, a hundredth of the length unit) so they +stay clear, and a line under each value says what stopped each side. An angle is searched a turn +each way: a side that meets nothing is set a turn from the other side, or half a turn each way +when nothing is met at all. A distance is searched as far as the parts reach; a side that meets +nothing there keeps what it had, and the limits stay off until both sides are found. Parts +already in each other where the joint is now are named, and stop the search only once they go +deeper. The search runs while the window goes on (Cancel drops it). `joint.find_limits {joint, +index?, refine?, step?, occurrences?, against?, contact_sets?}` answers the same: for each value +its `min` and `max` (`null` where a distance meets nothing), what stopped each side (`min_by`, +`max_by`: the two parts and where they touch, or `"loop"`, `"limit"` (the limit of +another of its values, or of another joint through a motion link), `"turn"` or `"range"`), the `range` searched, and the parts `touching_at_start` +and `overlapping_at_start` (with `depth_mm`). The joint's own limits are left out of the search, +closed loops follow, and each side is bisected to `refine` as `joint.sweep` does. + **Insert Design** (`component.insert_design {path, translate?}`, on the **ASSEMBLE** panel and in the **File** menu) adds a component linked to another saved design, so each part can live in its own document. When other designs are open in tabs, the button first lists them under diff --git a/skills/solidcraft-mechanisms/SKILL.md b/skills/solidcraft-mechanisms/SKILL.md index 35a806445..c3f214ad0 100644 --- a/skills/solidcraft-mechanisms/SKILL.md +++ b/skills/solidcraft-mechanisms/SKILL.md @@ -60,6 +60,7 @@ Written against SolidCraft `main` after 0.11.1, which counts the degrees of free - **Plot:** `motion.plot {"study":..., "joints":[...], "duration":seconds}` answers each joint value's `value`, `velocity` and `acceleration` per sample (finite differences; per step, or per second with a duration), and with `"occurrence"` and `"point"` a point's `position`, `velocity`, `acceleration`, `speed`. Check a follower's rate against the analytic one this way, without changing the design. - **Collisions:** `motion.interference {"study":..., "occurrences":[...], "against":[...]}` plays the study (contact sets don't stop it) and lists each colliding pair with `first_step` and `steps` ranges; `clear: true` when none and every step was checked (never while `truncated`: then it stopped at `checked_to`; give a gear train or other detailed parts more time with `budget_s`). It takes at most 256 bodies: on a big design list the moving part as `occurrences` and what it must miss as `against`. Parts joined at a knuckle often overlap by design and show up at every step. - **Sweep until contact:** `joint.sweep {"joint":..., "from":0, "to":120, "occurrences":[...], "against":[...], "report_gaps":true}` answers how far a hinge, door or linkage opens: `stopped_at` (last clear value, bisected to `refine` mm, default 0.01), `stopped_by` `{a, b, at}` (or `"loop"`, `"limit"`), per-sample `min_gap_mm` and the nearest each part came (`min_gap`). It runs on a copy; `"apply":true` leaves the design at the stop. Pairs touching at `from` (`touching_at_start`) stop it only once they pass into each other. +- **Find limits:** `joint.find_limits {"joint":...}` sweeps each value both ways from where it is (its own limits ignored, on a copy) and answers per value `min`, `max`, `min_by`/`max_by` (`{a, b, at}`, `"loop"`, `"limit"`, `"turn"`: nothing met within a turn, `"range"`: a distance meets nothing, `null` value). Set the joint's limits from it with `joint.limits`. A full turn of curved parts resting in each other can take a few seconds. ## Verify - **Each joint:** `execute occurrence.properties {"occurrence":"Wing:1"}` (about 2 KB) gives the world bbox, centre of mass and inertia of one occurrence. Joining must not move them.