* feat(engine,ui): allow restricting point-to-point align to chosen axes (#9946) * style: apply cargo fmt across crates * fix(clippy): use filter then map instead of bool::then in filter_map
This commit is contained in:
@@ -1083,6 +1083,11 @@ pub enum FeatureKind {
|
||||
/// bodies follow. Replaces `to`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
to_plane: Option<PlaneRef>,
|
||||
/// Point-to-point alignment: the directions the offset moves along (the chosen world
|
||||
/// X/Y/Z axes in the frame of the bodies being moved). `None`: all three axes, the
|
||||
/// offset in full.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
axes: Option<Vec<Dir>>,
|
||||
},
|
||||
/// A helical coil: a circular or square section swept `turns` times about `axis`, rising
|
||||
/// `pitch` per turn, on a helix of `diameter` (the section's centre, or its inside or outside).
|
||||
|
||||
@@ -97,7 +97,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
FeatureKind::Align { bodies, from, to, from_normal, to_normal, flip, from_plane, to_plane } => {
|
||||
FeatureKind::Align { bodies, from, to, from_normal, to_normal, flip, from_plane, to_plane, axes } => {
|
||||
// A plane on either side is worked out now, so the bodies follow it when it moves.
|
||||
let (mut from, mut from_normal) = (from.0, from_normal.and_then(|n| n.normalized()));
|
||||
if let Some(p) = from_plane {
|
||||
@@ -126,6 +126,28 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature,
|
||||
(Some(_), Some(n)) => n * (to - from).dot(n),
|
||||
_ => to - from,
|
||||
};
|
||||
// Point-to-point alignment can keep only the chosen world X/Y/Z directions,
|
||||
// stored in the bodies' frame. A missing list means all three (the full offset).
|
||||
let d = match axes {
|
||||
None => d,
|
||||
Some(dirs) if dirs.is_empty() => {
|
||||
return Err(DocError::Invalid("the align axes enable none of X, Y and Z".into()));
|
||||
}
|
||||
Some(dirs) => {
|
||||
let mut kept = Vec3::ZERO;
|
||||
let mut used = false;
|
||||
for a in dirs {
|
||||
if let Some(a) = a.0.normalized() {
|
||||
kept += a * d.dot(a);
|
||||
used = true;
|
||||
}
|
||||
}
|
||||
if !used {
|
||||
return Err(DocError::Invalid("the align axes have no direction".into()));
|
||||
}
|
||||
kept
|
||||
}
|
||||
};
|
||||
m[3][0] += d.x;
|
||||
m[3][1] += d.y;
|
||||
m[3][2] += d.z;
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
//! A point-to-point Align can save `axes`: the directions it moves along, as the chosen world
|
||||
//! X/Y/Z axes in the frame of the bodies being moved (if it is absent, all three axes are used and
|
||||
//! the offset is applied in full). Older designs need no transformation: they align on all three
|
||||
//! axes as before. The last release refuses a design that has this (it refuses the newer format
|
||||
//! number) rather than moving the bodies on all three axes.
|
||||
@@ -43,7 +43,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("solid.align", "Align", align)
|
||||
.at("SOLID", "MODIFY")
|
||||
.icon("align")
|
||||
.params("bodies: [names]; from: [x,y,z] | \"origin\" | {snap: vertex|edge_mid|face_center|circle_center, at: [x,y,z]} | from_face: [x,y,z] | from_plane: XY|XZ|YZ|construction or offset plane name or id|{origin, normal}; to: (the same) | to_face: [x,y,z] | to_plane: (a plane as from_plane; the point or face goes onto it along its normal, and the plane may move later: the bodies follow); faces and planes also turn to meet; flip?: bool"),
|
||||
.params("bodies: [names]; from: [x,y,z] | \"origin\" | {snap: vertex|edge_mid|face_center|circle_center, at: [x,y,z]} | from_face: [x,y,z] | from_plane: XY|XZ|YZ|construction or offset plane name or id|{origin, normal}; to: (the same) | to_face: [x,y,z] | to_plane: (a plane as from_plane; the point or face goes onto it along its normal, and the plane may move later: the bodies follow); faces and planes also turn to meet; flip?: bool; axes?: [x, y, z] (point-to-point only: which world axes the offset moves along; default all three, at least one true)"),
|
||||
CommandSpec::new("solid.remove", "Remove", remove).at("SOLID", "MODIFY").icon("delete").params("bodies: [names] (removed from here on in the timeline)"),
|
||||
];
|
||||
|
||||
@@ -398,6 +398,21 @@ fn replace_face(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add_feature(s, p, FeatureKind::ReplaceFace { faces: faces.into_iter().map(FacePick).collect(), target, body: body.map(BodyName) })
|
||||
}
|
||||
|
||||
/// `axes`: three booleans, one per world axis, for a point-to-point Align.
|
||||
/// `None` when the call does not restrict the move.
|
||||
fn axes_param(p: &Value, cmd: &str) -> Result<Option<[bool; 3]>> {
|
||||
let Some(v) = p.get("axes").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let a = v.as_array().filter(|a| a.len() == 3).ok_or_else(|| bad(cmd, "`axes` must be [x, y, z] booleans"))?;
|
||||
let mut mask = [false; 3];
|
||||
for (slot, v) in mask.iter_mut().zip(a) {
|
||||
*slot = v.as_bool().ok_or_else(|| bad(cmd, "`axes` must be [x, y, z] booleans"))?;
|
||||
}
|
||||
if !mask.iter().any(|on| *on) {
|
||||
return Err(bad(cmd, "`axes` must enable at least one of X, Y and Z"));
|
||||
}
|
||||
Ok((mask != [true; 3]).then_some(mask))
|
||||
}
|
||||
|
||||
fn align(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "solid.align";
|
||||
let bodies = string_list(cmd, p, "bodies")?;
|
||||
@@ -470,6 +485,18 @@ fn align(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(a, b) if from_plane.is_some() || to_plane.is_some() => (a, b),
|
||||
_ => (None, None),
|
||||
};
|
||||
let axes = axes_param(p, cmd)?;
|
||||
if axes.is_some() && (from_plane.is_some() || to_plane.is_some() || from_normal.is_some() || to_normal.is_some()) {
|
||||
return Err(bad(cmd, "`axes` applies to point-to-point alignment: leave out `from_face`, `to_face`, `from_plane` and `to_plane`"));
|
||||
}
|
||||
// The directions are stored in the same frame as `from`/`to` (the first moved body's frame).
|
||||
let axes = axes.map(|mask| {
|
||||
mask.into_iter()
|
||||
.zip([Vec3::X, Vec3::Y, Vec3::Z])
|
||||
.filter(|&(on, _)| on)
|
||||
.map(|(_, world)| Dir(solidcraft_doc::apply_vector(&inverse, world).normalized().unwrap_or(world)))
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
let flip = bool_(p, "flip").unwrap_or(false);
|
||||
add_feature(
|
||||
s,
|
||||
@@ -483,6 +510,7 @@ fn align(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
flip,
|
||||
from_plane,
|
||||
to_plane,
|
||||
axes,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -833,6 +833,50 @@ fn replace_face_align_remove() {
|
||||
assert_eq!(measure(&mut s)["body_count"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn align_can_keep_the_offset_to_chosen_axes() {
|
||||
let aligned = |axes: Option<Value>| {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "A"}));
|
||||
run(&mut s, "solid.box", json!({"corner": [50, 20, 30], "length": 10, "width": 10, "height": 10, "body_name": "B"}));
|
||||
let mut p = json!({"bodies": ["A"], "from": [0, 0, 0], "to": [50, 20, 30]});
|
||||
if let Some(axes) = axes {
|
||||
p["axes"] = axes;
|
||||
}
|
||||
run(&mut s, "solid.align", p);
|
||||
s
|
||||
};
|
||||
let min = |s: &mut Session| {
|
||||
let m = measure(s);
|
||||
let a = m["bodies"].as_array().unwrap().iter().find(|b| b["name"] == "A").unwrap().clone();
|
||||
let g = |i: usize| a["bbox"]["min"][i].as_f64().unwrap_or(f64::NAN);
|
||||
[g(0), g(1), g(2)]
|
||||
};
|
||||
let close = |got: [f64; 3], want: [f64; 3]| got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-6);
|
||||
assert!(close(min(&mut aligned(Some(json!([false, false, true])))), [0.0, 0.0, 30.0]));
|
||||
assert!(close(min(&mut aligned(Some(json!([true, false, false])))), [50.0, 0.0, 0.0]));
|
||||
assert!(close(min(&mut aligned(Some(json!([false, true, false])))), [0.0, 20.0, 0.0]));
|
||||
assert!(close(min(&mut aligned(Some(json!([true, true, true])))), [50.0, 20.0, 30.0]));
|
||||
assert!(close(min(&mut aligned(None)), [50.0, 20.0, 30.0]));
|
||||
|
||||
// Refusal cases
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "A"}));
|
||||
for axes in [json!([false, false, false]), json!([true, false]), json!([true, false, "yes"])] {
|
||||
assert!(s.execute("solid.align", &json!({"bodies": ["A"], "from": [0, 0, 0], "to": [1, 2, 3], "axes": axes})).is_err(), "{axes}");
|
||||
}
|
||||
// Face/plane alignment cannot take an axis mask.
|
||||
assert!(
|
||||
s.execute("solid.align", &json!({"bodies": ["A"], "from_face": [5, 5, 10], "to_face": [5, 5, 20], "axes": [true, false, false]})).is_err()
|
||||
);
|
||||
|
||||
// Normalisation: all axes true normalises to None in the saved feature
|
||||
let made = run(&mut s, "solid.align", json!({"bodies": ["A"], "from": [0, 0, 0], "to": [1, 2, 3], "axes": [true, true, true]}));
|
||||
let id = made["feature"].as_u64().expect("the feature id");
|
||||
let f = s.doc.feature(id).expect("the saved feature");
|
||||
assert!(matches!(&f.kind, solidcraft_doc::FeatureKind::Align { axes: None, .. }));
|
||||
}
|
||||
|
||||
/// The z range and the x minimum of body `name`.
|
||||
fn z_x(s: &mut Session, name: &str) -> (f64, f64, f64) {
|
||||
let m = measure(s);
|
||||
@@ -2404,3 +2448,17 @@ fn align_takes_both_ends_where_they_are_shown_across_placed_components() {
|
||||
assert!(near(a.min.z, 8.0) && near(a.max.z, 16.0), "on B's top, not across it: {a:?}");
|
||||
assert!(near(0.5 * (a.min.x + a.max.x), 60.0) && near(0.5 * (a.min.y + a.max.y), 15.0), "centred on the picked point: {a:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn align_axes_are_world_axes_on_a_placed_component() {
|
||||
let mut s = Session::default();
|
||||
placed_plate(&mut s, "Plate", 0.0, 90.0);
|
||||
let before = world_bounds(&s, "Plate");
|
||||
run(&mut s, "solid.align", json!({"bodies": ["Plate"], "from": [0, 0, 0], "to": [50, 20, 30], "axes": [false, true, false]}));
|
||||
let after = world_bounds(&s, "Plate");
|
||||
// World Y is masked in; X and Z stay where they were. A local-boolean mask would move
|
||||
// along the component's local Y (world Z) instead.
|
||||
assert!(near(after.min.x, before.min.x) && near(after.max.x, before.max.x), "x: {after:?}");
|
||||
assert!(near(after.min.y, before.min.y + 20.0) && near(after.max.y, before.max.y + 20.0), "y: {after:?}");
|
||||
assert!(near(after.min.z, before.min.z) && near(after.max.z, before.max.z), "z: {after:?}");
|
||||
}
|
||||
|
||||
@@ -680,7 +680,7 @@ fn browser_occurrence_clicks_fill_align_components_input() {
|
||||
h.app.start("solid.align");
|
||||
{
|
||||
let d = h.app.dialog.as_mut().unwrap();
|
||||
d.kind = crate::dialogs::Kind::Align { flip: false, components: true };
|
||||
d.kind = crate::dialogs::Kind::Align { flip: false, components: true, axes: [true; 3] };
|
||||
d.inputs[0].label = "Components";
|
||||
d.active = 0;
|
||||
}
|
||||
|
||||
@@ -274,6 +274,8 @@ crate::dialog_descriptor::dialog_descriptors! {
|
||||
Align {
|
||||
flip: bool,
|
||||
components: bool,
|
||||
/// Point-to-point: which of the world X, Y and Z axes take the offset.
|
||||
axes: [bool; 3],
|
||||
},
|
||||
/// Remove bodies from here on in the timeline.
|
||||
Remove,
|
||||
@@ -878,7 +880,7 @@ impl Dialog {
|
||||
"solid.align" => {
|
||||
let components = s.selection.iter().any(|x| matches!(x, Sel::Occurrence { .. }));
|
||||
Dialog::new(
|
||||
Kind::Align { flip: false, components },
|
||||
Kind::Align { flip: false, components, axes: [true; 3] },
|
||||
vec![
|
||||
SelInput::new(if components { "Components" } else { "Bodies" }, BODIES, true),
|
||||
SelInput::new("From", FACES | EDGES | selection::VERTICES | PLANES | selection::ORIGIN, false),
|
||||
@@ -4659,7 +4661,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result<Vec<(String, Value)>, S
|
||||
need(0, "faces")?;
|
||||
("face.delete", json!({"faces": face_points(0)}))
|
||||
}
|
||||
Kind::Align { flip, components } => {
|
||||
Kind::Align { flip, components, axes } => {
|
||||
need(0, if *components { "components" } else { "bodies" })?;
|
||||
need(1, "what to move from")?;
|
||||
need(2, "where to move it to")?;
|
||||
@@ -4670,7 +4672,11 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result<Vec<(String, Value)>, S
|
||||
}
|
||||
json!({"paths": paths, "flip": flip})
|
||||
} else {
|
||||
json!({"bodies": sels(d, 0).body_names(), "flip": flip})
|
||||
let mut p = json!({"bodies": sels(d, 0).body_names(), "flip": flip});
|
||||
if *axes != [true; 3] {
|
||||
p["axes"] = json!(axes);
|
||||
}
|
||||
p
|
||||
};
|
||||
for (i, key) in [(1, "from"), (2, "to")] {
|
||||
let snap = d.extra.get(&format!("{key}_snap")).and_then(Value::as_str).unwrap_or("picked");
|
||||
|
||||
@@ -769,7 +769,7 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo
|
||||
});
|
||||
ui.add(egui::Label::new(crate::i18n::tr("ui.emboss_wrap_note")).wrap());
|
||||
}
|
||||
Kind::Align { flip, components } => {
|
||||
Kind::Align { flip, components, axes: [ax, ay, az] } => {
|
||||
// Where on the picked face or edge to snap: as picked (a face turns to meet
|
||||
// the other, an edge at its middle), its centre, or a round one's centre.
|
||||
for (label, key) in [("From Snap", "from_snap"), ("To Snap", "to_snap")] {
|
||||
@@ -777,7 +777,11 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo
|
||||
extra_choice(ui, &mut d.extra, key, key, &[("As Picked", "picked"), ("Center", "center"), ("Circle Center", "circle")]);
|
||||
});
|
||||
}
|
||||
ui_kit::options(ui, "feature_options", &mut [("Flip", flip)]);
|
||||
if *components {
|
||||
ui_kit::options(ui, "feature_options", &mut [("Flip", flip)]);
|
||||
} else {
|
||||
ui_kit::options(ui, "feature_options", &mut [("Flip", flip), ("X", ax), ("Y", ay), ("Z", az)]);
|
||||
}
|
||||
// A part inside a subassembly placed more than once sits where that shared
|
||||
// definition says: aligning it moves it in every placement.
|
||||
if *components && align_moves_shared(&app.session, d.inputs.first().map_or(&[], |i| i.items.as_slice())) {
|
||||
|
||||
@@ -1911,7 +1911,7 @@ fn align_components_input_picks_occurrence_from_viewport_body_and_skips_root_bod
|
||||
let second = app.run("occurrence.copy", json!({"component": comp, "translate": [30, 0, 0]})).unwrap()["occurrence"].as_u64().unwrap();
|
||||
|
||||
let mut d = start(&mut app, vec![], "solid.align");
|
||||
d.kind = Kind::Align { flip: false, components: true };
|
||||
d.kind = Kind::Align { flip: false, components: true, axes: [true; 3] };
|
||||
d.inputs[0].label = "Components";
|
||||
d.active = 0;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user