Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 47 additions & 23 deletions crates/engine/src/cmd/draw2/arc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,18 +65,22 @@ impl ArcV {
const S: &str = "Specify start point of arc";
const C: &str = "Specify center point of arc";
const E: &str = "Specify end point of arc";
const A: &str = "Specify included angle";
const L: &str = "Specify length of chord";
// The last prompt of every variant whose direction Ctrl switches says so, as
// AutoCAD's does.
const EC: &str = "Specify end point of arc (hold Ctrl to switch direction)";
const CC: &str = "Specify center point of arc (hold Ctrl to switch direction)";
const A: &str = "Specify included angle (hold Ctrl to switch direction)";
const L: &str = "Specify length of chord (hold Ctrl to switch direction)";
match self {
ArcV::ThreeP => &[(S, Ask::Point), ("Specify second point of arc", Ask::Point), (E, Ask::Point)],
ArcV::Sec => &[(S, Ask::Point), (E, Ask::Point), (C, Ask::Point)],
ArcV::Sce => &[(S, Ask::Point), (C, Ask::Point), (E, Ask::Point)],
ArcV::Sec => &[(S, Ask::Point), (E, Ask::Point), (CC, Ask::Point)],
ArcV::Sce => &[(S, Ask::Point), (C, Ask::Point), (EC, Ask::Point)],
ArcV::Sca => &[(S, Ask::Point), (C, Ask::Point), (A, Ask::Sweep(1, 0))],
ArcV::Scl => &[(S, Ask::Point), (C, Ask::Point), (L, Ask::Dist(0))],
ArcV::Sea => &[(S, Ask::Point), (E, Ask::Point), (A, Ask::Angle(0))],
ArcV::Sed => &[(S, Ask::Point), (E, Ask::Point), ("Specify tangent direction for the start point of arc", Ask::Angle(0))],
ArcV::Ser => &[(S, Ask::Point), (E, Ask::Point), ("Specify radius of arc", Ask::Dist(1))],
ArcV::Cse => &[(C, Ask::Point), (S, Ask::Point), ("Specify end point of arc (hold Ctrl to switch direction)", Ask::Point)],
ArcV::Ser => &[(S, Ask::Point), (E, Ask::Point), ("Specify radius of arc (hold Ctrl to switch direction)", Ask::Dist(1))],
ArcV::Cse => &[(C, Ask::Point), (S, Ask::Point), (EC, Ask::Point)],
ArcV::Csa => &[(C, Ask::Point), (S, Ask::Point), (A, Ask::Sweep(0, 1))],
ArcV::Csl => &[(C, Ask::Point), (S, Ask::Point), (L, Ask::Dist(1))],
ArcV::CircleCd => &[("Specify center point for circle", Ask::Point), ("Specify diameter of circle", Ask::Dist(0))],
Expand All @@ -90,28 +94,36 @@ impl ArcV {
],
}
}
/// Builds the entity from the values. `ctrl` (Ctrl, or Cmd on macOS, held) switches the
/// arc to the other direction, clockwise from the start point instead of counter-clockwise:
///
/// * start/center/end picked (`Sce`, `Sec`, `Cse`): the same two endpoints on the same
/// circle, walking the other way around, so the start/end angles swap;
/// * start, end and angle or radius (`Sea`, `Ser`): the same sweep or radius bulging to the
/// other side of the chord;
/// * start, center and chord length (`Scl`, `Csl`): the same chord, clockwise from the start;
/// * included angle (`Sca`, `Csa`): already signed when the value was taken (see
/// `SeqM::value_from_point`), because a picked angle must keep ending at the cursor.
fn build(self, v: &[Val], ctrl: bool) -> Option<EntityKind> {
let p = |i: usize| v.get(i).and_then(|x| x.p());
let n = |i: usize| v.get(i).and_then(|x| x.n());
let swap = |a: Arc| if ctrl { Arc::new(a.center, a.radius, a.end, a.start) } else { a };
let a = match self {
ArcV::ThreeP => Arc::from_3_points(p(0)?, p(1)?, p(2)?),
ArcV::Sec => Some(Arc::from_start_center_end(p(0)?, p(2)?, p(1)?)),
ArcV::Sce => Some(Arc::from_start_center_end(p(0)?, p(1)?, p(2)?)),
ArcV::Sec => Some(swap(Arc::from_start_center_end(p(0)?, p(2)?, p(1)?))),
ArcV::Sce => Some(swap(Arc::from_start_center_end(p(0)?, p(1)?, p(2)?))),
ArcV::Sca => curves::arc_sca(p(0)?, p(1)?, n(2)?),
ArcV::Scl => curves::arc_scl(p(0)?, p(1)?, n(2)?),
ArcV::Sea => curves::arc_sea(p(0)?, p(1)?, n(2)?),
ArcV::Scl => curves::arc_scl(p(0)?, p(1)?, n(2)?).map(|a| if ctrl { clockwise_from_start(a) } else { a }),
ArcV::Sea => curves::arc_sea(p(0)?, p(1)?, if ctrl { -n(2)? } else { n(2)? }),
ArcV::Sed => curves::arc_sed(p(0)?, p(1)?, Vec2::from_angle(n(2)?)),
// Counter-clockwise from the end back to the start is clockwise from the start.
ArcV::Ser if ctrl => curves::arc_ser(p(1)?, p(0)?, n(2)?),
ArcV::Ser => curves::arc_ser(p(0)?, p(1)?, n(2)?),
// Center, Start, End. Ctrl keeps the two endpoints on the circle and walks the
// other way around: swapping the start/end angles is the mirror arc through the
// same two endpoints. (Continue below flips differently, by negating the start
// Center, Start, End. (Continue below flips differently, by negating the start
// tangent; both are "reverse", but only here is the chord fixed by the picks.)
ArcV::Cse => {
let a = Arc::from_start_center_end(p(1)?, p(0)?, p(2)?);
Some(if ctrl { Arc::new(a.center, a.radius, a.end, a.start) } else { a })
}
ArcV::Cse => Some(swap(Arc::from_start_center_end(p(1)?, p(0)?, p(2)?))),
ArcV::Csa => curves::arc_sca(p(1)?, p(0)?, n(2)?),
ArcV::Csl => curves::arc_scl(p(1)?, p(0)?, n(2)?),
ArcV::Csl => curves::arc_scl(p(1)?, p(0)?, n(2)?).map(|a| if ctrl { clockwise_from_start(a) } else { a }),
ArcV::CircleCd => {
let d = n(1)?.abs();
let c = p(0)?;
Expand All @@ -130,6 +142,13 @@ impl ArcV {
}
}

/// The counter-clockwise arc `a`, which starts at its start point, turned to sweep the same
/// angle clockwise from that point instead.
fn clockwise_from_start(a: Arc) -> Arc {
let sweep = norm_angle(a.end - a.start);
Arc::new(a.center, a.radius, a.start - sweep, a.start)
}

impl ArcV {
/// Options at step `i` and the variant each one switches to (the values so far carry over).
fn alts(self, i: usize) -> &'static [(&'static str, ArcV)] {
Expand Down Expand Up @@ -165,14 +184,17 @@ impl SeqM {
fn ask(&self) -> Option<(&'static str, Ask)> {
self.v.steps().get(self.vals.len()).copied()
}
fn value_from_point(&self, ask: Ask, q: Vec2) -> Option<Val> {
/// The value a picked point gives. With `ctrl` an included angle is measured clockwise
/// (negative), so the arc still ends on the ray through the cursor but goes the other way.
fn value_from_point(&self, ask: Ask, q: Vec2, ctrl: bool) -> Option<Val> {
let pt = |i: usize| self.vals.get(i).and_then(|x| x.p());
Some(match ask {
Ask::Point => Val::P(q),
Ask::Angle(b) => Val::N(pt(b)?.angle_to(q)),
Ask::Sweep(c, f) => {
let c = pt(c)?;
Val::N(norm_angle(c.angle_to(q) - c.angle_to(pt(f)?)))
let ccw = norm_angle(c.angle_to(q) - c.angle_to(pt(f)?));
Val::N(if ctrl && ccw > 0.0 { ccw - std::f64::consts::TAU } else { ccw })
}
Ask::Dist(b) => Val::N(pt(b)?.dist(q)),
})
Expand Down Expand Up @@ -235,12 +257,14 @@ impl Interactive for SeqM {
}
let Some((_, ask)) = self.ask() else { return Ok(Step::Done) };
let val = match (&i, ask) {
(Input::Point(q), _) => self.value_from_point(ask, *q),
(Input::Point(q), _) => self.value_from_point(ask, *q, s.ctrl_down),
(Input::Text(t), Ask::Angle(_) | Ask::Sweep(..)) => {
// The tangent direction is a direction; included angles are sizes.
let au = s.angle_settings();
let a = if self.v == ArcV::Sed { au.direction(t) } else { au.amount(t) };
Some(Val::N(a.ok_or_else(|| other("Requires a valid angle."))?))
let a = a.ok_or_else(|| other("Requires a valid angle."))?;
// A typed included angle is signed already; Ctrl reverses it like a picked one.
Some(Val::N(if s.ctrl_down && matches!(ask, Ask::Sweep(..)) { -a } else { a }))
}
(Input::Text(t), Ask::Dist(_)) => Some(Val::N(number(t).ok_or_else(|| other("Requires numeric distance or a point."))?)),
(Input::Enter, _) => return Ok(Step::Cancel),
Expand Down Expand Up @@ -274,7 +298,7 @@ impl Interactive for SeqM {
return curves::arc_sed(st, c, d).map(|a| vec![arc(&a)]).unwrap_or_default();
}
let Some((_, ask)) = self.ask() else { return Vec::new() };
let Some(v) = self.value_from_point(ask, c) else { return Vec::new() };
let Some(v) = self.value_from_point(ask, c, s.ctrl_down) else { return Vec::new() };
let mut vals = self.vals.clone();
vals.push(v);
let mut out: Vec<EntityKind> = self.base().map(|b| vec![line(b, c)]).unwrap_or_default();
Expand Down
121 changes: 121 additions & 0 deletions crates/engine/tests/it/arc_ctrl_direction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
//!
//! Both should land on the same circle with its two halves swapped, so the assertions below
//! are the same: same center, same radius, and the start/end angles are exchanged.
//!
//! The other ARC variants AutoCAD lets Ctrl reverse are below `every_variant_…`: each one is
//! drawn with and without Ctrl, and the rubber band shown while Ctrl is held must be the arc
//! the click then creates.

use draftcraft_engine::doc::EntityKind;
use draftcraft_engine::geom::Vec2;
Expand Down Expand Up @@ -106,3 +110,120 @@ fn no_ctrl_is_the_old_behavior() {
let plain = run_continue(false);
assert!(plain.0.y > 0.0, "tangent as-is puts the center above the chord: {:?}", plain.0);
}

// ---------------- every ARC variant whose direction Ctrl switches ----------------

/// Same angle modulo a full turn.
fn same_angle(a: f64, b: f64) -> bool {
let d = (a - b).rem_euclid(std::f64::consts::TAU);
d < 1e-9 || d > std::f64::consts::TAU - 1e-9
}

/// Types each input at the command line, holding Ctrl (or not) for the last one, and returns
/// the arc it made plus, when the last input is a point, the arc previewed at that point first.
fn draw(inputs: &[&str], ctrl: bool) -> ((Vec2, f64, f64, f64), Option<(Vec2, f64, f64, f64)>) {
let mut s = Session::new();
s.execute("setvar", &serde_json::json!({ "name": "OSMODE", "value": 0 })).unwrap();
let (last, first) = inputs.split_last().unwrap();
for t in first {
s.cmdline(t).unwrap();
}
assert!(s.prompt_text().contains("hold Ctrl"), "{inputs:?}: the last prompt should advertise Ctrl: {}", s.prompt_text());
s.ctrl_down = ctrl;
let previewed = last.split_once(',').map(|(x, y)| {
let c = Vec2::new(x.parse().unwrap(), y.parse().unwrap());
let arcs: Vec<_> = s
.preview(c)
.into_iter()
.filter_map(|e| match e.kind {
EntityKind::Arc(a) => Some((a.center.xy(), a.radius, a.start, a.end)),
_ => None,
})
.collect();
assert_eq!(arcs.len(), 1, "{inputs:?}: one arc in the rubber band");
arcs[0]
});
s.cmdline(last).unwrap();
assert!(s.current_prompt().is_none(), "{inputs:?}: ARC should be done");
(last_arc(&s), previewed)
}

fn same_arc(a: (Vec2, f64, f64, f64), b: (Vec2, f64, f64, f64)) -> bool {
a.0.dist(b.0) < 1e-9 && near(a.1, b.1) && same_angle(a.2, b.2) && same_angle(a.3, b.3)
}

/// How a Ctrl arc relates to the plain one.
enum Flip {
/// Same circle, other way round: start and end angles swap.
Swap,
/// Same sweep, clockwise from the same start point.
ClockwiseFromStart,
/// Same two endpoints and radius, the center mirrored across the chord.
Mirror(Vec2),
}

#[test]
fn every_variant_ctrl_switches_direction_in_preview_and_result() {
// Start (5,0), center (0,0) and the point (0,5) a quarter turn counter-clockwise.
let cases: &[(&str, &[&str], Flip)] = &[
("start, center, end", &["arc", "5,0", "c", "0,0", "0,5"], Flip::Swap),
("start, end, center", &["arc", "5,0", "e", "0,5", "0,0"], Flip::Swap),
("center, start, end", &["arc", "c", "0,0", "5,0", "0,5"], Flip::Swap),
("start, center, picked angle", &["arc", "5,0", "c", "0,0", "a", "0,5"], Flip::Swap),
("center, start, picked angle", &["arc", "c", "0,0", "5,0", "a", "0,5"], Flip::Swap),
("start, center, typed angle", &["arc", "5,0", "c", "0,0", "a", "90"], Flip::ClockwiseFromStart),
("center, start, typed angle", &["arc", "c", "0,0", "5,0", "a", "90"], Flip::ClockwiseFromStart),
("start, center, chord length", &["arc", "5,0", "c", "0,0", "l", "5"], Flip::ClockwiseFromStart),
("center, start, chord length", &["arc", "c", "0,0", "5,0", "l", "5"], Flip::ClockwiseFromStart),
("start, end, angle", &["arc", "5,0", "e", "0,5", "a", "90"], Flip::Mirror(Vec2::new(5.0, 5.0))),
("start, end, radius", &["arc", "5,0", "e", "0,5", "r", "5"], Flip::Mirror(Vec2::new(5.0, 5.0))),
];
for (name, inputs, flip) in cases {
let (plain, plain_preview) = draw(inputs, false);
let (flipped, flipped_preview) = draw(inputs, true);
for (arc, preview) in [(plain, plain_preview), (flipped, flipped_preview)] {
if let Some(p) = preview {
assert!(same_arc(arc, p), "{name}: the rubber band {p:?} is not the arc drawn {arc:?}");
}
}
assert!(plain.0.dist(Vec2::ZERO) < 1e-9 && near(plain.1, 5.0), "{name}: plain arc {plain:?}");
assert!(same_angle(plain.2, 0.0), "{name}: plain arc starts at the start point: {plain:?}");
assert!(!same_arc(plain, flipped), "{name}: Ctrl changed nothing: {plain:?}");
match flip {
Flip::Swap => assert!(
same_arc(flipped, (plain.0, plain.1, plain.3, plain.2)),
"{name}: Ctrl must walk the other way round the same circle: {plain:?} vs {flipped:?}"
),
Flip::ClockwiseFromStart => {
let sw = sweep(plain.2, plain.3);
assert!(
same_arc(flipped, (plain.0, plain.1, plain.2 - sw, plain.2)),
"{name}: Ctrl must sweep the same angle clockwise from the start: {plain:?} vs {flipped:?}"
);
}
Flip::Mirror(c) => {
assert!(flipped.0.dist(*c) < 1e-9 && near(flipped.1, plain.1), "{name}: mirrored center expected: {flipped:?}");
// Counter-clockwise from the end point (0,5) back to the start point (5,0).
let end = Vec2::new(0.0, 5.0) - *c;
let start = Vec2::new(5.0, 0.0) - *c;
assert!(same_angle(flipped.2, end.y.atan2(end.x)) && same_angle(flipped.3, start.y.atan2(start.x)), "{name}: {flipped:?}");
}
}
}
}

/// ARC's three-point form and the tangent direction variant have no Ctrl in AutoCAD; holding it
/// changes nothing there.
#[test]
fn ctrl_leaves_three_point_and_direction_arcs_alone() {
for inputs in [&["arc", "5,0", "3.5355339,3.5355339", "0,5"][..], &["arc", "5,0", "e", "0,5", "d", "90"][..]] {
let mut a = Session::new();
let mut b = Session::new();
b.ctrl_down = true;
for t in inputs {
a.cmdline(t).unwrap();
b.cmdline(t).unwrap();
}
assert!(same_arc(last_arc(&a), last_arc(&b)), "{inputs:?}");
}
}
4 changes: 3 additions & 1 deletion crates/ui-egui/src/canvas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,9 @@ fn navigate_canvas(app: &mut CadApp, ui: &mut egui::Ui, nav: &Navigation<'_>) ->
let p = nav.pointer;
let inside = p.hover_pos.is_some_and(|at| nav.rect.contains(at) && ui.ctx().layer_id_at(at) == Some(ui.layer_id()) && nav.response.hovered());
let on_menu = p.hover_pos.is_some_and(|at| over_canvas_menu(app, at));
app.session.ctrl_down = p.mods.ctrl;
// ARC's "hold Ctrl to switch direction": Ctrl everywhere, and Cmd too on macOS (`mac_cmd`;
// `command` is Cmd there and Ctrl elsewhere), where a Ctrl-click can turn into a right click.
app.session.ctrl_down = p.mods.ctrl || p.mods.command || p.mods.mac_cmd;
ui.input(|i| {
for event in &i.raw.events {
if let egui::Event::MouseWheel { unit, .. } = event {
Expand Down
29 changes: 29 additions & 0 deletions crates/ui-egui/src/canvas/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,3 +272,32 @@ fn selection_window_previews_what_it_would_select() {
assert!(app.canvas.window_preview.is_empty());
assert_eq!(app.session.selection(), vec![line]);
}

/// ARC's "hold Ctrl to switch direction" reads `Session::ctrl_down`, which the canvas writes
/// every frame: Ctrl does it everywhere, and Cmd (egui's `command`) does too, which is how it
/// is held on macOS, where a Ctrl-click can turn into a right click.
#[test]
fn ctrl_or_cmd_held_reaches_the_session() {
let mut app = CadApp::new(draftcraft_engine::Session::new(), crate::Services::default());
let ctx = egui::Context::default();
let frame = |app: &mut CadApp, modifiers: egui::Modifiers| {
let raw = egui::RawInput {
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0))),
events: vec![egui::Event::ModifiersChanged(modifiers), egui::Event::PointerMoved(pos2(700.0, 450.0))],
..Default::default()
};
ctx.run_ui(raw, |ui| {
app.logic(ui.ctx());
app.ui(ui);
})
.textures_delta
.clear();
app.session.ctrl_down
};
assert!(!frame(&mut app, egui::Modifiers::NONE));
assert!(frame(&mut app, egui::Modifiers::CTRL), "Ctrl");
assert!(!frame(&mut app, egui::Modifiers::NONE), "released");
assert!(frame(&mut app, egui::Modifiers::MAC_CMD), "Cmd on macOS");
assert!(frame(&mut app, egui::Modifiers::COMMAND), "Command");
assert!(!frame(&mut app, egui::Modifiers::SHIFT), "Shift alone");
}
16 changes: 16 additions & 0 deletions crates/ui-egui/src/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
//! - `ui.pointer {x, y, space?: "world"|"screen", button?: left|right, action?: click|move}`
//! - `ui.click {x, y, shift?, ctrl?}`, `ui.move {x, y}`: real egui pointer input in screen points
//! - `ui.key {key, cmd?, shift?, alt?}`, `ui.text {text}`: synthetic keyboard input
//! - `ui.modifiers {ctrl?, cmd?, shift?, alt?}`: hold these modifier keys (all false releases them)
//! - `ui.set {...UiState fields}`, `ui.resize {width, height}`
//! - `ui.screenshot {path?}`: PNG of the window; `ui.render {path?, width?, height?, fit?, window?,
//! background?, plot_style?}`: headless render of the drawing (no window needed; fits the drawing
Expand Down Expand Up @@ -209,6 +210,7 @@ const METHODS: &[(&str, &str, &str)] = &[
("ui.move", "{x, y}", "Real egui pointer move in screen points."),
("ui.drag", "{x, y, to: [x, y], button?}", "Real press, move and release."),
("ui.key", "{key, cmd?, shift?, alt?}", "Synthetic key press."),
("ui.modifiers", "{ctrl?, cmd?, shift?, alt?}", "Hold modifier keys until the next call (e.g. ARC's hold Ctrl to switch direction)."),
("ui.text", "{text}", "Synthetic text input."),
("ui.set", "UiState fields", "Change UI state: palettes, toolbars, command line, theme…"),
("ui.resize", "{width, height}", "Resize the window."),
Expand Down Expand Up @@ -445,6 +447,20 @@ pub fn handle(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -> Ou
app.synthetic.push(egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers });
ok(Value::Null)
}
// Holds modifiers like a real key held down: egui keeps them until the next change.
"ui.modifiers" => {
let b = |k: &str| p.get(k).and_then(Value::as_bool).unwrap_or(false);
let modifiers = egui::Modifiers {
alt: b("alt"),
shift: b("shift"),
command: b("cmd") || (b("ctrl") && !cfg!(target_os = "macos")),
mac_cmd: b("cmd") && cfg!(target_os = "macos"),
ctrl: b("ctrl") || (b("cmd") && !cfg!(target_os = "macos")),
};
app.synthetic_held = modifiers;
app.synthetic.push(egui::Event::ModifiersChanged(modifiers));
ok(Value::Null)
}
"ui.text" => {
app.synthetic.push(egui::Event::Text(s("text").unwrap_or("").to_string()));
ok(Value::Null)
Expand Down
Loading