From 3fe2b3386ff984fed93f4c37023e765a87de5e82 Mon Sep 17 00:00:00 2001 From: austin62jake Date: Mon, 2 Nov 2026 00:08:11 +0000 Subject: [PATCH] Sketch: Remove Spline Point takes one point out of a spline (#10783) (#10793) * Sketch: Remove Spline Point takes one fit point out of a spline (#10783) Co-Authored-By: Claude Opus 5.5 * Sketch: Remove Spline Point takes one point out of a spline (#10783) sketch.spline.remove_point takes one fit or control point out of a spline. The spline keeps its id and runs through its other points, which stay where they are. The point goes with the constraints on it, unless another curve uses it. A closed spline's closing point, an end joined to other geometry, the last 2 points (3 when closed), and projected, offset or patterned splines are refused with a message. The right-click menu of a spline point, picked alone, offers it beside Reverse Spline Direction. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude --- .../locales/pending/spline-remove-point.json | 31 +++++++ crates/engine/src/cmd/sketch_create.rs | 25 +++++- crates/engine/src/cmd/sketch_modify_tests.rs | 58 +++++++++++++ crates/engine/src/schema/sketch_create.rs | 44 ++++++++++ .../engine/src/schema/sketch_create_tests.rs | 24 +++++- crates/sketch/src/model.rs | 4 +- crates/sketch/src/spline_points.rs | 75 ++++++++++++++++- crates/sketch/src/tests.rs | 82 +++++++++++++++++++ crates/ui-egui/src/context_menu.rs | 54 ++++++++++++ 9 files changed, 391 insertions(+), 6 deletions(-) create mode 100644 assets/locales/pending/spline-remove-point.json diff --git a/assets/locales/pending/spline-remove-point.json b/assets/locales/pending/spline-remove-point.json new file mode 100644 index 000000000..17e7511b4 --- /dev/null +++ b/assets/locales/pending/spline-remove-point.json @@ -0,0 +1,31 @@ +{ + "en": { "cmd.sketch_spline_remove_point": "Remove Spline Point" }, + "ar": { "cmd.sketch_spline_remove_point": "إزالة نقطة من المنحنى الشريحي" }, + "bs": { "cmd.sketch_spline_remove_point": "Ukloni tačku splajna" }, + "cs": { "cmd.sketch_spline_remove_point": "Odebrat bod splajnu" }, + "da": { "cmd.sketch_spline_remove_point": "Fjern splinepunkt" }, + "de": { "cmd.sketch_spline_remove_point": "Splinepunkt entfernen" }, + "es": { "cmd.sketch_spline_remove_point": "Eliminar punto de spline" }, + "fi": { "cmd.sketch_spline_remove_point": "Poista splinipiste" }, + "fr": { "cmd.sketch_spline_remove_point": "Supprimer un point de spline" }, + "gl": { "cmd.sketch_spline_remove_point": "Eliminar punto do spline" }, + "he": { "cmd.sketch_spline_remove_point": "הסרת נקודה מהספליין" }, + "hr": { "cmd.sketch_spline_remove_point": "Ukloni točku splinea" }, + "hu": { "cmd.sketch_spline_remove_point": "Splinepont eltávolítása" }, + "id": { "cmd.sketch_spline_remove_point": "Hapus Titik Spline" }, + "it": { "cmd.sketch_spline_remove_point": "Rimuovi punto dalla spline" }, + "ja": { "cmd.sketch_spline_remove_point": "スプライン点を削除" }, + "ms": { "cmd.sketch_spline_remove_point": "Buang Titik Splin" }, + "nb": { "cmd.sketch_spline_remove_point": "Fjern splinepunkt" }, + "nl": { "cmd.sketch_spline_remove_point": "Splinepunt verwijderen" }, + "pl": { "cmd.sketch_spline_remove_point": "Usuń punkt splajnu" }, + "ro": { "cmd.sketch_spline_remove_point": "Elimină punct din spline" }, + "ru": { "cmd.sketch_spline_remove_point": "Удалить точку сплайна" }, + "sr": { "cmd.sketch_spline_remove_point": "Уклони тачку сплајна" }, + "sv": { "cmd.sketch_spline_remove_point": "Ta bort splinepunkt" }, + "tr": { "cmd.sketch_spline_remove_point": "Spline Noktasını Kaldır" }, + "uk": { "cmd.sketch_spline_remove_point": "Видалити точку сплайна" }, + "vi": { "cmd.sketch_spline_remove_point": "Xóa điểm khỏi đường cong Spline" }, + "zh": { "cmd.sketch_spline_remove_point": "删除样条曲线点" }, + "zh-TW": { "cmd.sketch_spline_remove_point": "刪除雲形線點" } +} diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs index 8afe7d695..de8101fa4 100644 --- a/crates/engine/src/cmd/sketch_create.rs +++ b/crates/engine/src/cmd/sketch_create.rs @@ -16,7 +16,7 @@ use super::sketch::{add_c, circumcircle, edit, ids_of, mark_construction, req_pa use super::sketch_store; use super::{CommandSpec, in_sketch}; use crate::params::{bad, num, req_vec2, str_, string_list}; -use crate::schema::sketch_create::{SplineReverseParams, SplineReverseResult}; +use crate::schema::sketch_create::{SplineRemovePointParams, SplineRemovePointResult, SplineReverseParams, SplineReverseResult}; use crate::schema::{TypedContract, output_schema_for}; use crate::{EngineError, Result, Session}; @@ -29,6 +29,7 @@ mod text_move_tests; mod text_expr_tests; const SPLINE_REVERSE_CONTRACT: TypedContract = TypedContract::new(); +const SPLINE_REMOVE_POINT_CONTRACT: TypedContract = TypedContract::new(); pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("sketch.line.midpoint", "Midpoint Line", midpoint_line) @@ -88,6 +89,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.remove_point", "Remove Spline Point", crate::checked!("sketch.spline.remove_point", spline_remove_point)) + .icon("spline") + .enabled(in_sketch) + .contract(&SPLINE_REMOVE_POINT_CONTRACT) + .output(output_schema_for::) + .params("curve: spline id, point: one of its points (a point id, or the curve's start or end such as s1.end): the spline runs through (or over) its other points only, and the point goes with the constraints on it unless another curve uses it. Fit point, control point and closed splines. Refused for a closed spline's closing point, for an end joined to other geometry or held by a constraint, when fewer than 2 points would be left (3 on a closed spline), and for a projected, offset or patterned spline. Returns curve, point: the point's id, deleted: whether the point went too"), CommandSpec::new("sketch.spline.reverse", "Reverse Spline Direction", crate::checked!("sketch.spline.reverse", spline_reverse)) .icon("spline") .enabled(in_sketch) @@ -711,6 +718,22 @@ fn spline_insert_point(s: &mut Session, p: &Value) -> Result { Ok(json!({"point": point, "curve": p.get("curve"), "sketch": info})) } +/// One point taken out of a spline (#10783). +fn spline_remove_point(s: &mut Session, p: &Value) -> Result { + let cmd = "sketch.spline.remove_point"; + let id = str_(p, "curve").ok_or_else(|| bad(cmd, "`curve` must be a spline id"))?.to_string(); + let point = str_(p, "point").ok_or_else(|| bad(cmd, "`point` must be one of the spline's points"))?.to_string(); + let ((point, deleted), info) = edit(s, p, cmd, false, |sk, _| { + let c = sk.curve_index(&id).ok_or_else(|| bad(cmd, format!("unknown curve `{id}`")))?; + let at = sk.resolve_point(&point).ok_or_else(|| bad(cmd, format!("unknown sketch point `{point}`")))?; + let name = sk.points.get(at).map_or(point.clone(), |q| q.id.clone()); + let deleted = sk.remove_spline_point(c, at).map_err(|e| bad(cmd, e.to_string()))?; + Ok((name, deleted)) + })?; + let reply = SplineRemovePointResult { curve: id, point, deleted, sketch: info, param_warnings: Vec::new() }; + serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) +} + 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(); diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs index 4a5c66894..ea69228da 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -1492,6 +1492,64 @@ fn a_point_added_to_a_spline_keeps_its_constraints_and_undoes() { assert_eq!(sketch(&s), unchanged, "refusals change nothing"); } +/// Remove Spline Point (#10783): one fit point goes, with the dimension on it. The spline runs +/// through its other points, which stay where they were, and the line joined to its end stays. +/// Undo puts the point back. The end the line joins, a line and an unknown point are refused; a +/// control point spline gives up a point too. +#[test] +fn a_point_removed_from_a_spline_goes_with_its_dimension_and_undoes() { + let mut s = new_sketch(); + let sid = + ids(&run(&mut s, "sketch.spline.fit_point", json!({"points": [[0, 0], [10, 8], [20, 0], [30, 6]], "connect": false}))["curves"])[0].clone(); + run(&mut s, "sketch.line", json!({"points": [format!("{sid}.end"), [40, 6]], "connect": false})); + let sk = sketch(&s); + let si = sk.curve_index(&sid).unwrap(); + let names: Vec = sk.curves[si].kind.point_ids().iter().map(|i| sk.points[*i].id.clone()).collect(); + run(&mut s, "sketch.dimension", json!({"entities": [names[1], names[2]], "value": 12.8})); + let before = sketch(&s); + let at = |sk: &solidcraft_sketch::Sketch, id: &str| sk.point(sk.point_index(id).unwrap()).unwrap(); + + let r = run(&mut s, "sketch.spline.remove_point", json!({"curve": sid, "point": names[1]})); + assert_eq!((r["curve"].as_str(), r["point"].as_str(), r["deleted"].as_bool()), (Some(sid.as_str()), Some(names[1].as_str()), Some(true)), "{r}"); + let after = sketch(&s); + assert!(after.point_index(&names[1]).is_none(), "the point went"); + let left: Vec = after.curves[si].kind.point_ids().iter().map(|i| after.points[*i].id.clone()).collect(); + assert_eq!(left, [names[0].clone(), names[2].clone(), names[3].clone()]); + let segs = after.exact_segs(si).unwrap(); + for id in &left { + let q = at(&after, id); + assert!(q.dist(at(&before, id)) < 1e-9, "{id} stays where it was"); + let off = segs.iter().map(|seg| seg.point_at(seg.closest_param(q)).dist(q)).fold(f64::INFINITY, f64::min); + assert!(off < 1e-9, "the curve runs through {id}"); + } + assert!(after.constraints.iter().all(|c| c.kind.value().is_none()), "the dimension on the point went"); + let joined = after.curves.iter().any(|c| matches!(c.kind, CurveKind::Line { a, .. } if after.points[a].id == names[3])); + assert!(joined, "the line still starts at the spline's end"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(sketch(&s), before, "undo puts the point back"); + + let line = before.curves.iter().find(|c| matches!(c.kind, CurveKind::Line { .. })).unwrap().id.clone(); + for (p, why) in [ + (json!({"curve": sid, "point": format!("{sid}.end")}), "joined"), + (json!({"curve": line, "point": names[0]}), "spline"), + (json!({"curve": sid, "point": "nope"}), "unknown sketch point"), + (json!({"curve": sid}), "`point`"), + ] { + let e = s.execute("sketch.spline.remove_point", &p).unwrap_err().to_string(); + assert!(e.contains(why), "{p}: {e}"); + } + assert_eq!(sketch(&s), before, "refusals change nothing"); + + let cv = + ids(&run(&mut s, "sketch.spline.control_point", json!({"points": [[0, 20], [10, 30], [20, 20]], "connect": false}))["curves"])[0].clone(); + let r = run(&mut s, "sketch.spline.remove_point", json!({"curve": cv, "point": format!("{cv}.start")})); + assert_eq!(r["deleted"], json!(true), "{r}"); + let sk = sketch(&s); + let ci = sk.curve_index(&cv).unwrap(); + let left: Vec = sk.curves[ci].kind.point_ids().iter().map(|i| sk.point(*i).unwrap()).collect(); + assert_eq!(left, [Vec2::new(10.0, 30.0), Vec2::new(20.0, 20.0)]); +} + /// 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 diff --git a/crates/engine/src/schema/sketch_create.rs b/crates/engine/src/schema/sketch_create.rs index 558045450..7c6d1971e 100644 --- a/crates/engine/src/schema/sketch_create.rs +++ b/crates/engine/src/schema/sketch_create.rs @@ -80,6 +80,50 @@ pub struct SplineReverseParams { pub sketch: Option, } +/// Take one point out of a spline: it runs through (or over) its other points only, and the point +/// goes with the constraints on it unless another curve uses it. Takes fit point, control point +/// and closed splines; refused for a closed spline's closing point, for an end joined to other +/// geometry or held by a constraint, when fewer than 2 points would be left (3 on a closed +/// spline), and for a projected, offset or patterned spline. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct SplineRemovePointParams { + /// The spline's curve id. + #[serde(deserialize_with = "spline_id")] + pub curve: String, + /// One of the spline's points: a point id, or the curve's `start` or `end` (`s1.end`). + #[serde(deserialize_with = "point_ref")] + pub point: 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, +} + +/// What `sketch.spline.remove_point` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct SplineRemovePointResult { + /// The spline's curve id (unchanged). + pub curve: String, + /// The id the point had. + pub point: String, + /// Whether the point went too; `false` when another curve still uses it. + pub deleted: bool, + /// 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, +} + +/// A point reference, with the handler's message for anything else. +fn point_ref<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + match Value::deserialize(d)? { + Value::String(s) => Ok(s), + _ => Err(serde::de::Error::custom("must be one of the spline's points")), + } +} + /// 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)? { diff --git a/crates/engine/src/schema/sketch_create_tests.rs b/crates/engine/src/schema/sketch_create_tests.rs index 3f841c626..bea64f761 100644 --- a/crates/engine/src/schema/sketch_create_tests.rs +++ b/crates/engine/src/schema/sketch_create_tests.rs @@ -1,6 +1,6 @@ use serde_json::json; -use super::{SplineReverseParams, SplineReverseResult}; +use super::{SplineRemovePointParams, SplineRemovePointResult, 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}; @@ -8,6 +8,7 @@ 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"]); + assert_keys(input_schema_for::(), &["curve", "point", "sketch"]); } #[test] @@ -17,9 +18,30 @@ fn strict_keeps_todays_errors() { ("sketch.spline.reverse", json!({"curve": null})), ("sketch.spline.reverse", json!({"curve": "nope"})), ("sketch.spline.reverse", json!({"curve": "l1"})), + ("sketch.spline.remove_point", json!({"curve": 5, "point": "p1"})), + ("sketch.spline.remove_point", json!({"curve": "nope", "point": "p1"})), + ("sketch.spline.remove_point", json!({"curve": "l1", "point": 3})), + ("sketch.spline.remove_point", json!({"curve": "l1"})), ]); } +#[test] +fn spline_remove_point_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": [[5, 0], [10, 5], [20, 0], [30, 5], [40, 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.remove_point", json!({"curve": spline, "point": format!("{spline}.start")})); + 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.remove_point", json!({"curve": spline, "point": format!("{spline}.end"), "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}"); +} + #[test] fn spline_reverse_reply_matches_its_schema() { let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; diff --git a/crates/sketch/src/model.rs b/crates/sketch/src/model.rs index b696bb955..a482e6e8a 100644 --- a/crates/sketch/src/model.rs +++ b/crates/sketch/src/model.rs @@ -1695,7 +1695,7 @@ impl Sketch { /// Points held together only through points about to go stay together: two rectangles' /// corners made coincident with one arc end are tied to each other when a trim takes that /// end away, instead of coming apart where they still meet. - fn keep_ties_through(&mut self, gone: &[usize]) { + pub(crate) fn keep_ties_through(&mut self, gone: &[usize]) { if gone.is_empty() { return; } @@ -1732,7 +1732,7 @@ impl Sketch { } } - fn point_used_by_curve(&self, p: usize) -> bool { + pub(crate) fn point_used_by_curve(&self, p: usize) -> bool { self.curves.iter().any(|c| c.kind.uses(p)) } diff --git a/crates/sketch/src/spline_points.rs b/crates/sketch/src/spline_points.rs index a2ab1308e..bd8e28e67 100644 --- a/crates/sketch/src/spline_points.rs +++ b/crates/sketch/src/spline_points.rs @@ -1,6 +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. Also a spline's direction reversed -//! (#8224). +//! runs, or a new first or last point the spline runs on to. One point taken out of a spline +//! (#10783). 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. @@ -87,6 +87,77 @@ impl Sketch { Ok(p) } + /// Take point `p` out of spline `ci` (#10783), and return whether the point itself went too. + /// The spline runs through (or over) its other points, and keeps its curve index, so + /// constraints on the curve and on its other points stay. The point goes with the constraints + /// on it, unless another curve uses it (it stays, for that curve) or it is the origin. + /// + /// The spline keeps at least 2 points (a closed one 3 besides its closing point, which stays). + /// An end of an open spline joined to other geometry stays, as for [`Sketch::extend_spline`]: + /// the spline would no longer end where it is joined. + pub fn remove_spline_point(&mut self, ci: usize, p: usize) -> Result { + let curve = self.curves.get(ci).ok_or_else(|| SketchError::Unknown(format!("curve {ci}")))?; + let CurveKind::Spline { pts, periodic, .. } = &curve.kind else { + return Err(SketchError::WrongKind(curve.id.clone(), "only a spline has points to remove".into())); + }; + let (pts, periodic) = (pts.clone(), *periodic); + if curve.link.is_some() { + return Err(SketchError::Invalid("a projected spline follows its source; its points can't be removed".into())); + } + if self.freeform_offsets.iter().any(|o| o.output == curve.id) { + return Err(SketchError::Invalid("an offset spline follows its source; break the offset association first".into())); + } + if self.freeform_offsets.iter().any(|o| o.source == curve.id) { + return Err(SketchError::Invalid( + "not supported yet: removing a point from a spline that has an offset; break the offset association first".into(), + )); + } + if self.patterns.iter().any(|pattern| pattern.contains(&curve.id)) { + return Err(SketchError::Invalid("not supported yet: removing a point from a patterned spline".into())); + } + let at = match pts.iter().enumerate().filter(|(_, q)| **q == p).map(|(i, _)| i).collect::>().as_slice() { + [] => return Err(SketchError::Invalid(format!("that point isn't one of {}'s points", curve.id))), + [at] => *at, + _ => return Err(SketchError::Invalid("that point closes the spline; remove another one".into())), + }; + let last = pts.len().saturating_sub(1); + if periodic && (at == 0 || at == last) { + return Err(SketchError::Invalid("a closed spline's closing point stays; remove another one".into())); + } + if pts.len() < if periodic { 5 } else { 3 } { + return Err(SketchError::Invalid(format!("a spline keeps at least {} points", if periodic { 3 } else { 2 }))); + } + if !periodic && (at == 0 || at == last) { + let joined = self.curves.iter().enumerate().any(|(i, c)| i != ci && c.kind.uses(p)) + || self.constraints.iter().any(|k| { + let (points, curves) = k.kind.indices(); + points.contains(&p) || (curves.contains(&ci) && matches!(k.kind, ConstraintKind::Tangent { .. } | ConstraintKind::Smooth { .. })) + }); + if joined { + return Err(SketchError::Invalid( + "that end of the spline is joined to other geometry or held by a constraint; remove those first".into(), + )); + } + } + let mut left = pts; + left.remove(at); + if periodic { + let pos: Vec = + left.iter().map(|i| self.point(*i).ok_or_else(|| SketchError::Unknown(format!("point {i}")))).collect::>()?; + crate::periodic::validate_periodic_points(&pos)?; + } + if let Some(CurveKind::Spline { pts, .. }) = self.curves.get_mut(ci).map(|c| &mut c.kind) { + *pts = left; + } + // The origin (point 0) is never removed. + if p == 0 || self.point_used_by_curve(p) { + return Ok(false); + } + self.keep_ties_through(&[p]); + self.remove_points(&[p]); + Ok(true) + } + /// 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 diff --git a/crates/sketch/src/tests.rs b/crates/sketch/src/tests.rs index feaa87cad..89bb53cbd 100644 --- a/crates/sketch/src/tests.rs +++ b/crates/sketch/src/tests.rs @@ -1220,6 +1220,88 @@ fn a_spline_extends_to_a_new_end_unless_the_end_is_joined() { assert!(sk.extend_spline(s, v(-10.0, 5.0), true).is_err(), "already a point there"); } +/// Where spline `s`'s points are, in order. +fn spline_places(sk: &Sketch, s: usize) -> Vec { + let CurveKind::Spline { pts, .. } = &sk.curves[s].kind else { panic!("{s} is no spline") }; + pts.iter().map(|i| sk.point(*i).unwrap()).collect() +} + +/// #10783: a spline gives up one of its points. The curve runs through the others, in order, and +/// the point goes with the constraints on it; a point a line also ends at stays, for the line. +#[test] +fn a_point_removed_from_a_spline_goes_and_the_curve_keeps_the_others() { + let mut sk = Sketch::new(); + let (pts, s) = wave_spline(&mut sk, false); + let mut others = spline_places(&sk, s); + let gone = others.remove(2); + // A free point held on the one that goes: the constraint goes, the free point stays. + let free = sk.add_point(gone, None).unwrap(); + sk.add_constraint(ConstraintKind::Coincident { p: pts[2], q: free }, None).unwrap(); + let count = sk.points.len(); + assert_eq!(sk.remove_spline_point(s, pts[2]), Ok(true)); + assert_eq!(spline_places(&sk, s), others); + for q in &others { + assert!(off_curve(&sk, s, *q) < 1e-9, "the curve still runs through {q:?}"); + } + assert!(matches!(sk.curves[s].kind, CurveKind::Spline { control: false, periodic: false, .. })); + assert_eq!(sk.points.len(), count - 1, "the point went"); + assert!(sk.constraints.is_empty(), "the constraint on it went: {:?}", sk.constraints); + // A free end goes too: the spline starts at the next point. + let start = sk.curves[s].kind.ends().unwrap().0; + assert_eq!(sk.remove_spline_point(s, start), Ok(true)); + others.remove(0); + assert_eq!(spline_places(&sk, s), others); + // An inner point a line also ends at stays, for the line. + let CurveKind::Spline { pts: now, .. } = sk.curves[s].kind.clone() else { panic!() }; + let line = sk.add_line(others[1], v(40.0, 30.0), Some(now[1]), None, None).unwrap(); + assert_eq!(sk.remove_spline_point(s, now[1]), Ok(false)); + assert!(sk.curves[line].kind.uses(now[1]) && !sk.curves[s].kind.uses(now[1])); + others.remove(1); + assert_eq!(spline_places(&sk, s), others); + // Two points are as few as a spline keeps. + assert_eq!(others.len(), 2); + let before = sk.clone(); + assert!(sk.remove_spline_point(s, sk.curves[s].kind.ends().unwrap().1).is_err()); + assert_eq!(sk, before, "a refused removal changes nothing"); +} + +/// #10783: what a spline keeps: an end joined to a line or held by a constraint, a closed +/// spline's closing point and its last three points. A control point spline gives up a point as a +/// fit point spline does. +#[test] +fn a_spline_keeps_its_joined_ends_and_closing_point() { + let mut sk = Sketch::new(); + let (pts, s) = wave_spline(&mut sk, false); + let line = sk.add_line(sk.point(pts[4]).unwrap(), v(60.0, 0.0), Some(pts[4]), None, None).unwrap(); + let tied = sk.add_point(sk.point(pts[0]).unwrap(), None).unwrap(); + sk.add_constraint(ConstraintKind::Coincident { p: pts[0], q: tied }, None).unwrap(); + let before = sk.clone(); + assert!(sk.remove_spline_point(s, pts[4]).is_err(), "a line ends there"); + assert!(sk.remove_spline_point(s, pts[0]).is_err(), "a constraint holds the start"); + assert!(sk.remove_spline_point(s, tied).is_err(), "not one of the spline's points"); + assert!(sk.remove_spline_point(line, pts[4]).is_err(), "a line has no spline points"); + assert_eq!(sk, before, "a refused removal changes nothing"); + + let mut sk = Sketch::new(); + let (pts, s) = wave_spline(&mut sk, true); + assert!(sk.remove_spline_point(s, pts[0]).is_err(), "the closing point"); + assert_eq!(sk.remove_spline_point(s, pts[2]), Ok(true)); + assert_eq!(sk.remove_spline_point(s, pts[1]), Ok(true)); + let CurveKind::Spline { pts: now, periodic, .. } = sk.curves[s].kind.clone() else { panic!() }; + assert!(periodic); + assert_eq!(now.len(), 4, "three points and the closing one: {now:?}"); + assert!(sk.remove_spline_point(s, now[1]).is_err(), "a closed spline keeps three points"); + sk.validate_periodic_splines().unwrap(); + + let mut sk = Sketch::new(); + let places = [v(0.0, 0.0), v(10.0, 10.0), v(20.0, -10.0), v(30.0, 0.0)]; + let cv: Vec = places.iter().map(|q| sk.add_point(*q, None).unwrap()).collect(); + let c = sk.add_curve(CurveKind::Spline { pts: cv.clone(), control: true, degree: 3, periodic: false }, None).unwrap(); + assert_eq!(sk.remove_spline_point(c, cv[1]), Ok(true)); + assert!(matches!(sk.curves[c].kind, CurveKind::Spline { control: true, .. })); + assert_eq!(spline_places(&sk, c), vec![places[0], places[2], places[3]]); +} + /// #755: a line drawn through a junction of a loop, but 2e-5 off it, still splits the loop. The /// junction lies on the loop's two curves only, so it cuts neither of them where the line /// crosses, and that crossing, next to the junction, was taken for one already cut there: the diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 71b80c3da..427284ab2 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -1281,6 +1281,19 @@ fn sketch_entity_items(app: &SolveApp) -> Vec { { v.push(cmd(app, "sketch.spline.reverse", "Reverse Spline Direction").with(json!({ "curve": curve }))); } + // #10783: a point of one spline of the sketch's own, alone, comes out of that spline. + if let ([], [point]) = (curves.as_slice(), points.as_slice()) + && let Some(at) = ss.sketch.resolve_point(point) + && let [spline] = ss + .sketch + .curves + .iter() + .filter(|c| c.link.is_none() && matches!(&c.kind, CurveKind::Spline { pts, .. } if pts.contains(&at))) + .collect::>() + .as_slice() + { + v.push(cmd(app, "sketch.spline.remove_point", "Remove Spline Point").with(json!({ "curve": spline.id, "point": point }))); + } 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")); @@ -2943,6 +2956,47 @@ mod tests { assert!(added.dist(at) < 0.5, "the new fit point is where the menu was opened: {added:?}"); } + /// #10783: a right-click on one of a spline's points offers Remove Spline Point, and the item + /// takes that point out: the spline stays, through its other points. A line's end isn't + /// offered it. + #[test] + fn spline_context_menu_removes_the_clicked_point() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + let fit = h.app.run("sketch.spline.fit_point", json!({"points":[[0,0],[10,8],[20,0],[30,6]],"connect":false})).unwrap()["curves"][0] + .as_str() + .unwrap() + .to_owned(); + h.app.run("sketch.line", json!({"points":[[0,-12],[20,-12]],"connect":false})).unwrap(); + let sid = h.app.session.active_sketch.unwrap(); + let places = |h: &crate::scenario::Harness| { + let state = h.app.session.world_state(); + let sk = &state.sketch(sid).unwrap().sketch; + sk.curves[sk.curve_index(&fit).unwrap()].kind.point_ids().iter().map(|i| sk.point(*i).unwrap()).collect::>() + }; + h.call("ui.view", json!({"view":"top"})); + h.app.cam.distance = 80.0; + h.settle(); + + h.step(&json!({"click":{"world":[20,-12,0]},"button":"right"})).unwrap(); + assert!(matches!(h.app.session.selection.as_slice(), [Sel::SketchPoint { .. }]), "{:?}", h.app.session.selection); + assert!(items(&h.app, &Target::Viewport).iter().all(|item| item.id != "sketch.spline.remove_point"), "a line's end"); + close(&mut h.app); + + let mut left = places(&h); + left.remove(1); + h.step(&json!({"click":{"world":[10,8,0]},"button":"right"})).unwrap(); + let [Sel::SketchPoint { id }] = h.app.session.selection.as_slice() else { panic!("{:?}", h.app.session.selection) }; + let id = id.clone(); + let menu = items(&h.app, &Target::Viewport); + let item = menu.iter().find(|item| item.id == "sketch.spline.remove_point").expect("a spline's point offers Remove Spline Point"); + assert_eq!((item.label.as_str(), item.params.clone()), ("Remove Spline Point", Some(json!({"curve": fit, "point": id})))); + assert!(item.enabled); + h.step(&json!({"click":{"handle":"menu:sketch.spline.remove_point"}})).unwrap(); + assert_eq!(places(&h), left, "the spline runs through its other points"); + } + #[test] fn solidworks_face_menu_runs_normal_to_selection_and_rejects_curved_faces() { let mut h = crate::scenario::Harness::new();