Skip to main content

brep_kernel/feature_pipeline/assembly/
constraints.rs

1//! The assembly-constraint definitions — ONE MODULE PER CONSTRAINT, the
2//! feature-module pattern: each `constraints/<type>.rs` owns everything about its
3//! type — its [`ConstraintTypeDef`] row (names, element count range, duplicate
4//! family, the `applicable` selection-context predicate), its schema entry, and (for
5//! the mate-mapped types) its `map` function. There is no Fixed constraint: a part
6//! is fixed by its own instance setting (ACOMP `isFixed`), and a legacy `fixed` row
7//! in an old document is migrated into that setting by [`super::lifecycle`].
8
9use crate::feature_pipeline::SelectionProbe;
10
11pub(crate) mod angle;
12pub(crate) mod cam;
13pub(crate) mod center;
14pub(crate) mod coincident;
15pub(crate) mod concentric;
16pub(crate) mod distance;
17pub(crate) mod parallel;
18pub(crate) mod path;
19pub(crate) mod gear;
20pub(super) mod mechanical;
21pub(crate) mod perpendicular;
22pub(crate) mod rack_pinion;
23pub(crate) mod screw;
24pub(crate) mod slot;
25pub(crate) mod symmetric;
26pub(crate) mod tangent;
27pub(crate) mod touch_align;
28
29/// One constraint type's static definition.
30pub struct ConstraintTypeDef {
31    /// Canonical `type` string (lowercase snake — the persisted key).
32    pub type_id: &'static str,
33    /// Id-mint prefix (`CONC` → `CONC3`).
34    pub short_name: &'static str,
35    /// The type's ONE icon — a single catalogued glyph character (the app's
36    /// `assets/glyphs` catalog, where Coincident shares `≡` with the sketch
37    /// solver's coincident). Every surface that stands for the type by picture
38    /// alone — the workbench toolbar button, the viewport chip, the tree row's
39    /// glyph column — reads THIS field; nothing derives it from `long_name`.
40    pub icon: &'static str,
41    /// Display label: `"{icon} {label}"` (the context bar draws the leading
42    /// glyph as artwork). Pinned to the other two by a test below.
43    pub long_name: &'static str,
44    /// Plain label for messages ("Duplicate … conflicts with Distance
45    /// constraint DIST4.").
46    pub label: &'static str,
47    /// The accepted `elements` count range, inclusive: the pairing types
48    /// exactly 2, center 3 or 4 (two width faces plus a one-
49    /// or two-element tab). The lifecycle marks a count outside the range
50    /// `incomplete`; the schema's `minSelections`/`maxSelections` mirror it.
51    pub min_elements: usize,
52    pub max_elements: usize,
53    /// Member of the duplicate-detection family (overlapping selection pairs
54    /// conflict across these types).
55    pub duplicate_family: bool,
56    /// Selection-context applicability (the feature `context_applicable`
57    /// pattern, [`crate::feature_pipeline::context_offer`]): does the current
58    /// selection make creating this constraint meaningful? Every element must
59    /// be component geometry (`super::mapping`'s `resolve_element` rejects
60    /// everything else), and the counted kinds are the ones the app's element
61    /// seeder can actually produce (faces/edges, solids as COMPONENT refs —
62    /// never vertices, whose `@`-refs only the modal picker builds).
63    pub applicable: fn(&SelectionProbe) -> bool,
64}
65
66/// Spec §4 table order — also the panel's `+` dropdown order.
67pub const CONSTRAINT_TYPES: [ConstraintTypeDef; 16] = [
68    coincident::DEF,
69    touch_align::DEF,
70    parallel::DEF,
71    distance::DEF,
72    angle::DEF,
73    concentric::DEF,
74    perpendicular::DEF,
75    tangent::DEF,
76    center::DEF,
77    symmetric::DEF,
78    gear::DEF,
79    rack_pinion::DEF,
80    screw::DEF,
81    path::DEF,
82    slot::DEF,
83    cam::DEF,
84];
85
86/// The limit-mate fields Distance and Angle share: a `limit` toggle and the
87/// `minimum`/`maximum` ends, in the constraint's own value convention.
88pub(super) fn limit_fields(unit: &str, step: f64, default_max: f64) -> [(&'static str, serde_json::Value); 3] {
89    [
90        ("limit", serde_json::json!({
91            "type": "boolean",
92            "default_value": false,
93            "hint": "Limit mate: hold the value anywhere between Minimum and Maximum instead of at the target; a drag stops at the ends"
94        })),
95        ("minimum", serde_json::json!({
96            "type": "number",
97            "step": step,
98            "default_value": 0,
99            "hint": format!("Limit mate: the smallest allowed value ({unit}), in the same convention as the target")
100        })),
101        ("maximum", serde_json::json!({
102            "type": "number",
103            "step": step,
104            "default_value": default_max,
105            "hint": format!("Limit mate: the largest allowed value ({unit}), in the same convention as the target")
106        })),
107    ]
108}
109
110/// Turn a mapped Distance/Angle into its limit mate when `limit` is on: the
111/// measuring mate is wrapped in [`crate::MateKind::Limit`] with the entry's
112/// `minimum`/`maximum`, mapped through `to_solver` (the display → solver
113/// convention: the exterior-angle remap, or the identity).
114pub(super) fn apply_limit(
115    entry: &super::ConstraintEntry,
116    mapped: &mut super::mapping::MappedConstraint,
117    env: &crate::feature_pipeline::Env,
118    to_solver: impl Fn(f64) -> f64,
119) -> Result<(), super::mapping::ConstraintFailure> {
120    if !entry.flag("limit") {
121        return Ok(());
122    }
123    let read = |key: &str, default: f64| {
124        entry
125            .number(key, env, default)
126            .map_err(|error| super::mapping::ConstraintFailure::new("error", error))
127    };
128    let (minimum, maximum) = (read("minimum", 0.0)?, read("maximum", 0.0)?);
129    if minimum > maximum {
130        return Err(super::mapping::ConstraintFailure::new(
131            "error",
132            format!("Limit minimum {minimum} is above the maximum {maximum}."),
133        ));
134    }
135    let (a, b) = (to_solver(minimum), to_solver(maximum));
136    let (min, max) = if a <= b { (a, b) } else { (b, a) };
137    for mapped_mate in &mut mapped.mates {
138        let inner = std::mem::replace(&mut mapped_mate.kind, crate::MateKind::Parallel {
139            direction_a: [0.0, 0.0, 1.0],
140            direction_b: [0.0, 0.0, 1.0],
141            align: crate::MateAlign::Any,
142        });
143        mapped_mate.kind = crate::MateKind::Limit { mate: Box::new(inner), min, max };
144    }
145    mapped.target = None;
146    mapped.note = Some(format!("Limit {minimum} to {maximum}"));
147    Ok(())
148}
149
150/// The constraint-form params to HIDE for the current `values` (the feature
151/// dialogs' `feature_hidden_params` hook): a Distance or Angle shows its
152/// `minimum`/`maximum` only with `limit` on, and its single target only with
153/// `limit` off (the target is ignored while the range rules).
154pub fn constraint_hidden_params(type_id: &str, values: &serde_json::Value) -> Vec<&'static str> {
155    let target = match type_id {
156        "distance" => "distance",
157        "angle" => "angle",
158        _ => return Vec::new(),
159    };
160    if values.get("limit").and_then(|limit| limit.as_bool()).unwrap_or(false) {
161        vec![target]
162    } else {
163        vec!["minimum", "maximum"]
164    }
165}
166
167/// Look up a type definition by its canonical `type` string.
168pub fn constraint_type(type_id: &str) -> Option<&'static ConstraintTypeDef> {
169    CONSTRAINT_TYPES.iter().find(|def| def.type_id == type_id)
170}
171
172/// `number` params are expression-capable against the part's expression scope
173/// (the dialog engine's established convention).
174pub fn constraint_schema_catalogue() -> serde_json::Value {
175    serde_json::Value::Array(vec![
176        coincident::schema(),
177        touch_align::schema(),
178        parallel::schema(),
179        distance::schema(),
180        angle::schema(),
181        concentric::schema(),
182        perpendicular::schema(),
183        tangent::schema(),
184        center::schema(),
185        symmetric::schema(),
186        gear::schema(),
187        rack_pinion::schema(),
188        screw::schema(),
189        path::schema(),
190        slot::schema(),
191        cam::schema(),
192    ])
193}
194
195/// A two-element pairing across TWO distinct components (a pair on one rigid
196/// body cannot move anything), counting `seedable` selected elements — the
197/// shared shape behind every pairing type's `applicable`.
198pub(super) fn pair_applicable(probe: &SelectionProbe, seedable: usize) -> bool {
199    probe.all_component && probe.components == 2 && seedable == 2
200}
201
202// --- shared schema-field builders (each module's `schema()` composes these) --
203
204pub(super) fn id_field() -> serde_json::Value {
205    serde_json::json!({
206        "type": "string",
207        "default_value": null,
208        "hint": "Unique identifier for the constraint"
209    })
210}
211
212/// The `elements` reference field: `min..=max` picks from `filter` (the type
213/// def's `min_elements..=max_elements` — a test below pins the two together).
214pub(super) fn elements_field(
215    filter: &[&str],
216    min: usize,
217    max: usize,
218    hint: &str,
219) -> serde_json::Value {
220    serde_json::json!({
221        "type": "reference_selection",
222        "selectionFilter": filter,
223        "multiple": max > 1,
224        "minSelections": min,
225        "maxSelections": max,
226        "default_value": null,
227        "hint": hint
228    })
229}
230
231pub(super) fn schema_entry(
232    def: &ConstraintTypeDef,
233    params: serde_json::Value,
234) -> serde_json::Value {
235    serde_json::json!({
236        "type": def.type_id,
237        "shortName": def.short_name,
238        "longName": def.long_name,
239        "label": def.label,
240        "icon": def.icon,
241        "inputParamsSchema": params,
242    })
243}
244
245
246/// What **Flip** does to one constraint: the parameter patch that selects the
247/// other solution, and how the moving component is seeded so the solve reaches
248/// it (`seed`: `turn` = 180° about an axis through the moving element's anchor,
249/// perpendicular to its direction; `turn-about-reference` = 180° about the
250/// reference element's direction; `mirror` = the moving anchor reflected across
251/// the reference plane; `rotate` = −2θ about the angle axis; `none` = the
252/// solve alone reaches it, or nothing may move). `Err` names why a type has no
253/// other solution. `geoms` are the elements' geometry classes in pick order.
254pub fn flip_rule(constraint_type: &str, params: &serde_json::Value, geoms: &[&str]) -> Result<(serde_json::Value, &'static str), String> {
255    let toggle = |key: &str| {
256        let on = params.get(key).and_then(serde_json::Value::as_bool).unwrap_or(false);
257        serde_json::json!({ key: !on })
258    };
259    let negate = |key: &str| params.get(key).and_then(serde_json::Value::as_f64).map(|value| -value);
260    let limited = params.get("limit").and_then(serde_json::Value::as_bool).unwrap_or(false);
261    let mirrored_range = || {
262        let min = params.get("minimum").and_then(serde_json::Value::as_f64).unwrap_or(0.0);
263        let max = params.get("maximum").and_then(serde_json::Value::as_f64).unwrap_or(0.0);
264        serde_json::json!({ "minimum": -max, "maximum": -min })
265    };
266    match constraint_type {
267        // The explicit facing (`mapping::effective_align`): Flip picks the
268        // other one.
269        "touch_align" | "parallel" | "concentric" | "center" => {
270            let opposed = params.get("facing").and_then(serde_json::Value::as_str) == Some("opposed");
271            Ok((serde_json::json!({ "facing": if opposed { "aligned" } else { "opposed" } }), "turn"))
272        }
273        "gear" | "rack_pinion" | "screw" => Ok((toggle("reverse"), "none")),
274        "path" | "slot" => Ok((toggle("reverse"), "none")),
275        "cam" => Ok((toggle("flip"), "turn")),
276        "distance" => {
277            if geoms.first() != Some(&"plane") {
278                return Err("a distance to a line or point has no side to flip to".into());
279            }
280            if limited {
281                return Ok((mirrored_range(), "mirror"));
282            }
283            let flipped = negate("distance").ok_or("the distance has no value to flip")?;
284            Ok((serde_json::json!({ "distance": flipped }), "mirror"))
285        }
286        "angle" => {
287            if limited {
288                return Ok((mirrored_range(), "rotate"));
289            }
290            let flipped = negate("angle").ok_or("the angle has no value to flip")?;
291            Ok((serde_json::json!({ "angle": flipped }), "rotate"))
292        }
293        "tangent" => Ok((serde_json::json!({}), "mirror")),
294        "perpendicular" => Ok((serde_json::json!({}), "turn-about-reference")),
295        "symmetric" => Err("a symmetric pair has one solution".into()),
296        "coincident" => Err("coincident elements have one solution".into()),
297        other => Err(format!("'{other}' has no flip")),
298    }
299}