diff --git a/assets/locales/pending/sketch-spline-reverse.json b/assets/locales/pending/sketch-spline-reverse.json new file mode 100644 index 000000000..237def3d7 --- /dev/null +++ b/assets/locales/pending/sketch-spline-reverse.json @@ -0,0 +1,83 @@ +{ + "en": { + "cmd.sketch_spline_reverse": "Reverse Spline Direction" + }, + "ar": { + "cmd.sketch_spline_reverse": "عكس اتجاه المنحنى الشريحي" + }, + "cs": { + "cmd.sketch_spline_reverse": "Obrátit směr splajnu" + }, + "da": { + "cmd.sketch_spline_reverse": "Vend splinens retning" + }, + "de": { + "cmd.sketch_spline_reverse": "Splinerichtung umkehren" + }, + "es": { + "cmd.sketch_spline_reverse": "Invertir dirección del spline" + }, + "fr": { + "cmd.sketch_spline_reverse": "Inverser le sens de la spline" + }, + "gl": { + "cmd.sketch_spline_reverse": "Inverter a dirección do spline" + }, + "he": { + "cmd.sketch_spline_reverse": "היפוך כיוון הספליין" + }, + "hu": { + "cmd.sketch_spline_reverse": "Spline irányának megfordítása" + }, + "id": { + "cmd.sketch_spline_reverse": "Balik Arah Spline" + }, + "it": { + "cmd.sketch_spline_reverse": "Inverti direzione della spline" + }, + "ja": { + "cmd.sketch_spline_reverse": "スプラインの方向を反転" + }, + "ko": { + "cmd.sketch_spline_reverse": "스플라인 방향 반전" + }, + "ms": { + "cmd.sketch_spline_reverse": "Songsangkan Arah Splin" + }, + "nb": { + "cmd.sketch_spline_reverse": "Reverser splineretning" + }, + "nl": { + "cmd.sketch_spline_reverse": "Splinerichting omkeren" + }, + "pl": { + "cmd.sketch_spline_reverse": "Odwróć kierunek splajnu" + }, + "pt-BR": { + "cmd.sketch_spline_reverse": "Inverter direção do spline" + }, + "ro": { + "cmd.sketch_spline_reverse": "Inversează direcția spline-ului" + }, + "ru": { + "cmd.sketch_spline_reverse": "Обратить направление сплайна" + }, + "sv": { + "cmd.sketch_spline_reverse": "Vänd splinens riktning" + }, + "tr": { + "cmd.sketch_spline_reverse": "Spline yönünü ters çevir" + }, + "uk": { + "cmd.sketch_spline_reverse": "Обернути напрямок сплайна" + }, + "vi": { + "cmd.sketch_spline_reverse": "Đảo ngược hướng đường cong Spline" + }, + "zh-TW": { + "cmd.sketch_spline_reverse": "反向雲形線方向" + }, + "zh": { + "cmd.sketch_spline_reverse": "反向样条曲线方向" + } +} diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs index ba0dd8835..1af364279 100644 --- a/crates/engine/src/cmd/sketch_create.rs +++ b/crates/engine/src/cmd/sketch_create.rs @@ -15,7 +15,9 @@ macro_rules! text_style_doc { use super::sketch::{add_c, circumcircle, edit, ids_of, mark_construction, req_parg, result, slot}; use super::{CommandSpec, in_sketch}; use crate::params::{bad, num, req_vec2, str_, string_list}; -use crate::{Result, Session}; +use crate::schema::sketch_create::{SplineReverseParams, SplineReverseResult}; +use crate::schema::{TypedContract, output_schema_for}; +use crate::{EngineError, Result, Session}; #[cfg(test)] #[path = "sketch_text_move_tests.rs"] @@ -25,6 +27,8 @@ mod text_move_tests; #[path = "sketch_text_expr_tests.rs"] mod text_expr_tests; +const SPLINE_REVERSE_CONTRACT: TypedContract = TypedContract::new(); + pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("sketch.line.midpoint", "Midpoint Line", midpoint_line) .at("SKETCH", "CREATE") @@ -83,6 +87,12 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("spline") .enabled(in_sketch) .params("curve: fit point spline id, at: [x,y]: a fit point is inserted where the curve passes nearest to it, between its neighbours (the curve still runs through it and all its old points; constraints on them stay); end?: start|end: `at` becomes the spline's new first or last point instead, and the curve runs on to it (refused when that end is joined to other geometry). Control point splines take no new points yet. Returns point: the new point's id"), + CommandSpec::new("sketch.spline.reverse", "Reverse Spline Direction", crate::checked!("sketch.spline.reverse", spline_reverse)) + .icon("spline") + .enabled(in_sketch) + .contract(&SPLINE_REVERSE_CONTRACT) + .output(output_schema_for::) + .params("curve: spline id (fit point, control point or closed): its last point becomes its first and the curve runs the other way along the same path; its points and the constraints on them stay. Refused for a projected spline and for one an offset uses or makes. Returns curve"), CommandSpec::new("sketch.conic", "Conic Curve", conic) .at("SKETCH", "CREATE") .icon("conic") @@ -704,6 +714,17 @@ fn spline_insert_point(s: &mut Session, p: &Value) -> Result { Ok(json!({"point": point, "curve": p.get("curve"), "sketch": info})) } +fn spline_reverse(s: &mut Session, p: &Value) -> Result { + let cmd = "sketch.spline.reverse"; + let id = str_(p, "curve").ok_or_else(|| bad(cmd, "`curve` must be a spline id"))?.to_string(); + let ((), info) = edit(s, p, cmd, false, |sk, _| { + let c = sk.curve_index(&id).ok_or_else(|| bad(cmd, format!("unknown curve `{id}`")))?; + sk.reverse_spline(c).map_err(|e| bad(cmd, e.to_string())) + })?; + let reply = SplineReverseResult { curve: id, sketch: info, param_warnings: Vec::new() }; + serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) +} + fn conic(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.conic"; let rho = num(p, "rho").unwrap_or(0.5); diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs index 534ccfba0..eb0decb57 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -1142,6 +1142,67 @@ fn a_point_added_to_a_spline_keeps_its_constraints_and_undoes() { assert_eq!(sketch(&s), unchanged, "refusals change nothing"); } +/// Reverse Spline Direction (#8224): a fit, a control point and a closed spline each run the +/// other way along the same path, their ends swapped. Their points, the constraints on them and +/// a line joined to an end stay, and undo restores the spline. A line and the source and output +/// of an offset are refused. +#[test] +fn a_reversed_spline_runs_the_other_way_along_the_same_path() { + use solidcraft_geom::Seg2; + let mut s = new_sketch(); + let fit = + ids(&run(&mut s, "sketch.spline.fit_point", json!({"points": [[0, 0], [10, 8], [25, 2], [30, 6]], "connect": false}))["curves"])[0].clone(); + run(&mut s, "sketch.line", json!({"points": [format!("{fit}.end"), [40, 6]], "connect": false})); + let cv = ids(&run(&mut s, "sketch.spline.control_point", json!({"points": [[0, 20], [10, 30], [25, 18], [30, 26]], "connect": false}))["curves"]) + [0] + .clone(); + let closed = ids(&run( + &mut s, + "sketch.spline.fit_point", + json!({"points": [[0, 40], [10, 48], [20, 40], [10, 34]], "periodic": true, "connect": false}), + )["curves"])[0] + .clone(); + let off = |segs: &[Seg2], q: Vec2| segs.iter().map(|seg| seg.point_at(seg.closest_param(q)).dist(q)).fold(f64::INFINITY, f64::min); + let unit = |v: Vec2| v.normalized().unwrap_or_default(); + for id in [&fit, &cv, &closed] { + let before = sketch(&s); + let ci = before.curve_index(id).unwrap(); + let path = before.exact_segs(ci).unwrap(); + let r = run(&mut s, "sketch.spline.reverse", json!({"curve": id})); + assert_eq!(r["curve"], json!(id), "{r}"); + let after = sketch(&s); + let mut reversed = before.curves[ci].kind.point_ids(); + reversed.reverse(); + assert_eq!(after.curves[ci].kind.point_ids(), reversed, "{id}"); + assert_eq!((&after.points, &after.constraints), (&before.points, &before.constraints), "{id}: points and constraints stay"); + let segs = after.exact_segs(ci).unwrap(); + for (a, b) in [(&path, &segs), (&segs, &path)] { + for seg in a { + for k in 0..=8 { + let q = seg.point_at(k as f64 / 8.0); + assert!(off(b, q) < 1e-7, "{id}: {q:?} is off the other path by {}", off(b, q)); + } + } + } + // It starts where it ended, heading back the way it came. + let (first, last) = (segs.first().unwrap(), path.last().unwrap()); + assert!(first.point_at(0.0).dist(last.point_at(1.0)) < 1e-9, "{id}"); + assert!(unit(first.derivative(0.0)).dist(unit(last.derivative(1.0)) * -1.0) < 1e-7, "{id}"); + } + let before = sketch(&s); + run(&mut s, "sketch.spline.reverse", json!({"curve": fit})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(sketch(&s), before, "undo restores the spline"); + + let line = before.curves.iter().find(|c| matches!(c.kind, CurveKind::Line { .. })).unwrap().id.clone(); + let made = ids(&run(&mut s, "sketch.offset", json!({"curves": [cv], "distance": 2, "side": [10, 40]}))["curves"]); + let unchanged = sketch(&s); + for id in [&line, &cv, &made[0]] { + assert!(s.execute("sketch.spline.reverse", &json!({"curve": id})).is_err(), "{id} is refused"); + } + assert_eq!(sketch(&s), unchanged, "refusals change nothing"); +} + #[test] fn text_makes_profiles_that_extrude_and_edit() { let mut s = new_sketch(); diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index eda6b7253..36c94c184 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -59,6 +59,7 @@ pub mod edit; pub mod features; pub mod inspect; pub mod sketch_constraints; +pub mod sketch_create; pub mod view_navigation; pub use check::{Contract, Issue, ParamCheck, TypedContract, input_schema_for, output_schema_for, run_checked, run_checked_as}; diff --git a/crates/engine/src/schema/sketch_create.rs b/crates/engine/src/schema/sketch_create.rs new file mode 100644 index 000000000..4b079e9a6 --- /dev/null +++ b/crates/engine/src/schema/sketch_create.rs @@ -0,0 +1,47 @@ +//! Contracts and result types for the commands in `cmd/sketch_create.rs`. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use super::types::{SketchRef, present}; + +/// Reverse a spline's direction: its last point becomes its first, and the curve runs the other +/// way along the same path. Its points, and the constraints on them and on the curve, stay. Takes +/// fit point, control point and closed splines; refused for a projected spline and for one an +/// offset uses or makes. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct SplineReverseParams { + /// The spline's curve id. + #[serde(deserialize_with = "spline_id")] + pub curve: String, + /// The sketch (default: the one being edited). + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "SketchRef")] + pub sketch: Option, +} + +/// A curve id, with the handler's message for anything else. +fn spline_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + match Value::deserialize(d)? { + Value::String(s) => Ok(s), + _ => Err(serde::de::Error::custom("must be a spline id")), + } +} + +/// What `sketch.spline.reverse` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct SplineReverseResult { + /// The spline's curve id (unchanged). + pub curve: String, + /// The sketch's solve: `{solved, dof}`. + pub sketch: Value, + /// 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 = "sketch_create_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/sketch_create_tests.rs b/crates/engine/src/schema/sketch_create_tests.rs new file mode 100644 index 000000000..ce79b6eab --- /dev/null +++ b/crates/engine/src/schema/sketch_create_tests.rs @@ -0,0 +1,38 @@ +use serde_json::json; + +use super::{SplineReverseParams, SplineReverseResult}; +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::(), &["curve", "sketch"]); +} + +#[test] +fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[ + ("sketch.spline.reverse", json!({"curve": 5})), + ("sketch.spline.reverse", json!({"curve": null})), + ("sketch.spline.reverse", json!({"curve": "nope"})), + ("sketch.spline.reverse", json!({"curve": "l1"})), + ]); +} + +#[test] +fn spline_reverse_reply_matches_its_schema() { + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let run = |s: &mut Session, id: &str, p: serde_json::Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + let c = run(&mut s, "sketch.spline.fit_point", json!({"points": [[0, 0], [10, 5], [20, 0]]})); + let spline = c["curves"][0].as_str().unwrap_or_else(|| panic!("{c}")).to_string(); + let schema = output_schema_for::(); + let schema = schema.as_value(); + let r = run(&mut s, "sketch.spline.reverse", json!({"curve": spline})); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + assert!(r.get("param_warnings").is_none(), "{r}"); + let r = run(&mut s, "sketch.spline.reverse", json!({"curve": spline, "unknown": 1})); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{r}"); +} diff --git a/crates/sketch/src/spline_points.rs b/crates/sketch/src/spline_points.rs index 6e3206d91..a2ab1308e 100644 --- a/crates/sketch/src/spline_points.rs +++ b/crates/sketch/src/spline_points.rs @@ -1,5 +1,6 @@ //! New points on an existing fit spline (#6533): a fit point inserted where the curve already -//! runs, or a new first or last point the spline runs on to. +//! runs, or a new first or last point the spline runs on to. Also a spline's direction reversed +//! (#8224). //! //! The spline keeps its curve index and every point it had (the new point is appended to //! `Sketch::points`), so constraints on its points and on the curve stay as they were. @@ -86,6 +87,32 @@ impl Sketch { Ok(p) } + /// Reverse spline `ci`'s direction: its last point becomes its first and the curve runs the + /// other way along the same path. Its points are reversed in place, so every point, and every + /// constraint on them and on the curve, stays. The shape doesn't change: a fit spline's chord + /// lengths and natural ends, a control point spline's uniform clamped knots and a closed + /// spline's cyclic fit (whose closing point repeats its first) read the same both ways. + pub fn reverse_spline(&mut self, ci: usize) -> Result<()> { + let curve = self.curves.get(ci).ok_or_else(|| SketchError::Unknown(format!("curve {ci}")))?; + if !matches!(curve.kind, CurveKind::Spline { .. }) { + return Err(SketchError::WrongKind(curve.id.clone(), "only a spline can be reversed".into())); + } + if curve.link.is_some() { + return Err(SketchError::Invalid("a projected spline follows its source; it can't be reversed on its own".into())); + } + let id = curve.id.as_str(); + // An offset's side is taken along its sources' directions. + let offset = self.freeform_offsets.iter().any(|o| o.source == id || o.output == id) + || self.offsets.iter().any(|o| o.sources.iter().any(|(source, _)| source == id) || o.owns_output(id)); + if offset { + return Err(SketchError::Invalid("the spline is part of an offset; break the offset association first".into())); + } + if let Some(CurveKind::Spline { pts, .. }) = self.curves.get_mut(ci).map(|c| &mut c.kind) { + pts.reverse(); + } + Ok(()) + } + /// The points of spline `ci`, when it may take another one. fn editable_spline(&self, ci: usize) -> Result> { let curve = self.curves.get(ci).ok_or_else(|| SketchError::Unknown(format!("curve {ci}")))?; diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 600057f73..08d8760f0 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -1117,6 +1117,16 @@ fn sketch_entity_items(app: &SolveApp) -> Vec { { v.push(cmd(app, "sketch.spline.insert_point", "Add Spline Point").with(json!({"curve": curve, "at": [at.x, at.y]}))); } + // #8224: any spline of the sketch's own runs the other way. + if let [curve] = curves.as_slice() + && ss + .sketch + .curve_index(curve) + .and_then(|i| ss.sketch.curves.get(i)) + .is_some_and(|c| matches!(c.kind, CurveKind::Spline { .. }) && c.link.is_none()) + { + v.push(cmd(app, "sketch.spline.reverse", "Reverse Spline Direction").with(json!({ "curve": curve }))); + } v.push(act("ui.fix", "Fix/Unfix", "c_fix").with(json!({ "entities": ents }))); // The clipboard beside Delete, as in every menu. v.push(act("ui.cut", "Cut", "cut").key("Ctrl+X")); @@ -2501,7 +2511,8 @@ mod tests { } /// #6533: a right-click on a fit point spline offers Add Spline Point at the clicked spot, and - /// the item puts a fit point there. A control point spline is not offered it. + /// the item puts a fit point there. A control point spline is not offered it. Every spline is + /// offered Reverse Spline Direction (#8224), which runs it the other way. #[test] fn spline_context_menu_adds_a_fit_point_where_it_was_clicked() { let mut h = crate::scenario::Harness::new(); @@ -2534,6 +2545,18 @@ mod tests { h.step(&json!({"click":{"world":[c.x,c.y,0]},"button":"right"})).unwrap(); assert_eq!(h.app.session.selection, vec![Sel::SketchCurve { id: control.clone(), sketch: None }]); assert!(items(&h.app, &Target::Viewport).iter().all(|item| item.id != "sketch.spline.insert_point")); + let menu = items(&h.app, &Target::Viewport); + let item = menu.iter().find(|item| item.id == "sketch.spline.reverse").expect("a control point spline offers Reverse Spline Direction"); + assert_eq!((item.label.as_str(), item.params.clone()), ("Reverse Spline Direction", Some(json!({"curve": control})))); + let points = |h: &crate::scenario::Harness, id: &str| { + let state = h.app.session.world_state(); + let sk = &state.sketch(sid).unwrap().sketch; + sk.curves[sk.curve_index(id).unwrap()].kind.point_ids() + }; + let mut reversed = points(&h, &control); + reversed.reverse(); + h.step(&json!({"click":{"handle":"menu:sketch.spline.reverse"}})).unwrap(); + assert_eq!(points(&h, &control), reversed); close(&mut h.app); let at = spot(&h, &fit, 1);