diff --git a/OpenNest.Core/CNC/CutSimulation.cs b/OpenNest.Core/CNC/CutSimulation.cs index 11347aa1..b7d69a7b 100644 --- a/OpenNest.Core/CNC/CutSimulation.cs +++ b/OpenNest.Core/CNC/CutSimulation.cs @@ -129,6 +129,33 @@ namespace OpenNest.CNC return Length > 0 ? new Vector((End.X - Start.X) / Length, (End.Y - Start.Y) / Length) : Vector.Zero; } + /// The fraction (0..1) of this step at which the tool passes nearest . + internal double FractionNearest(Vector point) + { + if (Kind == CutSimulationStepKind.Pierce || Length <= 0) + return 0; + + if (IsArc) + { + var span = System.Math.Abs(Sweep); + if (point.DistanceTo(Center) > Tolerance.Epsilon) + { + var angle = Center.AngleTo(point); + var along = Sweep > 0 + ? Angle.NormalizeRad(angle - StartAngle) + : Angle.NormalizeRad(StartAngle - angle); + if (along <= span) + return along / span; + } + return point.DistanceTo(Start) <= point.DistanceTo(End) ? 0 : 1; + } + + var dx = End.X - Start.X; + var dy = End.Y - Start.Y; + var t = ((point.X - Start.X) * dx + (point.Y - Start.Y) * dy) / (dx * dx + dy * dy); + return System.Math.Clamp(t, 0, 1); + } + /// The tool position after (0..1) of this step. public Vector PointAt(double fraction) { @@ -308,6 +335,54 @@ namespace OpenNest.CNC return step.StartTime + TimeSpan.FromTicks(lo); } + /// + /// When the tool passes nearest , or null when no move comes within + /// . Cuts, scribes and pierces win over travel, so a rapid + /// crossing a cut never takes the click. Among passes about as near as the nearest (common + /// lines, overcuts, a lead-out over its lead-in), the one closest to + /// wins. + /// + public TimeSpan? TimeNearest(Vector point, double tolerance, TimeSpan current) + { + var hit = Nearest(point, tolerance, current, travel: false) + ?? Nearest(point, tolerance, current, travel: true); + return hit is { } h ? TimeAt(h.Index, h.Fraction) : null; + } + + private (int Index, double Fraction)? Nearest(Vector point, double tolerance, TimeSpan current, bool travel) + { + var hits = new List<(int Index, double Fraction, double Distance)>(); + var best = double.MaxValue; + for (var i = 0; i < steps.Count; i++) + { + if ((steps[i].Kind == CutSimulationStepKind.Rapid) != travel) + continue; + var fraction = steps[i].FractionNearest(point); + var distance = steps[i].PointAt(fraction).DistanceTo(point); + if (distance > tolerance) + continue; + hits.Add((i, fraction, distance)); + best = System.Math.Min(best, distance); + } + + // Passes this close are indistinguishable on screen; take the one nearest the playhead. + var band = best + tolerance / 2; + (int Index, double Fraction)? chosen = null; + var chosenGap = TimeSpan.MaxValue; + foreach (var (index, fraction, distance) in hits) + { + if (distance > band) + continue; + var gap = (TimeAt(index, fraction) - current).Duration(); + if (gap < chosenGap) + { + chosen = (index, fraction); + chosenGap = gap; + } + } + return chosen; + } + public Vector ToolPositionAt(TimeSpan time) { var index = IndexAt(time); diff --git a/OpenNest.Desktop.Tests/Interaction/CutSimulationPlaybackTests.cs b/OpenNest.Desktop.Tests/Interaction/CutSimulationPlaybackTests.cs index 73beddc3..35b6d226 100644 --- a/OpenNest.Desktop.Tests/Interaction/CutSimulationPlaybackTests.cs +++ b/OpenNest.Desktop.Tests/Interaction/CutSimulationPlaybackTests.cs @@ -351,4 +351,31 @@ public sealed class CutSimulationPlaybackTests : IDisposable Assert.Equal("25 mm/sec", CutSimulationStatus.FeedText(25, Units.Millimeters)); private static string CutTimeFormat(TimeSpan time) => OpenNest.Forms.CutTimeReport.FormatTime(time); + + [Fact] + public void SeekTo_PausesWhereTheToolPassesTheClick() + { + var playback = Loaded(TwoSquares()); + playback.Play(); + + Assert.True(playback.SeekTo(new Vector(25, 10.1), 0.5)); + + Assert.False(playback.IsPlaying); + var position = playback.Simulation.ToolPositionAt(playback.Time); + Assert.Equal(25, position.X, 4); + Assert.Equal(10, position.Y, 4); + } + + [Fact] + public void SeekTo_OffTheToolpath_ChangesNothing() + { + var playback = Loaded(TwoSquares()); + playback.Time = TimeSpan.FromSeconds(3); + playback.Play(); + + Assert.False(playback.SeekTo(new Vector(15, 50), 0.5)); + + Assert.True(playback.IsPlaying); + Assert.Equal(TimeSpan.FromSeconds(3), playback.Time); + } } diff --git a/OpenNest.Desktop/Interaction/CutSimulationPlayback.cs b/OpenNest.Desktop/Interaction/CutSimulationPlayback.cs index 5d52c198..909b91db 100644 --- a/OpenNest.Desktop/Interaction/CutSimulationPlayback.cs +++ b/OpenNest.Desktop/Interaction/CutSimulationPlayback.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; using OpenNest.CNC; +using OpenNest.Geometry; namespace OpenNest.Desktop.Interaction; @@ -204,6 +205,20 @@ public sealed class CutSimulationPlayback Time = simulation.TotalTime * fraction; } + /// + /// Pauses with the playhead where the tool passes nearest (plate + /// coordinates), as picks it; false, changing nothing, + /// when no move comes within . + /// + public bool SeekTo(Vector point, double tolerance) + { + if (simulation?.TimeNearest(point, tolerance, time) is not { } target) + return false; + Pause(); + Time = target; + return true; + } + /// True for a part the torch has not started yet. public bool IsPartPending(int partIndex) { diff --git a/OpenNest.Tests/CNC/CutSimulationTests.cs b/OpenNest.Tests/CNC/CutSimulationTests.cs index 3891bf4e..47754ba5 100644 --- a/OpenNest.Tests/CNC/CutSimulationTests.cs +++ b/OpenNest.Tests/CNC/CutSimulationTests.cs @@ -357,4 +357,74 @@ public class CutSimulationTests Assert.Equal(TimeSpan.Zero, sim.TotalTime); Assert.Equal(-1, sim.IndexAt(TimeSpan.Zero)); } + + private static readonly CutParameters Accelerated = new() + { + Feedrate = 100, + RapidTravelRate = 600, + PierceTime = TimeSpan.FromSeconds(1), + Units = Units.Inches, + Motion = new MotionProfile { CutAcceleration = 2, RapidAcceleration = 4, CornerDeviation = 0.001 }, + }; + + private static void AssertNear(Vector expected, Vector actual) => + Assert.True(expected.DistanceTo(actual) < 1e-4, $"expected {expected}, got {actual}"); + + [Fact] + public void TimeNearest_FindsThePointAlongALineUnderAcceleration() + { + var sim = CutSimulation.Build(PlateWith((Square(10), new Vector(30, 40))), Accelerated); + + var time = sim.TimeNearest(new Vector(33, 40.2), 0.5, TimeSpan.Zero); + + Assert.NotNull(time); + AssertNear(new Vector(33, 40), sim.ToolPositionAt(time.Value)); + } + + [Fact] + public void TimeNearest_FindsThePointAlongAnArc() + { + var program = new Program(); + program.Codes.Add(new RapidMove(10, 5)); + program.Codes.Add(new ArcMove(new Vector(10, 5), new Vector(5, 5), RotationType.CCW)); + var sim = CutSimulation.Build(PlateWith((program, new Vector(20, 20))), Accelerated); + + var time = sim.TimeNearest(new Vector(25, 30.3), 0.5, TimeSpan.Zero); + + Assert.NotNull(time); + AssertNear(new Vector(25, 30), sim.ToolPositionAt(time.Value)); + } + + [Fact] + public void TimeNearest_PrefersACutOverACloserRapid() + { + var sim = CutSimulation.Build(PlateWith((Square(10), new Vector(30, 40))), Parameters); + + // On the rapid in from the origin, half a unit short of the square's corner. + var time = sim.TimeNearest(new Vector(29.7, 39.6), 1, TimeSpan.Zero); + + Assert.NotNull(time); + Assert.NotEqual(CutSimulationStepKind.Rapid, sim.Steps[sim.IndexAt(time.Value)].Kind); + AssertNear(new Vector(30, 40), sim.ToolPositionAt(time.Value)); + } + + [Fact] + public void TimeNearest_TakesThePassNearestThePlayhead() + { + var sim = CutSimulation.Build(PlateWith((Square(10), new Vector(30, 40))), Parameters); + var corner = new Vector(30, 40); + var pierce = sim.Steps.First(s => s.Kind == CutSimulationStepKind.Pierce); + + // The square starts and closes at the same corner. + Assert.Equal(pierce.StartTime, sim.TimeNearest(corner, 0.5, TimeSpan.Zero)); + Assert.Equal(sim.TotalTime, sim.TimeNearest(corner, 0.5, sim.TotalTime)); + } + + [Fact] + public void TimeNearest_IsNullAwayFromTheToolpath() + { + var sim = CutSimulation.Build(PlateWith((Square(10), new Vector(30, 40))), Parameters); + + Assert.Null(sim.TimeNearest(new Vector(35, 45), 0.5, TimeSpan.Zero)); + } } diff --git a/OpenNest.WinForms.Tests/Controls/CutSimulationOverlayTests.cs b/OpenNest.WinForms.Tests/Controls/CutSimulationOverlayTests.cs index 9f351da2..177d7440 100644 --- a/OpenNest.WinForms.Tests/Controls/CutSimulationOverlayTests.cs +++ b/OpenNest.WinForms.Tests/Controls/CutSimulationOverlayTests.cs @@ -2,6 +2,7 @@ using System.Drawing; using OpenNest.CNC; using OpenNest.Controls; using OpenNest.Geometry; +using static OpenNest.WinForms.Tests.FormTesting; namespace OpenNest.WinForms.Tests.Controls; @@ -127,6 +128,39 @@ public class CutSimulationOverlayTests Assert.False(view.CutSimulation.IsPlaying); }); + [Fact] + public void ClickingThePlate_SeeksThereInsteadOfSelecting() => RunSta(() => + { + using var view = new PlateView { Plate = TwoSquares(), Size = new System.Drawing.Size(800, 600) }; + view.ZoomToFit(); + var sim = CutSimulation.Build(view.Plate, Parameters); + view.CutSimulation.Load(sim); + + // The second square's bottom edge, partway along. + var at = view.PointWorldToControl(new Vector(30, 5)); + Mouse(view, "OnMouseDown", at); + Mouse(view, "OnMouseUp", at); + + Assert.Empty(view.SelectedParts); + Assert.Equal(1, sim.Steps[sim.IndexAt(view.CutSimulation.Time)].PartIndex); + Assert.True(sim.ToolPositionAt(view.CutSimulation.Time).DistanceTo(new Vector(30, 5)) < 6 / view.ViewScale); + }); + + [Fact] + public void ClickingThePlate_SelectsOnceTheSimulatorCloses() => RunSta(() => + { + using var view = new PlateView { Plate = TwoSquares(), Size = new System.Drawing.Size(800, 600) }; + view.ZoomToFit(); + view.CutSimulation.Load(CutSimulation.Build(view.Plate, Parameters)); + view.CutSimulation.Clear(); + + var at = view.PointWorldToControl(new Vector(30, 10)); + Mouse(view, "OnMouseDown", at); + Mouse(view, "OnMouseUp", at); + + Assert.Single(view.SelectedParts); + }); + private static Color Pixel(PlateView view, Bitmap bitmap, Vector world) { var point = view.PointWorldToGraph(world); diff --git a/OpenNest/Controls/PlateView.cs b/OpenNest/Controls/PlateView.cs index 28033228..3ecfc5a3 100644 --- a/OpenNest/Controls/PlateView.cs +++ b/OpenNest/Controls/PlateView.cs @@ -240,6 +240,17 @@ namespace OpenNest.Controls ShowBendLines && plate != null && !HasProposalDisplay && !EditsLocked && actionManager.CurrentAction is ActionSelect; + // Pixels within which a click on the plate picks the cut simulator's time. + private const double SimulationPickPixels = 6; + private bool simulationClicked; + + /// + /// While the cut simulator is open, a left click sets its time to where the tool passes + /// nearest the click, in place of selecting parts. + /// + private bool PicksSimulationTime => + cutSimulation.IsActive && !HasProposalDisplay && actionManager.CurrentAction is ActionSelect; + private bool HitsGrainIndicator(Point controlPoint) => plate != null && GrainIndicator.Bounds(this, plate).Contains(controlPoint.X - origin.X, controlPoint.Y - origin.Y); @@ -530,6 +541,15 @@ namespace OpenNest.Controls if (e.Button == MouseButtons.Middle) middleMouseDownPoint = e.Location; + if (e.Button == MouseButtons.Left && PicksSimulationTime) + { + // The click is the simulator's; selection never sees it, down, up or double. + simulationClicked = true; + var point = CurrentPoint; + cutSimulation.Step(p => p.SeekTo(point, SimulationPickPixels / ViewScale)); + return; + } + if (EditsLocked) return; @@ -563,6 +583,11 @@ namespace OpenNest.Controls protected override void OnMouseUp(MouseEventArgs e) { + if (e.Button == MouseButtons.Left && simulationClicked) + { + simulationClicked = false; + return; + } if (EditsLocked) return; if (e.Button == MouseButtons.Left && grainIndicatorClicked) @@ -718,6 +743,8 @@ namespace OpenNest.Controls protected override void OnMouseDoubleClick(MouseEventArgs e) { + if (e.Button == MouseButtons.Left && simulationClicked) + return; if (!EditsLocked) base.OnMouseDoubleClick(e); diff --git a/OpenNest/Forms/CutSimulatorForm.cs b/OpenNest/Forms/CutSimulatorForm.cs index c53d249b..37d8e888 100644 --- a/OpenNest/Forms/CutSimulatorForm.cs +++ b/OpenNest/Forms/CutSimulatorForm.cs @@ -222,7 +222,7 @@ namespace OpenNest.Forms tips.SetToolTip(machineLabel, "The nest's machine, whose acceleration limits time the moves (Nest > Machine)"); tips.SetToolTip(heatBox, "Estimated heat in the sheet: now, or the hottest each area has been so far"); tips.SetToolTip(heatPowerBox, "Torch power that stays in the sheet as heat (an estimate; most of the beam leaves with the melt)"); - tips.SetToolTip(trackBar, "Drag to scrub through the cut (Left/Right step one move)"); + tips.SetToolTip(trackBar, "Drag to scrub through the cut (Left/Right step one move), or click the plate to jump to when the torch passes there"); overlay.Speed = Speeds[speedBox.SelectedIndex]; overlay.Changed += Overlay_Changed; diff --git a/README.md b/README.md index 8ab67ae4..db1a3e5f 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ A Windows desktop application for CNC nesting — imports DXF, DWG and SVG drawi - **Nesting** — automatic multi-plate/multi-material jobs, interlocking pair evaluation, and built-in or plug-in engines. [Choose an engine](docs/nesting-engines.md). - **Plate operations** — manual sheet cut-offs, [plate- or nest-wide automatic scrap cutoffs](docs/automatic-scrap-cutoffs.md) that cut the skeleton into strips sized for your scrap hopper while keeping a reusable tail, oversized-part splitting (straight, weld-gap tabs, spike-groove), interactive editing, and spacing-aware pushes that can slide along or away from touching parts. - **Visual overlap check** — highlight shared material on the active plate, rechecked automatically after edits, including containment and cutouts, with area shading, pair markers, and hover details through View > Overlap Check. [Usage and limitations](docs/geometry/visual-overlap-check.md). -- **Cut simulator** — Plate > Simulate Cutting replays the active plate in cut order: the torch traces each cut, rapid and pierce at adjustable feed, rapid and pierce settings, with play/pause, scrubbing, 1×–250× speed and previous/next part (Page Up/Down) and cutout (Ctrl+Left/Right) jumps. Parts the torch has not reached stay grayed. It and Calculate Cut Time use separate outside and hole feeds, skip etch-only contours like the CI Fiber post, and apply the chosen machine's acceleration and corner limits from Machine Configuration (placeholder values until you enter the controller's). [Timing model](docs/cut-time-estimates.md). +- **Cut simulator** — Plate > Simulate Cutting replays the active plate in cut order: the torch traces each cut, rapid and pierce at adjustable feed, rapid and pierce settings, with play/pause, scrubbing, a click on the plate to jump to when the torch passes there, 1×–250× speed and previous/next part (Page Up/Down) and cutout (Ctrl+Left/Right) jumps. Parts the torch has not reached stay grayed. It and Calculate Cut Time use separate outside and hole feeds, skip etch-only contours like the CI Fiber post, and apply the chosen machine's acceleration and corner limits from Machine Configuration (placeholder values until you enter the controller's). [Timing model](docs/cut-time-estimates.md). - **CNC output** — configurable lead-ins/outs and tabs, [support-bed checks that tab only the parts the grid or slats can't hold level](docs/support-tabs.md), contour editing, etched part-number labels with grain-based bend group letters so parts needing the same press brake angle correction can be formed together ([label box](docs/label-box.md)), user-defined G-code variables (`$name` → `#200+` machine variables), plugin post-processors (Cincinnati CL-707/800/900/940/CLX included). [Pre-post verification](docs/post-verification.md) checks overlaps, missing lead-ins, and rapid crossings, with explicit risk acknowledgment required to bypass warnings. ## Requirements diff --git a/docs/cut-time-estimates.md b/docs/cut-time-estimates.md index 52d0d4ed..cc661f75 100644 --- a/docs/cut-time-estimates.md +++ b/docs/cut-time-estimates.md @@ -6,6 +6,12 @@ and the last-used settings are shared through `SavedCutTimeSettings` (`OpenNest. both desktop apps read and write in the user settings. Both apps word the timing through `CutTimeReport` and play the simulator through `CutSimulationPlayback`. +While the simulator is open, a left click on the plate (with the Select tool, in place of +selecting parts) pauses at the time the tool passes nearest the click (`CutSimulation.TimeNearest`, +within 6 pixels). Cuts, scribes and pierces win over travel; where passes overlap (common lines, +overcuts, a lead-out over its lead-in) the one nearest the current time wins. +A click off the toolpath does nothing. + ## Inputs - **Outside feed, hole feed, rapid and pierce** from the dialog or simulator. Inch rates are per