Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Configurations: a parameter edit runs the suppression rules whose condition reads what changed (#6303)

NOWN-DEVf54ad0f12f43
diff --git a/crates/doc/src/config_rules.rs b/crates/doc/src/config_rules.rs
index ebd01a3a6a..87dea95f3c 100644
--- a/crates/doc/src/config_rules.rs
+++ b/crates/doc/src/config_rules.rs
@@ -235,7 +235,61 @@ fn condition(doc: &Document, values: &BTreeMap<String, expr::Value>, value: &Rul
}
}
+/// The features whose suppression a condition reads.
+fn suppression_reads(c: &RuleCondition) -> Vec<u64> {
+ match c {
+ RuleCondition::Always | RuleCondition::Parameter { .. } => Vec::new(),
+ RuleCondition::All { conditions } | RuleCondition::Any { conditions } => conditions.iter().flat_map(suppression_reads).collect(),
+ RuleCondition::Not { condition } => suppression_reads(condition),
+ RuleCondition::Suppression { feature, .. } => vec![*feature],
+ }
+}
+
impl Document {
+ /// After a plain parameter edit (`before`: the parameter values before it): the enabled rules
+ /// that switch a feature's suppression and whose condition reads a parameter whose value
+ /// changed, or the suppression of a feature switched earlier in this pass, applied in their
+ /// order as activation applies them. A switch parameter alone so switches its features.
+ /// Driven parameters and restrictions still wait for a configuration edit or activation, and
+ /// a rule whose condition reads nothing that changed leaves its feature as it is. A rule that
+ /// cannot be evaluated (a missing parameter) is skipped: it never blocks the edit.
+ /// Returns the features switched, with their new suppression.
+ pub fn apply_suppression_rules(&mut self, before: &BTreeMap<String, expr::Value>) -> Vec<(u64, bool)> {
+ if !self.configs.rules.iter().any(|r| r.enabled && matches!(r.effect, RuleEffect::DriveSuppression { .. })) {
+ return Vec::new();
+ }
+ let (values, _) = self.param_values();
+ let changed: BTreeSet<&String> = values
+ .iter()
+ .filter(|(name, v)| before.get(*name).is_none_or(|b| !close(b.v, v.v) || b.len != v.len || b.ang != v.ang))
+ .map(|(name, _)| name)
+ .chain(before.keys().filter(|name| !values.contains_key(*name)))
+ .collect();
+ if changed.is_empty() {
+ return Vec::new();
+ }
+ let mut switched: Vec<(u64, bool)> = Vec::new();
+ for rule in self.configs.rules.clone() {
+ let RuleEffect::DriveSuppression { feature, value } = rule.effect else { continue };
+ if !rule.enabled {
+ continue;
+ }
+ let reads = rule.parameter_references().iter().any(|n| changed.contains(n))
+ || suppression_reads(&rule.condition).iter().any(|f| switched.iter().any(|(s, _)| s == f));
+ if !reads || !condition(self, &values, &rule.condition, rule.length_unit.as_deref()).unwrap_or(false) {
+ continue;
+ }
+ if let Some(f) = self.feature_mut(feature)
+ && f.suppressed != value
+ {
+ f.suppressed = value;
+ switched.retain(|(s, _)| *s != feature);
+ switched.push((feature, value));
+ }
+ }
+ switched
+ }
+
/// Apply ordered drives, then enforce all matched restrictions on the final state.
/// Running on a scratch document makes a failing rule fully atomic for callers.
pub(super) fn evaluate_configuration_rules(&mut self) -> Result<Vec<RuleTrace>> {
diff --git a/crates/engine/src/cmd/config.rs b/crates/engine/src/cmd/config.rs
index e8916bb1a6..36e47ae490 100644
--- a/crates/engine/src/cmd/config.rs
+++ b/crates/engine/src/cmd/config.rs
@@ -443,6 +443,43 @@ mod tests {
run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap_or(f64::NAN)
}
+ #[test]
+ fn a_switch_parameter_alone_switches_the_features_its_rules_suppress() {
+ // A 10 mm cube with a 4 mm hole cut through it; `Enable` and the hole's suppression are
+ // configured, with one rule each way. A plain parameter edit runs them: no activation.
+ let mut s = Session::default();
+ run(&mut s, "parameters.add", json!({"name": "Enable", "expression": "1", "unit": ""}));
+ run(&mut s, "parameters.add", json!({"name": "W", "expression": "10 mm"}));
+ run(&mut s, "solid.box", json!({"length": "W", "width": 10, "height": 10, "body_name": "A"}));
+ run(&mut s, "solid.hole", json!({"position": [5, 5, 10], "diameter": 4, "name": "Hole"}));
+ let hole = s.doc.features.last().map_or(0, |f| f.id);
+ run(&mut s, "config.configure", json!({"params": ["Enable"], "features": ["Hole"]}));
+ let rule = |id: &str, when: &str, off: bool| {
+ json!({"rule": {"id": id, "name": id, "enabled": true,
+ "condition": {"type": "parameter", "parameter": "Enable", "operator": "eq", "expression": when},
+ "effect": {"type": "drive_suppression", "feature": hole, "value": off}}})
+ };
+ run(&mut s, "config.rule", rule("off", "0", true));
+ run(&mut s, "config.rule", rule("on", "1", false));
+ let full = 1000.0;
+ let drilled = full - std::f64::consts::PI * 4.0 * 10.0;
+ assert!((volume(&mut s) - drilled).abs() < 0.5, "{}", volume(&mut s));
+ let r = run(&mut s, "parameters.change", json!({"name": "Enable", "expression": "0"}));
+ assert_eq!(r["switched"], json!([{"feature": hole, "name": "Hole", "suppressed": true}]), "{r}");
+ assert!((volume(&mut s) - full).abs() < 1e-6, "the hole is off: {}", volume(&mut s));
+ // Back on, through the `changes` form; one undo takes the edit and its switch back.
+ let r = run(&mut s, "parameters.change", json!({"changes": {"Enable": "1"}}));
+ assert_eq!(r["switched"][0]["suppressed"], json!(false), "{r}");
+ assert!((volume(&mut s) - drilled).abs() < 0.5);
+ run(&mut s, "edit.undo", json!({}));
+ assert!(s.doc.features.iter().any(|f| f.id == hole && f.suppressed), "undo restores the switch with the value");
+ run(&mut s, "edit.redo", json!({}));
+ // The hole switched off by hand stays off through an edit its rules do not read.
+ run(&mut s, "timeline.suppress", json!({"feature": hole, "suppressed": true}));
+ let r = run(&mut s, "parameters.change", json!({"name": "W", "expression": "12 mm"}));
+ assert!(r.get("switched").is_none() && s.doc.features.iter().any(|f| f.id == hole && f.suppressed), "{r}");
+ }
+
#[test]
fn configuration_activation_tolerates_identical_existing_errors_but_rejects_reenabled_failure() {
let mut s = Session::default();
diff --git a/crates/engine/src/cmd/parameters.rs b/crates/engine/src/cmd/parameters.rs
index e5c3780802..26a6359ebb 100644
--- a/crates/engine/src/cmd/parameters.rs
+++ b/crates/engine/src/cmd/parameters.rs
@@ -14,7 +14,9 @@ pub static COMMANDS: &[CommandSpec] = &[
"name, expression (number or text), unit?: mm|cm|m|in|ft|deg|rad|\"\" (new parameters default to their value's unit), comment?, \
favorite?: bool, new_name?: rename (references follow); or delete: name; or changes: {name: expression, …} (existing \
parameters, checked together and rebuilt once, all or nothing) → changed?: {name: value} (with changes), recomputed: features rebuilt, \
- restored: features whose earlier result for the same inputs was reused (e.g. a value set back)",
+ restored: features whose earlier result for the same inputs was reused (e.g. a value set back), switched?: [{feature, name, suppressed}] \
+ (the configuration rules that switch a feature's suppression and read a parameter whose value changed run in their order, as on \
+ activation; driven parameters and restrictions wait for a configuration edit or activation)",
),
CommandSpec::new("parameters.list", "List Parameters", list).icon("list").noundo().doc_only().params(
"favorites?: bool (only favourites), filter?: all|user|sketch|feature|favorites → parameters (name, expression, unit, value in its unit, \
@@ -107,6 +109,7 @@ fn change_param(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "`expression` must be a number or text"));
};
let (unit, comment) = (str_(p, "unit"), str_(p, "comment"));
+ let before = s.doc.param_values().0;
match &e {
Some(e) => s.doc_mut().change_param(&name, e, unit, comment)?,
None => {
@@ -121,8 +124,12 @@ fn change_param(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(f) = bool_(p, "favorite") {
s.doc_mut().set_favorite(&name, f)?;
}
+ let switched = switch_by_rules(s, &before);
s.settle_value_edit(&solved)?;
let (vals, _) = s.doc.param_values();
+ if !switched.is_empty() {
+ out["switched"] = json!(switched);
+ }
out["name"] = json!(name);
out["expression"] = json!(e);
out["value"] = json!(vals.get(&name).map(|v| v.v));
@@ -146,11 +153,34 @@ fn change_many(s: &mut Session, changes: &Value, solved: &crate::SketchValues) -
let e = expr_arg(&json!({"e": e}), "e").ok_or_else(|| bad(cmd, format!("`changes.{name}` must be a number or text")))?;
list.push((name.trim().to_string(), e));
}
+ let before = s.doc.param_values().0;
s.doc_mut().change_params_atomic(&list)?;
+ let switched = switch_by_rules(s, &before);
s.settle_value_edit(solved)?;
let (vals, _) = s.doc.param_values();
let values: serde_json::Map<String, Value> = list.iter().map(|(n, _)| (n.clone(), json!(vals.get(n).map(|v| v.v)))).collect();
- Ok(json!({"changed": values, "recomputed": s.model.last_recomputed, "restored": s.model.last_restored, "errors": failing(s)}))
+ let mut out = json!({"changed": values, "recomputed": s.model.last_recomputed, "restored": s.model.last_restored, "errors": failing(s)});
+ if !switched.is_empty() {
+ out["switched"] = json!(switched);
+ }
+ Ok(out)
+}
+
+/// The configuration rules that switch a feature's suppression and read a parameter this edit
+/// changed (`Document::apply_suppression_rules`), applied before the design is rebuilt, so that
+/// one rebuild has them: `[{feature, name, suppressed}]` for each feature they switched.
+fn switch_by_rules(s: &mut Session, before: &std::collections::BTreeMap<String, expr::Value>) -> Vec<Value> {
+ if s.doc.configs.rules.is_empty() {
+ return Vec::new();
+ }
+ let switched = s.doc_mut().apply_suppression_rules(before);
+ switched
+ .into_iter()
+ .map(|(id, suppressed)| {
+ let name = s.doc.features.iter().find(|f| f.id == id).map(|f| f.name.clone());
+ json!({"feature": id, "name": name, "suppressed": suppressed})
+ })
+ .collect()
}
fn list(s: &mut Session, p: &Value) -> Result<Value> {
diff --git a/docs/configurations.md b/docs/configurations.md
index 7f5aea8679..e79a25d204 100644
--- a/docs/configurations.md
+++ b/docs/configurations.md
@@ -119,8 +119,12 @@ multiplier. Bare saved feature length cells and rule thresholds gain the previou
unit; explicit units and nonliteral source expressions retain their text. A matching active
row rederives its driven values when units change. User parameters retain their own units.
-Rules recompute on configured edits, **Apply**, and **Preview Row**. Ordinary parameter
-edits can leave the configuration unmatched and do not continuously enforce restrictions.
+Rules recompute on configured edits, **Apply**, and **Preview Row**. An ordinary parameter edit
+runs only the rules that switch a feature's suppression and whose condition reads a parameter whose
+value changed (or a feature such a rule just switched), in their order, so a switch parameter alone
+turns its features on and off; `parameters.change` lists them as `switched`. It does not drive
+parameters or enforce restrictions: those, and a matching configuration, wait for an edit of the
+configuration or an activation.
Cross-unit drives store effective numeric lengths; their saved source expressions reevaluate
on the next Apply or Preview rather than following later ordinary parameter edits live.
Saved source cells are preserved: disabling a drive restores the row's original choice.