diff --git a/OpenNest.Desktop.Tests/Forms/CutTimeReportTests.cs b/OpenNest.Desktop.Tests/Forms/CutTimeReportTests.cs new file mode 100644 index 00000000..aa652c12 --- /dev/null +++ b/OpenNest.Desktop.Tests/Forms/CutTimeReportTests.cs @@ -0,0 +1,186 @@ +using System.Globalization; +using OpenNest.Data; +using OpenNest.Forms; + +namespace OpenNest.Desktop.Tests.Forms; + +public sealed class CutTimeReportTests : IDisposable +{ + private readonly CultureInfo previous = CultureInfo.CurrentCulture; + + public CutTimeReportTests() => CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; + + public void Dispose() => CultureInfo.CurrentCulture = previous; + + private static CutParameters Entered(Units units = Units.Inches, MachineConfig? machine = null) => + CutTimeEntry.Parameters(120, 60, 600, 1, true, units, machine); + + // Two squares on the plate, two of the sheet cut. + private static Nest TwoSquares() + { + var nest = TestNests.TwoSquares(); + nest.Plates[0].Quantity = 2; + return nest; + } + + // The WinForms TimingForm computed these itself before the report was shared; the report + // must give the same numbers for the same inputs. + [Fact] + public void ForPlate_IsTheTimingTheWinFormsDialogShowed() + { + var nest = TwoSquares(); + var plate = nest.Plates[0]; + var parameters = Entered(machine: new MachineConfig { Units = UnitSystem.Inches }); + + var report = CutTimeReport.ForPlate(plate, parameters, nest.Units); + + var info = Timing.GetTimingInfo(plate); + Assert.Equal(Timing.CalculateTime(plate, parameters), report.CutTime); + Assert.Equal(info.CutDistance, report.Info.CutDistance); + Assert.Equal(info.TravelDistance, report.Info.TravelDistance); + Assert.Equal(info.PierceCount, report.Info.PierceCount); + Assert.Equal(info.IntersectionCount, report.Info.IntersectionCount); + } + + [Fact] + public void ForNest_AddsEveryPlate() + { + var nest = TwoSquares(); + nest.Plates.Add(TestNests.TwoSquares().Plates[0]); + var parameters = Entered(); + + var report = CutTimeReport.ForNest(nest, parameters); + + Assert.Equal(Timing.CalculateTime(nest, parameters), report.CutTime); + Assert.Equal(Timing.GetTimingInfo(nest).CutDistance, report.Info.CutDistance); + Assert.Equal( + Timing.CalculateTime(nest.Plates[0], parameters) + Timing.CalculateTime(nest.Plates[1], parameters), + report.CutTime); + } + + // Full speed: each square's 40 in of hole contour at 60 in/min is 40 s, plus a 1 s pierce; + // two squares, two sheets, and the rapid between them at 600 in/min. + [Fact] + public void ForPlate_FullSpeed_TheHandWorkedTime() + { + var nest = TwoSquares(); + var report = CutTimeReport.ForPlate(nest.Plates[0], Entered(), Units.Inches); + + var rapid = TimeSpan.FromMinutes(20.0 / 600); + var sheet = 2 * (TimeSpan.FromSeconds(40) + TimeSpan.FromSeconds(1)) + rapid; + Assert.Equal(sheet.TotalSeconds * 2, report.CutTime.TotalSeconds, 6); + Assert.Equal("02m 48s", report.CutTimeText); + } + + [Fact] + public void Texts_AreWordedAsTheWinFormsTimingWindow() + { + var nest = TwoSquares(); + var report = CutTimeReport.ForPlate(nest.Plates[0], Entered(), Units.Inches); + + // Quantity 2: two squares of 40 in, twice. + Assert.Equal("160 in", report.CutDistanceText); + Assert.Equal(report.Info.PierceCount.ToString(), report.PierceCountText); + Assert.Equal(report.Info.IntersectionCount.ToString(), report.IntersectionCountText); + Assert.Equal("120 in/min", report.FeedrateText); + Assert.Equal("600 in/min", report.RapidText); + Assert.Equal("01s", report.PierceTimeText); + } + + [Fact] + public void Millimeters_ReadPerSecond() + { + Assert.Equal("250 mm/sec", CutTimeReport.RateText(250, Units.Millimeters)); + Assert.Equal("12.3457 mm", CutTimeReport.DistanceText(12.345678, Units.Millimeters)); + } + + [Theory] + [InlineData(3723, "1h 02m 03s")] + [InlineData(90000, "25h 00m 00s")] + [InlineData(125, "02m 05s")] + [InlineData(45, "45s")] + [InlineData(5, "05s")] + [InlineData(0, "00s")] + public void FormatTime_AsTheWinFormsTimingWindow(int seconds, string expected) => + Assert.Equal(expected, CutTimeReport.FormatTime(TimeSpan.FromSeconds(seconds))); + + [Fact] + public void FormatTime_UnderAMinute_RoundsTheSeconds() => + Assert.Equal("13s", CutTimeReport.FormatTime(TimeSpan.FromSeconds(12.6))); + + [Fact] + public void Entry_TheWinFormsBoxValues() + { + var machine = new MachineConfig { Units = UnitSystem.Millimeters }; + + var parameters = CutTimeEntry.Parameters(250, 120.5m, 1000, 0.75m, false, Units.Inches, machine); + + Assert.Equal(250, parameters.Feedrate); + Assert.Equal(120.5, parameters.HoleFeedrate); + Assert.Equal(1000, parameters.RapidTravelRate); + Assert.Equal(TimeSpan.FromSeconds(0.75), parameters.PierceTime); + Assert.False(parameters.SkipScribe); + Assert.Equal(Units.Inches, parameters.Units); + var expected = machine.GetMotionOrPlaceholder().ToProfile(UnitSystem.Millimeters, Units.Inches); + Assert.Equal(expected.CutAcceleration, parameters.Motion.CutAcceleration); + } + + [Fact] + public void Entry_FullSpeed_HasNoMotion() => + Assert.Null(CutTimeEntry.Parameters(1, 1, 1, 0, true, Units.Inches, null).Motion); + + [Fact] + public void Entry_Clamp_TakesTheBoxRange() + { + Assert.Equal(CutTimeEntry.MaximumRate, CutTimeEntry.Clamp(20000, CutTimeEntry.MinimumRate, CutTimeEntry.MaximumRate)); + Assert.Equal(CutTimeEntry.MinimumRate, CutTimeEntry.Clamp(0, CutTimeEntry.MinimumRate, CutTimeEntry.MaximumRate)); + Assert.Equal(0.5m, CutTimeEntry.Clamp(0.5, 0, CutTimeEntry.DialogMaximumPierce)); + } + + // The saved settings round trip through the boxes unchanged. + [Fact] + public void Entry_FromSavedSettings_GivesTheSavedParameters() + { + var saved = new SavedCutTimeSettings(250, 120.5m, 1000, 0.75m, false, SavedCutTimeSettings.FullSpeed); + var loaded = saved.ToCutParameters(Units.Inches, null); + + var entered = CutTimeEntry.Parameters( + (decimal)loaded.Feedrate, (decimal)loaded.HoleFeedrate!.Value, (decimal)loaded.RapidTravelRate, + (decimal)loaded.PierceTime.TotalSeconds, loaded.SkipScribe, Units.Inches, null); + + Assert.Equal(saved, saved.With(entered)); + } + + [Fact] + public void MachineChoices_FullSpeedFirst_ThenByName_MarkingPlaceholders() + { + var machines = new List + { + new() { Name = "Zeta", Motion = new MotionConfig() }, + new() { Name = "alpha" }, + }; + + var choices = CutTimeMachineChoice.For(machines); + + Assert.Equal(["None (full speed)", "alpha (placeholder)", "Zeta"], choices.Select(c => c.ToString())); + Assert.Null(choices[0].GetMotion(Units.Inches)); + Assert.NotNull(choices[1].GetMotion(Units.Inches)); + } + + [Fact] + public void MachineChoices_SavedIndex() + { + var id = Guid.NewGuid(); + var choices = CutTimeMachineChoice.For( + [ + new MachineConfig { Name = "b" }, + new MachineConfig { Id = id, Name = "c" }, + new MachineConfig { Name = "a" }, + ]); + + Assert.Equal(3, CutTimeMachineChoice.SavedIndex(choices, id.ToString())); + Assert.Equal(1, CutTimeMachineChoice.SavedIndex(choices, "")); + Assert.Equal(0, CutTimeMachineChoice.SavedIndex(choices, SavedCutTimeSettings.FullSpeed)); + Assert.Equal(0, CutTimeMachineChoice.SavedIndex(CutTimeMachineChoice.For([]), "")); + } +} diff --git a/OpenNest.Desktop.Tests/Interaction/CutSimulationPlaybackTests.cs b/OpenNest.Desktop.Tests/Interaction/CutSimulationPlaybackTests.cs new file mode 100644 index 00000000..73beddc3 --- /dev/null +++ b/OpenNest.Desktop.Tests/Interaction/CutSimulationPlaybackTests.cs @@ -0,0 +1,354 @@ +using System.Globalization; +using OpenNest.CNC; +using OpenNest.Desktop.Interaction; +using OpenNest.Geometry; + +namespace OpenNest.Desktop.Tests.Interaction; + +public sealed class CutSimulationPlaybackTests : IDisposable +{ + private readonly CultureInfo previous = CultureInfo.CurrentCulture; + + public CutSimulationPlaybackTests() => CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; + + public void Dispose() => CultureInfo.CurrentCulture = previous; + + private static Plate TwoSquares() => TestNests.TwoSquares().Plates[0]; + + private static CutParameters FullSpeed(double feed = 60) => new() + { + Feedrate = feed, + HoleFeedrate = feed, + RapidTravelRate = 600, + PierceTime = TimeSpan.FromSeconds(1), + Units = Units.Inches, + }; + + private static CutSimulationPlayback Loaded(Plate plate, CutParameters? parameters = null) + { + var playback = new CutSimulationPlayback(); + playback.Load(CutSimulation.Build(plate, parameters ?? FullSpeed())); + return playback; + } + + [Fact] + public void Time_WithoutATimeline_StaysAtZero() + { + var playback = new CutSimulationPlayback(); + var changes = 0; + playback.Changed += (_, _) => changes++; + + playback.Time = TimeSpan.FromSeconds(5); + + Assert.Equal(TimeSpan.Zero, playback.Time); + Assert.Equal(0, changes); + } + + [Fact] + public void Time_StaysWithinTheTimeline() + { + var playback = Loaded(TwoSquares()); + + playback.Time = TimeSpan.FromHours(1); + Assert.Equal(playback.Simulation.TotalTime, playback.Time); + + playback.Time = TimeSpan.FromSeconds(-1); + Assert.Equal(TimeSpan.Zero, playback.Time); + } + + [Fact] + public void Advance_MovesBySpeedTimesWallTime_AndPausesAtTheEnd() + { + var playback = Loaded(TwoSquares()); + playback.Speed = 5; + playback.Play(); + Assert.True(playback.IsPlaying); + + playback.Advance(TimeSpan.FromSeconds(2)); + Assert.Equal(TimeSpan.FromSeconds(10), playback.Time); + + playback.Advance(TimeSpan.FromHours(1)); + Assert.Equal(playback.Simulation.TotalTime, playback.Time); + Assert.False(playback.IsPlaying); + } + + [Fact] + public void Play_AtTheEnd_StartsOver() + { + var playback = Loaded(TwoSquares()); + playback.End(); + + playback.Play(); + + Assert.Equal(TimeSpan.Zero, playback.Time); + Assert.True(playback.IsPlaying); + } + + [Fact] + public void Play_WithNothingToCut_DoesNotStart() + { + var playback = Loaded(new Plate(new Size(48, 96))); + + playback.Play(); + + Assert.False(playback.IsPlaying); + } + + [Fact] + public void Load_Retimed_KeepsTheTorchWhereItWas() + { + var plate = TwoSquares(); + var playback = Loaded(plate, FullSpeed(60)); + playback.Time = TimeSpan.FromSeconds(15); + var before = playback.Simulation.ToolPositionAt(playback.Time); + + playback.Load(CutSimulation.Build(plate, FullSpeed(120))); + + var after = playback.Simulation.ToolPositionAt(playback.Time); + Assert.Equal(before.X, after.X, 6); + Assert.Equal(before.Y, after.Y, 6); + Assert.NotEqual(TimeSpan.FromSeconds(15), playback.Time); + } + + [Fact] + public void Load_DifferentMoves_KeepsThePlayheadTime() + { + var plate = TwoSquares(); + var playback = Loaded(plate); + playback.Time = TimeSpan.FromSeconds(15); + plate.Parts.RemoveAt(1); + + playback.Load(CutSimulation.Build(plate, FullSpeed())); + + Assert.Equal(TimeSpan.FromSeconds(15), playback.Time); + } + + [Fact] + public void Load_Null_Pauses() + { + var playback = Loaded(TwoSquares()); + playback.Play(); + + playback.Load(null!); + + Assert.False(playback.IsPlaying); + Assert.False(playback.IsActive); + } + + [Fact] + public void Parts_JumpForwardAndBack_Pausing() + { + var playback = Loaded(TwoSquares()); + var sim = playback.Simulation; + Assert.Equal(2, sim.PartStarts.Count); + playback.Play(); + + // The first part starts the timeline, so the next is the second. + Assert.Equal(TimeSpan.Zero, sim.PartStarts[0]); + playback.NextPart(); + Assert.False(playback.IsPlaying); + Assert.Equal(sim.PartStarts[1], playback.Time); + + playback.NextPart(); + Assert.Equal(sim.TotalTime, playback.Time); + + playback.PreviousPart(); + Assert.Equal(sim.PartStarts[1], playback.Time); + + // Already at a part's start: back to the one before. + playback.PreviousPart(); + Assert.Equal(sim.PartStarts[0], playback.Time); + } + + [Fact] + public void Contours_JumpForwardAndBack() + { + var playback = Loaded(TwoSquares()); + var sim = playback.Simulation; + + playback.NextContour(); + Assert.Equal(sim.ContourStarts[1], playback.Time); + + playback.Time += TimeSpan.FromSeconds(1); + playback.PreviousContour(); + Assert.Equal(sim.ContourStarts[1], playback.Time); + + playback.PreviousContour(); + Assert.Equal(sim.ContourStarts[0], playback.Time); + } + + [Fact] + public void StepMove_GoesOneMoveAtATime() + { + var playback = Loaded(TwoSquares()); + var steps = playback.Simulation.Steps; + + playback.StepMove(1); + Assert.Equal(steps[1].StartTime, playback.Time); + playback.StepMove(1); + Assert.Equal(steps[2].StartTime, playback.Time); + + // At a move's start, back to the one before; mid-move, back to its start. + playback.StepMove(-1); + Assert.Equal(steps[1].StartTime, playback.Time); + playback.Time = steps[2].StartTime + TimeSpan.FromTicks(steps[2].Duration.Ticks / 2); + playback.StepMove(-1); + Assert.Equal(steps[2].StartTime, playback.Time); + + playback.Time = TimeSpan.Zero; + playback.StepMove(-1); + Assert.Equal(TimeSpan.Zero, playback.Time); + } + + [Fact] + public void TogglePlay_RebuildsOnlyAtTheStartOrEnd() + { + var plate = TwoSquares(); + var playback = Loaded(plate); + var rebuilds = 0; + void Rebuild() + { + rebuilds++; + playback.Load(CutSimulation.Build(plate, FullSpeed())); + } + + playback.TogglePlay(Rebuild); + Assert.True(playback.IsPlaying); + Assert.Equal(1, rebuilds); + + playback.TogglePlay(Rebuild); + Assert.False(playback.IsPlaying); + + playback.Time = TimeSpan.FromSeconds(10); + playback.TogglePlay(Rebuild); + Assert.True(playback.IsPlaying); + Assert.Equal(1, rebuilds); + } + + [Fact] + public void Restart_KeepsPlaying_EndPauses() + { + var playback = Loaded(TwoSquares()); + playback.Time = TimeSpan.FromSeconds(10); + playback.Play(); + + playback.Restart(); + Assert.Equal(TimeSpan.Zero, playback.Time); + Assert.True(playback.IsPlaying); + + playback.End(); + Assert.False(playback.IsPlaying); + Assert.Equal(playback.Simulation.TotalTime, playback.Time); + } + + [Fact] + public void Seek_AndProgress_AreFractionsOfTheTimeline() + { + var playback = Loaded(TwoSquares()); + + playback.Seek(0.5); + + Assert.Equal(playback.Simulation.TotalTime / 2, playback.Time); + Assert.Equal(0.5, playback.Progress, 6); + } + + [Fact] + public void IsPartPending_UntilTheTorchReachesThePart() + { + var playback = Loaded(TwoSquares()); + var sim = playback.Simulation; + + playback.Time = TimeSpan.Zero; + Assert.True(playback.IsPartPending(1)); + + // On the travel to the second part, it has not been touched yet. + var travel = sim.Steps.First(s => s.PartIndex == 1 && s.Kind == CutSimulationStepKind.Rapid); + playback.Time = travel.StartTime + TimeSpan.FromTicks(travel.Duration.Ticks / 2); + Assert.False(playback.IsPartPending(0)); + Assert.True(playback.IsPartPending(1)); + + playback.Time = sim.PartStarts[1] + TimeSpan.FromSeconds(0.5); + Assert.False(playback.IsPartPending(1)); + + playback.End(); + Assert.False(playback.IsPartPending(1)); + } + + [Fact] + public void Clear_DropsTheTimelineAndStops() + { + var playback = Loaded(TwoSquares()); + playback.Play(); + + playback.Clear(); + + Assert.Null(playback.Simulation); + Assert.False(playback.IsPlaying); + Assert.Equal(TimeSpan.Zero, playback.Time); + Assert.False(playback.IsPartPending(0)); + } + + [Fact] + public void Speeds_StartAtFiveTimes() + { + Assert.Equal(CutSimulationPlayback.DefaultSpeed, CutSimulationPlayback.Speeds[CutSimulationPlayback.DefaultSpeedIndex]); + Assert.Equal("5×", CutSimulationStatus.SpeedText(5)); + Assert.Equal("250×", CutSimulationStatus.SpeedText(250)); + } + + [Fact] + public void Status_NothingToCut() + { + var status = CutSimulationStatus.For(new CutSimulationPlayback(), null!, Units.Inches); + + Assert.Equal(new CutSimulationStatus("Nothing to cut", "", "", ""), status); + } + + [Fact] + public void Status_Cutting_ShowsTheFeedPerMinute() + { + var plate = TwoSquares(); + var playback = Loaded(plate); + // Mid-way along the first part's cut, past its pierce. + var cut = playback.Simulation.Steps.First(s => s.Kind == CutSimulationStepKind.Cut); + playback.Time = cut.StartTime + TimeSpan.FromTicks(cut.Duration.Ticks / 2); + + var status = CutSimulationStatus.For(playback, plate, Units.Inches); + + Assert.Equal($"{CutTimeFormat(playback.Time)} / {CutTimeFormat(playback.Simulation.TotalTime)}", status.Time); + Assert.Equal("1 of 2", status.Part); + Assert.Equal("square", status.Drawing); + Assert.Equal("Cutting · 60 in/min", status.Motion); + } + + [Fact] + public void Status_Piercing_HasNoSpeed() + { + var plate = TwoSquares(); + var playback = Loaded(plate); + var pierce = playback.Simulation.Steps.First(s => s.Kind == CutSimulationStepKind.Pierce); + playback.Time = pierce.StartTime + TimeSpan.FromTicks(pierce.Duration.Ticks / 2); + + Assert.Equal("Piercing", CutSimulationStatus.For(playback, plate, Units.Inches).Motion); + } + + [Fact] + public void Status_Done() + { + var plate = TwoSquares(); + var playback = Loaded(plate); + playback.End(); + + var status = CutSimulationStatus.For(playback, plate, Units.Inches); + + Assert.Equal("2 of 2", status.Part); + Assert.Equal("", status.Drawing); + Assert.Equal("Done", status.Motion); + } + + [Fact] + public void FeedText_MillimetersPerSecond() => + Assert.Equal("25 mm/sec", CutSimulationStatus.FeedText(25, Units.Millimeters)); + + private static string CutTimeFormat(TimeSpan time) => OpenNest.Forms.CutTimeReport.FormatTime(time); +} diff --git a/OpenNest.Desktop.Tests/TestNests.cs b/OpenNest.Desktop.Tests/TestNests.cs index 04a7a253..f29d2e22 100644 --- a/OpenNest.Desktop.Tests/TestNests.cs +++ b/OpenNest.Desktop.Tests/TestNests.cs @@ -30,4 +30,32 @@ internal static class TestNests nest.Plates.Add(plate); return nest; } + + /// + /// A nest with one 48x96 plate holding two 10x10 squares drawn as imported part programs are + /// (incremental, counterclockwise from the corner), the second 20 to the right of the first. + /// + public static Nest TwoSquares() + { + var program = new Program(Mode.Incremental); + program.Codes.Add(new RapidMove(new Vector(0, 0))); + program.Codes.Add(new LinearMove(new Vector(10, 0))); + program.Codes.Add(new LinearMove(new Vector(0, 10))); + program.Codes.Add(new LinearMove(new Vector(-10, 0))); + program.Codes.Add(new LinearMove(new Vector(0, -10))); + + var drawing = new Drawing("square", program); + drawing.Quantity.Required = 2; + + var plate = new Plate(new Size(48, 96)); + plate.Parts.Add(new Part(drawing)); + var second = new Part(drawing); + second.Offset(new Vector(20, 0)); + plate.Parts.Add(second); + + var nest = new Nest { Name = "test" }; + nest.Drawings.Add(drawing); + nest.Plates.Add(plate); + return nest; + } } diff --git a/OpenNest.Desktop/CutTimeEntry.cs b/OpenNest.Desktop/CutTimeEntry.cs new file mode 100644 index 00000000..38627571 --- /dev/null +++ b/OpenNest.Desktop/CutTimeEntry.cs @@ -0,0 +1,39 @@ +using System; +using OpenNest.Data; + +namespace OpenNest.Desktop; + +/// +/// The cut-time values entered in Calculate Cut Time or the simulator, with the ranges their +/// WinForms boxes take: feeds and rapid from 1 to 9999 per time unit, pierce seconds from 0 to +/// 100 in the dialog and to 999 in the simulator. +/// +public static class CutTimeEntry +{ + public const decimal MinimumRate = 1; + public const decimal MaximumRate = 9999; + public const decimal DialogMaximumPierce = 100; + public const decimal SimulatorMaximumPierce = 999; + + /// A value shown in a box from to . + public static decimal Clamp(double value, decimal minimum, decimal maximum) => + System.Math.Clamp((decimal)value, minimum, maximum); + + /// + /// The parameters the entered values time with in , with + /// 's acceleration (null for full speed). + /// + public static CutParameters Parameters( + decimal feed, decimal holeFeed, decimal rapid, decimal pierceSeconds, bool skipEtch, + Units units, MachineConfig machine) => + new() + { + Feedrate = (double)feed, + HoleFeedrate = (double)holeFeed, + RapidTravelRate = (double)rapid, + PierceTime = TimeSpan.FromSeconds((double)pierceSeconds), + SkipScribe = skipEtch, + Units = units, + Motion = CutTimeMachineChoice.Motion(machine, units), + }; +} diff --git a/OpenNest.Desktop/CutTimeMachineChoice.cs b/OpenNest.Desktop/CutTimeMachineChoice.cs new file mode 100644 index 00000000..f9384bb6 --- /dev/null +++ b/OpenNest.Desktop/CutTimeMachineChoice.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using OpenNest.Data; + +namespace OpenNest.Desktop; + +/// +/// One entry of the cut-time Acceleration list: a machine whose acceleration limits time the +/// moves, or none for full speed everywhere. Named as the WinForms list names them: a machine +/// with no saved motion values is marked "(placeholder)". +/// +public sealed record CutTimeMachineChoice(MachineConfig Machine) +{ + public const string FullSpeedText = "None (full speed)"; + + public override string ToString() => + Machine == null ? FullSpeedText + : Machine.Motion == null ? $"{Machine.Name} (placeholder)" + : Machine.Name; + + /// Full speed first, then by name. + public static List For(IEnumerable machines) + { + ArgumentNullException.ThrowIfNull(machines); + var choices = new List { new((MachineConfig)null) }; + choices.AddRange(SavedCutTimeSettings.SortedByName(machines).Select(m => new CutTimeMachineChoice(m))); + return choices; + } + + /// + /// The index in of the remembered choice (): the first machine until one is saved, full speed + /// when saved so or when there are no machines. + /// + public static int SavedIndex(IReadOnlyList choices, string saved) + { + ArgumentNullException.ThrowIfNull(choices); + var machine = SavedCutTimeSettings.ChooseMachine( + choices.Where(c => c.Machine != null).Select(c => c.Machine), saved); + for (var i = 0; i < choices.Count; i++) + { + if (ReferenceEquals(choices[i].Machine, machine)) + return i; + } + return 0; + } + + /// The machine's limits in , or null for full speed. + public MotionProfile GetMotion(Units units) => Motion(Machine, units); + + /// + /// 's limits (its placeholder without saved ones) in + /// , or null for full speed. + /// + public static MotionProfile Motion(MachineConfig machine, Units units) => + machine?.GetMotionOrPlaceholder().ToProfile(machine.Units, units); +} diff --git a/OpenNest.Desktop/Forms/CutTimeReport.cs b/OpenNest.Desktop/Forms/CutTimeReport.cs new file mode 100644 index 00000000..4d57510f --- /dev/null +++ b/OpenNest.Desktop/Forms/CutTimeReport.cs @@ -0,0 +1,99 @@ +using System; + +namespace OpenNest.Forms +{ + /// + /// What Calculate Cut Time shows for a plate or a nest, worded as the WinForms timing window: + /// the time from (the simulation + /// with acceleration, plus clamp removal, over the quantity) and the distances and counts from + /// . Numbers are in the current culture. + /// + public sealed class CutTimeReport + { + private CutTimeReport(Units units, CutParameters parameters, TimingInfo info, TimeSpan cutTime) + { + Units = units; + Parameters = parameters; + Info = info; + CutTime = cutTime; + } + + public Units Units { get; } + + public CutParameters Parameters { get; } + + public TimingInfo Info { get; } + + public TimeSpan CutTime { get; } + + /// Plate > Calculate Cut Time: in its nest's . + public static CutTimeReport ForPlate(Plate plate, CutParameters parameters, Units units) + { + ArgumentNullException.ThrowIfNull(plate); + ArgumentNullException.ThrowIfNull(parameters); + return new CutTimeReport(units, parameters, Timing.GetTimingInfo(plate), Timing.CalculateTime(plate, parameters)); + } + + /// Nest > Calculate Cut Time: every plate of . + public static CutTimeReport ForNest(Nest nest, CutParameters parameters) + { + ArgumentNullException.ThrowIfNull(nest); + ArgumentNullException.ThrowIfNull(parameters); + return new CutTimeReport(nest.Units, parameters, Timing.GetTimingInfo(nest), Timing.CalculateTime(nest, parameters)); + } + + public string CutTimeText => FormatTime(CutTime); + + public string CutDistanceText => DistanceText(Info.CutDistance, Units); + + public string RapidDistanceText => DistanceText(Info.TravelDistance, Units); + + public string PierceCountText => Info.PierceCount.ToString(); + + public string IntersectionCountText => Info.IntersectionCount.ToString(); + + /// The outside feed, as the timing window's "Feedrate". + public string FeedrateText => RateText(Parameters.Feedrate, Units); + + public string RapidText => RateText(Parameters.RapidTravelRate, Units); + + public string PierceTimeText => FormatTime(Parameters.PierceTime); + + /// A distance rounded to four places with the unit, as "12.3457 in". + public static string DistanceText(double distance, Units units) => + string.Format("{0} {1}", System.Math.Round(distance, 4), UnitsHelper.GetShortString(units)); + + /// A rate with its unit pair, as "250 in/min". + public static string RateText(double rate, Units units) => + string.Format("{0} {1}/{2}", rate, UnitsHelper.GetShortString(units), UnitsHelper.GetShortTimeUnit(units)); + + /// + /// "1h 02m 03s" from an hour, "02m 03s" from a minute, otherwise whole seconds as "45s" + /// (at least two digits). + /// + public static string FormatTime(TimeSpan time) + { + var hrs = time.Days * 24 + time.Hours; + var min = time.Minutes; + var sec = time.Seconds; + + var msg = string.Empty; + + if (hrs > 0) + { + msg += hrs.ToString() + "h "; + msg += min.ToString().PadLeft(2, '0') + "m "; + msg += sec.ToString().PadLeft(2, '0') + "s"; + } + else if (min > 0) + { + msg += min.ToString().PadLeft(2, '0') + "m "; + msg += sec.ToString().PadLeft(2, '0') + "s"; + } + else + msg += time.TotalSeconds.ToString("n0").PadLeft(2, '0') + "s"; + + return msg; + } + } +} diff --git a/OpenNest.Desktop/Interaction/CutSimulationPlayback.cs b/OpenNest.Desktop/Interaction/CutSimulationPlayback.cs new file mode 100644 index 00000000..5d52c198 --- /dev/null +++ b/OpenNest.Desktop/Interaction/CutSimulationPlayback.cs @@ -0,0 +1,233 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using OpenNest.CNC; + +namespace OpenNest.Desktop.Interaction; + +/// +/// The Cut Simulator's playhead over a , without drawing: the time, +/// play and pause at a speed, the jumps between parts, cutouts and moves, and which parts the +/// torch has not reached. The host runs a timer that calls while +/// and redraws after each change. +/// +public sealed class CutSimulationPlayback +{ + /// The simulator's speed choices, as multiples of real time. + public static IReadOnlyList Speeds { get; } = new double[] { 1, 2, 5, 10, 25, 50, 100, 250 }; + + /// The speed the simulator starts at. + public const double DefaultSpeed = 5; + + /// The index of in . + public static int DefaultSpeedIndex => 2; + + private readonly Stopwatch clock = new(); + private CutSimulation simulation; + private TimeSpan time; + private bool playing; + + /// Raised when the playhead, play state or timeline changes. + public event EventHandler Changed; + + public CutSimulation Simulation => simulation; + + public bool IsActive => simulation != null; + + public bool IsPlaying => playing; + + /// Simulated time per wall-clock time. + public double Speed { get; set; } = 10; + + /// The playhead, kept within the timeline; nothing changes without one. + public TimeSpan Time + { + get => time; + set + { + if (simulation == null) + return; + time = value < TimeSpan.Zero ? TimeSpan.Zero : value > simulation.TotalTime ? simulation.TotalTime : value; + Changed?.Invoke(this, EventArgs.Empty); + } + } + + /// + /// Shows , keeping the torch where it was when the moves are the same + /// (new rates or acceleration only retime them), else keeping the playhead's time. + /// + public void Load(CutSimulation value) + { + var anchored = Anchor(simulation, value, time); + simulation = value; + Time = anchored; + if (simulation == null) + Pause(); + Changed?.Invoke(this, EventArgs.Empty); + } + + /// Where on falls on . + public static TimeSpan Anchor(CutSimulation old, CutSimulation next, TimeSpan time) + { + if (old == null || next == null || old.Steps.Count == 0 || old.Steps.Count != next.Steps.Count) + return time; + var index = old.IndexAt(time); + if (index >= old.Steps.Count) + return next.TotalTime; + return next.TimeAt(index, old.FractionAt(index, time)); + } + + /// Plays from the playhead, or from the start once it is at the end. + public void Play() + { + if (simulation == null || simulation.Steps.Count == 0) + return; + if (time >= simulation.TotalTime) + Time = TimeSpan.Zero; + clock.Restart(); + playing = true; + Changed?.Invoke(this, EventArgs.Empty); + } + + public void Pause() + { + if (!playing) + return; + playing = false; + clock.Reset(); + Changed?.Invoke(this, EventArgs.Empty); + } + + /// Drops the timeline and stops. + public void Clear() + { + playing = false; + clock.Reset(); + simulation = null; + time = TimeSpan.Zero; + Changed?.Invoke(this, EventArgs.Empty); + } + + /// Moves the playhead by the wall time since the last advance (or since Play). + public void Advance() + { + var elapsed = clock.Elapsed; + clock.Restart(); + Advance(elapsed); + } + + /// + /// Moves the playhead by times , pausing at + /// the end. + /// + public void Advance(TimeSpan wallElapsed) + { + if (simulation == null) + return; + var next = time + TimeSpan.FromTicks((long)(wallElapsed.Ticks * Speed)); + time = next > simulation.TotalTime ? simulation.TotalTime : next; + Changed?.Invoke(this, EventArgs.Empty); + if (time >= simulation.TotalTime) + Pause(); + } + + /// + /// The play button: pauses while playing; otherwise plays, first calling + /// (parts may have moved, which raises no plate event) when there + /// is no timeline or the playhead is at its start or end. + /// + public void TogglePlay(Action rebuild) + { + if (playing) + { + Pause(); + return; + } + if (simulation == null || time <= TimeSpan.Zero || time >= simulation.TotalTime) + rebuild?.Invoke(); + Play(); + } + + /// Back to the start (Home), still playing if it was. + public void Restart() => Time = TimeSpan.Zero; + + /// Pauses at the end. + public void End() + { + Pause(); + Time = simulation?.TotalTime ?? TimeSpan.Zero; + } + + public void NextContour() => Jump(sim => sim.NextContour(time)); + + public void PreviousContour() => Jump(sim => sim.PreviousContour(time)); + + public void NextPart() => Jump(sim => sim.NextPart(time)); + + public void PreviousPart() => Jump(sim => sim.PreviousPart(time)); + + // Jumps pause so the jumped-to contour stays on screen. + private void Jump(Func target) + { + if (simulation is not { } sim || sim.Steps.Count == 0) + return; + Pause(); + Time = target(sim); + } + + /// + /// Pauses at the start of the next move ( > 0), or back at the + /// start of the current move, or of the one before when already there. + /// + public void StepMove(int direction) + { + var sim = simulation; + if (sim == null || sim.Steps.Count == 0) + return; + Pause(); + var index = System.Math.Clamp(sim.IndexAt(time), 0, sim.Steps.Count); + var atStart = index < sim.Steps.Count && time == sim.Steps[index].StartTime; + var target = direction > 0 ? index + 1 : atStart ? index - 1 : index; + Time = target <= 0 ? TimeSpan.Zero + : target >= sim.Steps.Count ? sim.TotalTime + : sim.Steps[target].StartTime; + } + + /// The playhead as a fraction of the timeline (0 without one). + public double Progress => + simulation is { } sim && sim.TotalTime > TimeSpan.Zero ? time / sim.TotalTime : 0; + + /// Moves the playhead to of the timeline (a scrub). + public void Seek(double fraction) + { + if (simulation != null) + Time = simulation.TotalTime * fraction; + } + + /// True for a part the torch has not started yet. + public bool IsPartPending(int partIndex) + { + if (simulation == null) + return false; + var index = simulation.IndexAt(time); + if (index >= simulation.Steps.Count) + return false; + if (index < 0) + return true; + var current = simulation.Steps[index]; + // Travel toward a part has not touched it yet. + return partIndex > current.PartIndex + || partIndex == current.PartIndex && current.Kind == CutSimulationStepKind.Rapid && !PartStarted(index); + } + + private bool PartStarted(int index) + { + var part = simulation.Steps[index].PartIndex; + for (var i = index - 1; i >= 0 && simulation.Steps[i].PartIndex == part; i--) + { + if (simulation.Steps[i].Kind != CutSimulationStepKind.Rapid) + return true; + } + return false; + } +} diff --git a/OpenNest.Desktop/Interaction/CutSimulationStatus.cs b/OpenNest.Desktop/Interaction/CutSimulationStatus.cs new file mode 100644 index 00000000..f5b5fc07 --- /dev/null +++ b/OpenNest.Desktop/Interaction/CutSimulationStatus.cs @@ -0,0 +1,56 @@ +using System; +using OpenNest.CNC; +using OpenNest.Forms; + +namespace OpenNest.Desktop.Interaction; + +/// +/// The Cut Simulator's status rows, worded as the WinForms simulator: the time as "elapsed / +/// total", the part as "n of m", its drawing, and the motion with the speed at the playhead. +/// +public sealed record CutSimulationStatus(string Time, string Part, string Drawing, string Motion) +{ + public const string NothingToCut = "Nothing to cut"; + + /// The rows for on in . + public static CutSimulationStatus For(CutSimulationPlayback playback, Plate plate, Units units) + { + ArgumentNullException.ThrowIfNull(playback); + var sim = playback.Simulation; + if (sim == null || sim.Steps.Count == 0) + return new CutSimulationStatus(NothingToCut, string.Empty, string.Empty, string.Empty); + + var time = playback.Time; + var timeText = $"{CutTimeReport.FormatTime(time)} / {CutTimeReport.FormatTime(sim.TotalTime)}"; + + var index = sim.IndexAt(time); + if (index >= sim.Steps.Count) + return new CutSimulationStatus(timeText, $"{sim.PartCount} of {sim.PartCount}", string.Empty, "Done"); + + var step = sim.Steps[index]; + var drawing = plate != null && step.PartIndex < plate.Parts.Count ? plate.Parts[step.PartIndex].BaseDrawing?.Name : null; + var state = step.Kind switch + { + CutSimulationStepKind.Rapid => "Rapid", + CutSimulationStepKind.Pierce => "Piercing", + CutSimulationStepKind.Scribe => "Scribing", + _ => "Cutting", + }; + if (step.Kind != CutSimulationStepKind.Pierce) + state += $" · {FeedText(step.SpeedAt(time - step.StartTime), units)}"; + return new CutSimulationStatus(timeText, $"{step.PartIndex + 1} of {sim.PartCount}", drawing ?? string.Empty, state); + } + + /// + /// A speed in units per second as the feed reads: inch feeds per minute, millimeter feeds per + /// second, as uses them. + /// + public static string FeedText(double unitsPerSecond, Units units) + { + var rate = units == Units.Millimeters ? unitsPerSecond : unitsPerSecond * 60; + return $"{rate:n0} {UnitsHelper.GetShortTimeUnitPair(units)}"; + } + + /// The speed list's text for , as "5×". + public static string SpeedText(double speed) => $"{speed:g}×"; +} diff --git a/OpenNest/Controls/CutSimulationOverlay.cs b/OpenNest/Controls/CutSimulationOverlay.cs index 7558bca9..b28536c6 100644 --- a/OpenNest/Controls/CutSimulationOverlay.cs +++ b/OpenNest/Controls/CutSimulationOverlay.cs @@ -6,6 +6,7 @@ using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Windows.Forms; using OpenNest.CNC; +using OpenNest.Desktop.Interaction; using OpenNest.Geometry; using OpenNest.Math; @@ -26,10 +27,8 @@ internal sealed class CutSimulationOverlay : IDisposable private readonly PlateView view; private readonly Timer timer; private readonly Timer settleTimer; - private readonly Stopwatch clock = new(); private readonly Stopwatch sinceZoom = new(); - private CutSimulation simulation; - private TimeSpan time; + private readonly CutSimulationPlayback playback = new(); // The finished trail, rendered once at the scale it was built for, so panning and playback // only blit it and draw the moves since. Null when the whole timeline would be too large an @@ -52,26 +51,43 @@ internal sealed class CutSimulationOverlay : IDisposable settleTimer.Stop(); view.Invalidate(); }; + // The timer runs while the playhead plays, which stops itself at the end. + playback.Changed += (_, _) => + { + if (timer.Enabled != playback.IsPlaying) + timer.Enabled = playback.IsPlaying; + }; } /// Raised when the playhead, play state or timeline changes. - public event EventHandler Changed; + public event EventHandler Changed + { + add => playback.Changed += value; + remove => playback.Changed -= value; + } - public CutSimulation Simulation => simulation; - public bool IsActive => simulation != null; - public bool IsPlaying => timer.Enabled; - public double Speed { get; set; } = 10; + /// The playhead the simulator steps; each change through this overlay also redraws. + public CutSimulationPlayback Playback => playback; + + public CutSimulation Simulation => playback.Simulation; + public bool IsActive => playback.IsActive; + public bool IsPlaying => playback.IsPlaying; + + public double Speed + { + get => playback.Speed; + set => playback.Speed = value; + } public TimeSpan Time { - get => time; + get => playback.Time; set { - if (simulation == null) + if (playback.Simulation == null) return; - time = value < TimeSpan.Zero ? TimeSpan.Zero : value > simulation.TotalTime ? simulation.TotalTime : value; + playback.Time = value; view.Invalidate(); - Changed?.Invoke(this, EventArgs.Empty); } } @@ -81,128 +97,71 @@ internal sealed class CutSimulationOverlay : IDisposable /// public void Load(CutSimulation value) { - var anchored = Anchor(simulation, value, time); - simulation = value; ResetTrail(); - Time = anchored; - if (simulation == null) - Pause(); + playback.Load(value); view.Invalidate(); - Changed?.Invoke(this, EventArgs.Empty); - } - - private static TimeSpan Anchor(CutSimulation old, CutSimulation next, TimeSpan time) - { - if (old == null || next == null || old.Steps.Count == 0 || old.Steps.Count != next.Steps.Count) - return time; - var index = old.IndexAt(time); - if (index >= old.Steps.Count) - return next.TotalTime; - return next.TimeAt(index, old.FractionAt(index, time)); } public void Play() { - if (simulation == null || simulation.Steps.Count == 0) - return; - if (time >= simulation.TotalTime) - Time = TimeSpan.Zero; - clock.Restart(); - timer.Start(); - Changed?.Invoke(this, EventArgs.Empty); + playback.Play(); + view.Invalidate(); } - public void Pause() + public void Pause() => playback.Pause(); + + /// Runs on the playhead, then redraws. + public void Step(Action action) { - if (!timer.Enabled) - return; - timer.Stop(); - clock.Reset(); - Changed?.Invoke(this, EventArgs.Empty); + action(playback); + view.Invalidate(); } public void Clear() { - timer.Stop(); - simulation = null; - time = TimeSpan.Zero; + playback.Clear(); ResetTrail(); view.Invalidate(); - Changed?.Invoke(this, EventArgs.Empty); } private void Tick() { - Advance(); + playback.Advance(); view.Invalidate(); } - // Moves the playhead by the wall time since the last advance. Paints call it too: WM_TIMER - // is only delivered when no paint is pending, so a pan's stream of repaints starves the timer. - private void Advance() - { - var elapsed = clock.Elapsed; - clock.Restart(); - var next = time + TimeSpan.FromTicks((long)(elapsed.Ticks * Speed)); - time = next > simulation.TotalTime ? simulation.TotalTime : next; - Changed?.Invoke(this, EventArgs.Empty); - if (time >= simulation.TotalTime) - Pause(); - } - /// True for a part the torch has not started yet. - public bool IsPartPending(int partIndex) - { - if (simulation == null) - return false; - var index = simulation.IndexAt(time); - if (index >= simulation.Steps.Count) - return false; - if (index < 0) - return true; - var current = simulation.Steps[index]; - // Travel toward a part has not touched it yet. - return partIndex > current.PartIndex - || partIndex == current.PartIndex && current.Kind == CutSimulationStepKind.Rapid && !PartStarted(index); - } - - private bool PartStarted(int index) - { - var part = simulation.Steps[index].PartIndex; - for (var i = index - 1; i >= 0 && simulation.Steps[i].PartIndex == part; i--) - { - if (simulation.Steps[i].Kind != CutSimulationStepKind.Rapid) - return true; - } - return false; - } + public bool IsPartPending(int partIndex) => playback.IsPartPending(partIndex); public void Draw(Graphics graphics) { - if (simulation == null || simulation.Steps.Count == 0) + if (Simulation == null || Simulation.Steps.Count == 0) return; + // Paints advance too: WM_TIMER is only delivered when no paint is pending, so a pan's + // stream of repaints starves the timer. if (IsPlaying) - Advance(); + playback.Advance(); var state = graphics.Save(); try { graphics.SmoothingMode = SmoothingMode.AntiAlias; var dpi = view.DeviceDpi / 96f; - var index = simulation.IndexAt(time); - var finished = System.Math.Clamp(index, 0, simulation.Steps.Count); + var time = playback.Time; + var index = Simulation.IndexAt(time); + var finished = System.Math.Clamp(index, 0, Simulation.Steps.Count); using var pens = new TrailPens(dpi); DrawTrail(graphics, pens, finished); - if (index >= simulation.Steps.Count) + if (index >= Simulation.Steps.Count) { - DrawHead(graphics, simulation.Steps[^1].End, null, 0, dpi); + DrawHead(graphics, Simulation.Steps[^1].End, null, 0, dpi); return; } - var step = simulation.Steps[index]; - var fraction = simulation.FractionAt(index, time); + var step = Simulation.Steps[index]; + var fraction = Simulation.FractionAt(index, time); var partial = Points(step, fraction); if (partial.Length > 1) { @@ -293,7 +252,7 @@ internal sealed class CutSimulationOverlay : IDisposable trailPhase = phase; var bounds = RectangleF.Empty; - foreach (var step in simulation.Steps) + foreach (var step in Simulation.Steps) { if (step.Kind != CutSimulationStepKind.Pierce) bounds = bounds.IsEmpty ? StepBounds(step) : RectangleF.Union(bounds, StepBounds(step)); @@ -328,7 +287,7 @@ internal sealed class CutSimulationOverlay : IDisposable for (var i = from; i < to; i++) { - var step = simulation.Steps[i]; + var step = Simulation.Steps[i]; if (step.Kind == CutSimulationStepKind.Pierce) continue; diff --git a/OpenNest/Forms/CutParametersForm.cs b/OpenNest/Forms/CutParametersForm.cs index 88387b3f..f3fa933d 100644 --- a/OpenNest/Forms/CutParametersForm.cs +++ b/OpenNest/Forms/CutParametersForm.cs @@ -1,5 +1,6 @@ using System; using System.Windows.Forms; +using OpenNest.Desktop; using NumericUpDown = OpenNest.Controls.NumericUpDown; namespace OpenNest.Forms @@ -57,7 +58,7 @@ namespace OpenNest.Forms } private static decimal Clamp(System.Windows.Forms.NumericUpDown box, double value) => - System.Math.Clamp((decimal)value, box.Minimum, box.Maximum); + CutTimeEntry.Clamp(value, box.Minimum, box.Maximum); protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { @@ -86,18 +87,8 @@ namespace OpenNest.Forms holeFeedBox.Suffix = " " + suffix; } - public CutParameters GetCutParameters() - { - return new CutParameters() - { - Feedrate = (double)numericUpDown1.Value, - HoleFeedrate = (double)holeFeedBox.Value, - RapidTravelRate = (double)numericUpDown2.Value, - PierceTime = TimeSpan.FromSeconds((double)numericUpDown3.Value), - SkipScribe = skipEtchBox.Checked, - Units = units, - Motion = machineBox.GetMotion(units), - }; - } + public CutParameters GetCutParameters() => + CutTimeEntry.Parameters(numericUpDown1.Value, holeFeedBox.Value, numericUpDown2.Value, + numericUpDown3.Value, skipEtchBox.Checked, units, machineBox.Machine); } } diff --git a/OpenNest/Forms/CutSimulatorForm.cs b/OpenNest/Forms/CutSimulatorForm.cs index 3b79882d..405f818d 100644 --- a/OpenNest/Forms/CutSimulatorForm.cs +++ b/OpenNest/Forms/CutSimulatorForm.cs @@ -1,8 +1,11 @@ using System; +using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using OpenNest.CNC; using OpenNest.Controls; +using OpenNest.Desktop; +using OpenNest.Desktop.Interaction; using NumericUpDown = OpenNest.Controls.NumericUpDown; namespace OpenNest.Forms @@ -16,7 +19,7 @@ namespace OpenNest.Forms public sealed class CutSimulatorForm : Form { private const int TrackResolution = 1000; - private static readonly double[] Speeds = { 1, 2, 5, 10, 25, 50, 100, 250 }; + private static readonly IReadOnlyList Speeds = CutSimulationPlayback.Speeds; private readonly EditNestForm nestForm; private readonly CutSimulationOverlay overlay; @@ -55,8 +58,8 @@ namespace OpenNest.Forms endButton = TransportButton("⏭", 44, 12f); speedBox = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList, Width = 70, Anchor = AnchorStyles.Left }; foreach (var speed in Speeds) - speedBox.Items.Add($"{speed:g}×"); - speedBox.SelectedIndex = Array.IndexOf(Speeds, 5.0); + speedBox.Items.Add(CutSimulationStatus.SpeedText(speed)); + speedBox.SelectedIndex = CutSimulationPlayback.DefaultSpeedIndex; previousPartButton = JumpButton("◀◀ Part"); previousContourButton = JumpButton("◀ Cutout"); @@ -147,17 +150,13 @@ namespace OpenNest.Forms layout.Controls.Add(motion); Controls.Add(layout); - restartButton.Click += (_, _) => overlay.Time = TimeSpan.Zero; - endButton.Click += (_, _) => - { - overlay.Pause(); - overlay.Time = overlay.Simulation?.TotalTime ?? TimeSpan.Zero; - }; + restartButton.Click += (_, _) => overlay.Step(p => p.Restart()); + endButton.Click += (_, _) => overlay.Step(p => p.End()); playButton.Click += (_, _) => TogglePlay(); - previousPartButton.Click += (_, _) => Jump(sim => sim.PreviousPart(overlay.Time)); - previousContourButton.Click += (_, _) => Jump(sim => sim.PreviousContour(overlay.Time)); - nextContourButton.Click += (_, _) => Jump(sim => sim.NextContour(overlay.Time)); - nextPartButton.Click += (_, _) => Jump(sim => sim.NextPart(overlay.Time)); + previousPartButton.Click += (_, _) => overlay.Step(p => p.PreviousPart()); + previousContourButton.Click += (_, _) => overlay.Step(p => p.PreviousContour()); + nextContourButton.Click += (_, _) => overlay.Step(p => p.NextContour()); + nextPartButton.Click += (_, _) => overlay.Step(p => p.NextPart()); speedBox.SelectedIndexChanged += (_, _) => overlay.Speed = Speeds[speedBox.SelectedIndex]; trackBar.Scroll += (_, _) => Seek(); feedBox.ValueChanged += (_, _) => Rebuild(); @@ -217,15 +216,6 @@ namespace OpenNest.Forms private static Button JumpButton(string text) => new() { Text = text, AutoSize = true, MinimumSize = new Size(80, 0) }; - // Jumps pause so the jumped-to contour stays on screen. - private void Jump(Func target) - { - if (overlay.Simulation is not { } sim || sim.Steps.Count == 0) - return; - overlay.Pause(); - overlay.Time = target(sim); - } - private static Label StatusCaption(string text) => new() { Text = text, AutoSize = true, ForeColor = SystemColors.GrayText, Margin = new Padding(3, 2, 8, 2) }; @@ -245,16 +235,8 @@ namespace OpenNest.Forms new() { Text = text, AutoSize = true, Margin = new Padding(3, 7, 0, 0), Anchor = AnchorStyles.Left }; private CutParameters GetCutParameters() => - new() - { - Feedrate = (double)feedBox.Value, - HoleFeedrate = (double)holeFeedBox.Value, - SkipScribe = skipEtchBox.Checked, - RapidTravelRate = (double)rapidBox.Value, - PierceTime = TimeSpan.FromSeconds((double)pierceBox.Value), - Units = nestForm.Nest.Units, - Motion = machineBox.GetMotion(nestForm.Nest.Units), - }; + CutTimeEntry.Parameters(feedBox.Value, holeFeedBox.Value, rapidBox.Value, pierceBox.Value, + skipEtchBox.Checked, nestForm.Nest.Units, machineBox.Machine); private void Rebuild() { @@ -311,39 +293,17 @@ namespace OpenNest.Forms private void NestForm_FormClosed(object sender, FormClosedEventArgs e) => Close(); - private void TogglePlay() - { - if (overlay.IsPlaying) - { - overlay.Pause(); - return; - } - // Parts may have moved since the timeline was built; moves raise no plate event. - if (overlay.Simulation == null || overlay.Time <= TimeSpan.Zero || overlay.Time >= overlay.Simulation.TotalTime) - Rebuild(); - overlay.Play(); - } + // Parts may have moved since the timeline was built; moves raise no plate event. + private void TogglePlay() => overlay.Step(p => p.TogglePlay(Rebuild)); private void Seek() { if (updatingTrack || overlay.Simulation == null) return; - overlay.Time = overlay.Simulation.TotalTime * ((double)trackBar.Value / TrackResolution); + overlay.Step(p => p.Seek((double)trackBar.Value / TrackResolution)); } - private void StepMove(int direction) - { - var sim = overlay.Simulation; - if (sim == null || sim.Steps.Count == 0) - return; - overlay.Pause(); - var index = System.Math.Clamp(sim.IndexAt(overlay.Time), 0, sim.Steps.Count); - var atStart = index < sim.Steps.Count && overlay.Time == sim.Steps[index].StartTime; - var target = direction > 0 ? index + 1 : atStart ? index - 1 : index; - overlay.Time = target <= 0 ? TimeSpan.Zero - : target >= sim.Steps.Count ? sim.TotalTime - : sim.Steps[target].StartTime; - } + private void StepMove(int direction) => overlay.Step(p => p.StepMove(direction)); protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { @@ -358,16 +318,16 @@ namespace OpenNest.Forms TogglePlay(); return true; case Keys.Control | Keys.Right: - Jump(sim => sim.NextContour(overlay.Time)); + overlay.Step(p => p.NextContour()); return true; case Keys.Control | Keys.Left: - Jump(sim => sim.PreviousContour(overlay.Time)); + overlay.Step(p => p.PreviousContour()); return true; case Keys.PageDown: - Jump(sim => sim.NextPart(overlay.Time)); + overlay.Step(p => p.NextPart()); return true; case Keys.PageUp: - Jump(sim => sim.PreviousPart(overlay.Time)); + overlay.Step(p => p.PreviousPart()); return true; case Keys.Right: StepMove(1); @@ -376,7 +336,7 @@ namespace OpenNest.Forms StepMove(-1); return true; case Keys.Home: - overlay.Time = TimeSpan.Zero; + overlay.Step(p => p.Restart()); return true; } } @@ -391,49 +351,14 @@ namespace OpenNest.Forms var sim = overlay.Simulation; playButton.Text = overlay.IsPlaying ? "⏸" : "▶"; - if (sim == null || sim.Steps.Count == 0) - { - timeLabel.Text = "Nothing to cut"; - partLabel.Text = drawingLabel.Text = stateLabel.Text = string.Empty; - SetTrack(0); - return; - } - - var time = overlay.Time; - timeLabel.Text = $"{TimingForm.GetTimeMsg(time)} / {TimingForm.GetTimeMsg(sim.TotalTime)}"; - SetTrack(sim.TotalTime > TimeSpan.Zero ? (int)System.Math.Round(TrackResolution * (time / sim.TotalTime)) : 0); - - var index = sim.IndexAt(time); - if (index >= sim.Steps.Count) - { - partLabel.Text = $"{sim.PartCount} of {sim.PartCount}"; - drawingLabel.Text = string.Empty; - stateLabel.Text = "Done"; - return; - } - - var step = sim.Steps[index]; - var drawing = plate != null && step.PartIndex < plate.Parts.Count ? plate.Parts[step.PartIndex].BaseDrawing?.Name : null; - partLabel.Text = $"{step.PartIndex + 1} of {sim.PartCount}"; - drawingLabel.Text = drawing ?? string.Empty; - var state = step.Kind switch - { - CutSimulationStepKind.Rapid => "Rapid", - CutSimulationStepKind.Pierce => "Piercing", - CutSimulationStepKind.Scribe => "Scribing", - _ => "Cutting", - }; - if (step.Kind != CutSimulationStepKind.Pierce) - state += $" · {FeedText(step.SpeedAt(time - step.StartTime))}"; - stateLabel.Text = state; - } - - // Speeds are per second; inch feeds read per minute, as Timing uses them. - private string FeedText(double unitsPerSecond) - { - var units = nestForm.Nest.Units; - var rate = units == Units.Millimeters ? unitsPerSecond : unitsPerSecond * 60; - return $"{rate:n0} {UnitsHelper.GetShortTimeUnitPair(units)}"; + var status = CutSimulationStatus.For(overlay.Playback, plate, nestForm.Nest.Units); + timeLabel.Text = status.Time; + partLabel.Text = status.Part; + drawingLabel.Text = status.Drawing; + stateLabel.Text = status.Motion; + SetTrack(sim is { Steps.Count: > 0 } && sim.TotalTime > TimeSpan.Zero + ? (int)System.Math.Round(TrackResolution * (overlay.Time / sim.TotalTime)) + : 0); } private void SetTrack(int value) diff --git a/OpenNest/Forms/CutTimeMachineBox.cs b/OpenNest/Forms/CutTimeMachineBox.cs index 513b8849..1b7ae6f8 100644 --- a/OpenNest/Forms/CutTimeMachineBox.cs +++ b/OpenNest/Forms/CutTimeMachineBox.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Windows.Forms; using OpenNest.Data; using OpenNest.Desktop; @@ -13,37 +12,26 @@ namespace OpenNest.Forms /// internal sealed class CutTimeMachineBox : ComboBox { - private sealed record Choice(MachineConfig Machine) - { - public override string ToString() => - Machine == null ? "None (full speed)" - : Machine.Motion == null ? $"{Machine.Name} (placeholder)" - : Machine.Name; - } - public CutTimeMachineBox() { DropDownStyle = ComboBoxStyle.DropDownList; Width = 200; - var machines = SavedCutTimeSettings.SortedByName(MachineSettings.LoadMachines()); - Items.Add(new Choice(null)); - foreach (var machine in machines) - Items.Add(new Choice(machine)); + var choices = CutTimeMachineChoice.For(MachineSettings.LoadMachines()); + foreach (var choice in choices) + Items.Add(choice); - var saved = SavedMachine(machines); - SelectedItem = Items.Cast().First(c => c.Machine == saved); + SelectedIndex = CutTimeMachineChoice.SavedIndex(choices, Properties.Settings.Default.CutTimeMachine); } /// The remembered machine, the first one until a choice is saved, or null for full speed. public static MachineConfig SavedMachine(IEnumerable machines) => SavedCutTimeSettings.ChooseMachine(machines, Properties.Settings.Default.CutTimeMachine); - public MachineConfig Machine => (SelectedItem as Choice)?.Machine; + public MachineConfig Machine => (SelectedItem as CutTimeMachineChoice)?.Machine; /// The chosen machine's limits in , or null for full speed. - public MotionProfile GetMotion(Units units) => - Machine?.GetMotionOrPlaceholder().ToProfile(Machine.Units, units); + public MotionProfile GetMotion(Units units) => CutTimeMachineChoice.Motion(Machine, units); public void SaveChoice() { diff --git a/OpenNest/Forms/EditNestForm.cs b/OpenNest/Forms/EditNestForm.cs index 78381648..ebd3d55e 100644 --- a/OpenNest/Forms/EditNestForm.cs +++ b/OpenNest/Forms/EditNestForm.cs @@ -1219,31 +1219,20 @@ namespace OpenNest.Forms } public void CalculateCurrentPlateCutTime() => - ShowCutTime(() => Timing.GetTimingInfo(PlateView.Plate), cutparams => Timing.CalculateTime(PlateView.Plate, cutparams)); + ShowCutTime(cutparams => CutTimeReport.ForPlate(PlateView.Plate, cutparams, Nest.Units)); public void CalculateNestCutTime() => - ShowCutTime(() => Timing.GetTimingInfo(Nest), cutparams => Timing.CalculateTime(Nest, cutparams)); + ShowCutTime(cutparams => CutTimeReport.ForNest(Nest, cutparams)); - private void ShowCutTime(Func getInfo, Func calculateTime) + private void ShowCutTime(Func report) { var cutParamsForm = new CutParametersForm(); cutParamsForm.Units = Nest.Units; if (cutParamsForm.ShowDialog() == DialogResult.OK) { - var cutparams = cutParamsForm.GetCutParameters(); - var info = getInfo(); - var time = calculateTime(cutparams); - var timingForm = new TimingForm(); - timingForm.Units = Nest.Units; - timingForm.SetCutDistance(info.CutDistance); - timingForm.SetCutTime(time); - timingForm.SetIntersectionCount(info.IntersectionCount); - timingForm.SetPierceCount(info.PierceCount); - timingForm.SetRapidDistance(info.TravelDistance); - timingForm.SetCutParameters(cutparams); - + timingForm.SetReport(report(cutParamsForm.GetCutParameters())); timingForm.ShowDialog(); } } diff --git a/OpenNest/Forms/TimingForm.cs b/OpenNest/Forms/TimingForm.cs index 17f09baa..5233be21 100644 --- a/OpenNest/Forms/TimingForm.cs +++ b/OpenNest/Forms/TimingForm.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Windows.Forms; namespace OpenNest.Forms @@ -19,20 +19,12 @@ namespace OpenNest.Forms public void SetCutDistance(double dist) { - cutDistanceLabel.Text = string.Format( - "{0} {1}", - System.Math.Round(dist, 4), - UnitsHelper.GetShortString(Units) - ); + cutDistanceLabel.Text = CutTimeReport.DistanceText(dist, Units); } public void SetRapidDistance(double dist) { - rapidDistanceLabel.Text = string.Format( - "{0} {1}", - System.Math.Round(dist, 4), - UnitsHelper.GetShortString(Units) - ); + rapidDistanceLabel.Text = CutTimeReport.DistanceText(dist, Units); } public void SetIntersectionCount(int count) @@ -47,44 +39,25 @@ namespace OpenNest.Forms public void SetCutParameters(CutParameters cutparams) { - feedrateLabel.Text = string.Format( - "{0} {1}/{2}", - cutparams.Feedrate, - UnitsHelper.GetShortString(Units), - UnitsHelper.GetShortTimeUnit(Units) - ); - rapidLabel.Text = string.Format( - "{0} {1}/{2}", - cutparams.RapidTravelRate, - UnitsHelper.GetShortString(Units), - UnitsHelper.GetShortTimeUnit(Units) - ); + feedrateLabel.Text = CutTimeReport.RateText(cutparams.Feedrate, Units); + rapidLabel.Text = CutTimeReport.RateText(cutparams.RapidTravelRate, Units); pierceTimeLabel.Text = GetTimeMsg(cutparams.PierceTime); } - public static string GetTimeMsg(TimeSpan time) + /// Shows everything holds, in its units. + public void SetReport(CutTimeReport report) { - int hrs = time.Days * 24 + time.Hours; - int min = time.Minutes; - int sec = time.Seconds; - - string msg = string.Empty; - - if (hrs > 0) - { - msg += hrs.ToString() + "h "; - msg += min.ToString().PadLeft(2, '0') + "m "; - msg += sec.ToString().PadLeft(2, '0') + "s"; - } - else if (min > 0) - { - msg += min.ToString().PadLeft(2, '0') + "m "; - msg += sec.ToString().PadLeft(2, '0') + "s"; - } - else - msg += time.TotalSeconds.ToString("n0").PadLeft(2, '0') + "s"; - - return msg; + Units = report.Units; + cutTimeLabel.Text = report.CutTimeText; + cutDistanceLabel.Text = report.CutDistanceText; + rapidDistanceLabel.Text = report.RapidDistanceText; + interectionsLabel.Text = report.IntersectionCountText; + piercesLabel.Text = report.PierceCountText; + feedrateLabel.Text = report.FeedrateText; + rapidLabel.Text = report.RapidText; + pierceTimeLabel.Text = report.PierceTimeText; } + + public static string GetTimeMsg(TimeSpan time) => CutTimeReport.FormatTime(time); } }