diff --git a/.github/workflows/server-image.yml b/.github/workflows/server-image.yml index b02b69b2..fcef121c 100644 --- a/.github/workflows/server-image.yml +++ b/.github/workflows/server-image.yml @@ -114,8 +114,7 @@ jobs: publish: if: >- github.repository == 'ajisaacs/OpenNest' && - ((github.event_name == 'release' && github.event.release.prerelease == false) || - (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/master')) + github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/master' runs-on: ubuntu-latest timeout-minutes: 40 permissions: diff --git a/OpenNest.Core/CNC/CuttingPlanning/ContourEntryCandidate.cs b/OpenNest.Core/CNC/CuttingPlanning/ContourEntryCandidate.cs index 87560b04..68e00051 100644 --- a/OpenNest.Core/CNC/CuttingPlanning/ContourEntryCandidate.cs +++ b/OpenNest.Core/CNC/CuttingPlanning/ContourEntryCandidate.cs @@ -70,9 +70,11 @@ internal enum SupportEntries /// /// One automatic start candidate: the owned contour choice plus its preference kind and a /// stable geometry tie key for deterministic ranking. The choice keeps this preparation as -/// owner; nothing here exposes or mutates the underlying shape. +/// owner; nothing here exposes or mutates the underlying shape. +/// is how far a corner fillet's joint lies from the sharp corner it rounds (0 otherwise), so +/// ranking can count it on both of that corner's sides. /// -internal sealed record ContourEntryCandidate(ContourChoice Choice, AutomaticEntryKind Kind) +internal sealed record ContourEntryCandidate(ContourChoice Choice, AutomaticEntryKind Kind, double CornerReach = 0) { /// /// Stable geometric tie key: the point quantized to the preparation epsilon grid, so diff --git a/OpenNest.Core/CNC/CuttingPlanning/ContourEntryRanking.cs b/OpenNest.Core/CNC/CuttingPlanning/ContourEntryRanking.cs index 56e7a288..30dde691 100644 --- a/OpenNest.Core/CNC/CuttingPlanning/ContourEntryRanking.cs +++ b/OpenNest.Core/CNC/CuttingPlanning/ContourEntryRanking.cs @@ -107,16 +107,18 @@ internal static class ContourEntryRanking if (target != null) { // Nearest side(s) of the candidate bounding rectangle (a corner belongs to two - // sides within tolerance); count how many of them are facing sides. + // sides within tolerance, a fillet's joint within its reach of the corner it + // rounds); count how many of them are facing sides. var left = p.X - minX; var right = maxX - p.X; var bottom = p.Y - minY; var top = maxY - p.Y; var min = System.Math.Min(System.Math.Min(left, right), System.Math.Min(bottom, top)); - if (facingRight && right <= min + PostVerificationGeometry.Epsilon) facing++; - if (!facingRight && left <= min + PostVerificationGeometry.Epsilon) facing++; - if (facingTop && top <= min + PostVerificationGeometry.Epsilon) facing++; - if (!facingTop && bottom <= min + PostVerificationGeometry.Epsilon) facing++; + var near = min + PostVerificationGeometry.Epsilon + candidate.CornerReach; + if (facingRight && right <= near) facing++; + if (!facingRight && left <= near) facing++; + if (facingTop && top <= near) facing++; + if (!facingTop && bottom <= near) facing++; } var travel = (arrival != null ? arrival.Value.DistanceTo(p) : 0.0) + (target != null ? p.DistanceTo(target.Value) : 0.0); diff --git a/OpenNest.Core/CNC/CuttingPlanning/PreparedContours.cs b/OpenNest.Core/CNC/CuttingPlanning/PreparedContours.cs index 54fd0d8b..83a98797 100644 --- a/OpenNest.Core/CNC/CuttingPlanning/PreparedContours.cs +++ b/OpenNest.Core/CNC/CuttingPlanning/PreparedContours.cs @@ -602,7 +602,7 @@ public sealed class PreparedContours /// Preferred tier: convex corners, straight midpoints, tangent joints. private List PreferredCandidates(Shape shape, int contourOrdinal, CancellationToken token) => CataloguePoints(shape, token) - .Select(p => new ContourEntryCandidate(Entry(contourOrdinal, p.EntityOrdinal, p.Point), p.Kind)) + .Select(p => new ContourEntryCandidate(Entry(contourOrdinal, p.EntityOrdinal, p.Point), p.Kind, p.CornerReach)) .ToList(); /// @@ -763,12 +763,14 @@ public sealed class PreparedContours /// /// The preferred catalogue points for one contour: for each entity, its convex corner /// (end vertex, classified from the contour's own winding) and its straight-edge midpoint, - /// plus tangent line/arc joints. Reflex, cusp and collinear-split vertices contribute + /// plus tangent line/arc joints. The joints of a corner fillet (see ) + /// are that corner's convex corners. Reflex, cusp and collinear-split vertices contribute /// nothing; a single whole circle yields no points at all. /// - private List<(int EntityOrdinal, Vector Point, AutomaticEntryKind Kind)> CataloguePoints(Shape shape, CancellationToken token) + private List<(int EntityOrdinal, Vector Point, AutomaticEntryKind Kind, double CornerReach)> CataloguePoints( + Shape shape, CancellationToken token) { - var found = new List<(int, Vector, AutomaticEntryKind)>(); + var found = new List<(int, Vector, AutomaticEntryKind, double)>(); var count = shape.Entities.Count; if (count == 1 && shape.Entities[0] is Circle) { @@ -792,29 +794,65 @@ public sealed class PreparedContours switch (corner.Kind) { case ContourCuttingStrategy.CornerKind.Convex: - found.Add((i, vertex, AutomaticEntryKind.ConvexCorner)); + found.Add((i, vertex, AutomaticEntryKind.ConvexCorner, 0)); break; case ContourCuttingStrategy.CornerKind.Smooth when entity is Line && Next(i) is Arc: // A line leaving into an arc: the tangent joint. The reverse travel // order classifies the same joint from the arc, matched below. - found.Add((i, vertex, AutomaticEntryKind.TangentJoint)); + found.Add(Joint(i, vertex, (i + 1) % count)); break; // Reflex, cusp, collinear splits (smooth line→line) and arc→line joins // of a plain straight edge are not preferred automatic starts here. case ContourCuttingStrategy.CornerKind.Smooth when entity is Arc && Next(i) is Line: - found.Add((i, vertex, AutomaticEntryKind.TangentJoint)); + found.Add(Joint(i, vertex, i)); break; } } if (entity is Line line) - found.Add((i, line.MidPoint, AutomaticEntryKind.StraightMidpoint)); + found.Add((i, line.MidPoint, AutomaticEntryKind.StraightMidpoint, 0)); } return found; Entity Next(int index) => shape.Entities[(index + 1) % count]; + + (int, Vector, AutomaticEntryKind, double) Joint(int entityOrdinal, Vector vertex, int arcOrdinal) => + FilletReach(shape, arcOrdinal) is { } reach + ? (entityOrdinal, vertex, AutomaticEntryKind.ConvexCorner, reach) + : (entityOrdinal, vertex, AutomaticEntryKind.TangentJoint, 0); + } + + /// + /// How far the joints of the arc at lie from the sharp corner it + /// rounds, when it is a corner fillet: tangent to straight edges at both ends, turning less + /// than a half circle the convex way, and reaching back along each edge no further than the + /// edge is long. A fillet's joints start the cut at the corner, where the mismatch when the + /// cut closes is least seen, instead of on a straight edge. Null for any other arc. + /// + private static double? FilletReach(Shape shape, int arcOrdinal) + { + var count = shape.Entities.Count; + if (shape.Entities[arcOrdinal] is not Arc arc + || shape.Entities[(arcOrdinal + count - 1) % count] is not Line before + || shape.Entities[(arcOrdinal + 1) % count] is not Line after) + return null; + var sweep = arc.SweepAngle(); + if (sweep >= System.Math.PI - OpenNest.Math.Tolerance.Epsilon) + return null; + if (!IsSmooth(before.EndPoint, before) || !IsSmooth(arc.EndPoint(), arc)) + return null; + var winding = ContourCuttingStrategy.DetermineWinding(shape); + if (ContourCuttingStrategy.ClassifyTurn((before.EndPoint - before.StartPoint).Normalize(), + (after.EndPoint - after.StartPoint).Normalize(), winding) != ContourCuttingStrategy.CornerKind.Convex) + return null; + var reach = arc.Radius * System.Math.Tan(sweep / 2); + return reach <= System.Math.Min(before.Length, after.Length) ? reach : null; + + bool IsSmooth(Vector vertex, Entity entity) => + ContourCuttingStrategy.TryClassifyAutomaticStartCorner(shape, vertex, entity, out var corner) + && corner.Kind == ContourCuttingStrategy.CornerKind.Smooth; } /// Emits every contour once in caller order, holes before perimeter, with scribes once. diff --git a/OpenNest.Core/CNC/CuttingStrategy/ContourCuttingStrategy.cs b/OpenNest.Core/CNC/CuttingStrategy/ContourCuttingStrategy.cs index 2f4d3e46..3762aee1 100644 --- a/OpenNest.Core/CNC/CuttingStrategy/ContourCuttingStrategy.cs +++ b/OpenNest.Core/CNC/CuttingStrategy/ContourCuttingStrategy.cs @@ -867,10 +867,18 @@ namespace OpenNest.CNC.CuttingStrategy /// A turn whose offset over the tangent is within chaining tolerance is smooth, /// not a corner. /// - private static CornerKind ClassifyCorner(ContourCorner corner, RotationType winding) + private static CornerKind ClassifyCorner(ContourCorner corner, RotationType winding) => + ClassifyTurn(corner.TangentIn, corner.TangentOut, winding); + + /// + /// The corner a contour of would make turning from travel + /// direction to , classified + /// exactly as a shared vertex is (see ). + /// + internal static CornerKind ClassifyTurn(Vector tangentIn, Vector tangentOut, RotationType winding) { - var cross = corner.TangentIn.X * corner.TangentOut.Y - corner.TangentIn.Y * corner.TangentOut.X; - var dot = corner.TangentIn.DotProduct(corner.TangentOut); + var cross = tangentIn.X * tangentOut.Y - tangentIn.Y * tangentOut.X; + var dot = tangentIn.DotProduct(tangentOut); var turn = winding == RotationType.CCW ? cross : -cross; if (System.Math.Abs(turn) <= Tolerance.Epsilon) diff --git a/OpenNest.Core/CNC/DisplayPerimeterTail.cs b/OpenNest.Core/CNC/DisplayPerimeterTail.cs index e333b76b..8851648b 100644 --- a/OpenNest.Core/CNC/DisplayPerimeterTail.cs +++ b/OpenNest.Core/CNC/DisplayPerimeterTail.cs @@ -135,7 +135,7 @@ namespace OpenNest.CNC if (HasDisplayPerimeterMotion(executed)) throw new InvalidOperationException( $"{partName} has a display perimeter (a supplied blank's outline that is never cut) but no " - + "cutting plan. Run Plan Cutting before posting so only its cutouts are cut."); + + "cutting plan. Plan cutting first (Plate > Plan Cutting..., or --plan-cutting) so only its cutouts are cut."); return executed; } diff --git a/OpenNest.Core/Diagnostics/PostVerificationAnalyzer.cs b/OpenNest.Core/Diagnostics/PostVerificationAnalyzer.cs index fbc43007..1c67bc09 100644 --- a/OpenNest.Core/Diagnostics/PostVerificationAnalyzer.cs +++ b/OpenNest.Core/Diagnostics/PostVerificationAnalyzer.cs @@ -139,7 +139,7 @@ public static class PostVerificationAnalyzer // perimeter left is an unplanned blank whose outline a post would refuse. if (moves.Any(move => move.Layer == LayerType.DisplayPerimeter)) Incomplete("This part has a display perimeter (a supplied blank's outline that is never cut) " - + "but no cutting plan; posts refuse it. Run Plan Cutting so only its cutouts are cut."); + + "but no cutting plan; posts refuse it. Plan cutting first (Plate > Plan Cutting..., or --plan-cutting) so only its cutouts are cut."); if (expectsCuts && !moves.Any(move => !move.Rapid && move.Layer is LayerType.Cut or LayerType.Display && move.Curve.Length > PostVerificationGeometry.Epsilon)) diff --git a/OpenNest.Data/ClampSettings.cs b/OpenNest.Data/ClampSettings.cs index 9d57219b..776f2de2 100644 --- a/OpenNest.Data/ClampSettings.cs +++ b/OpenNest.Data/ClampSettings.cs @@ -23,9 +23,11 @@ public enum ClampSettingsStatus } /// -/// The machine's fixed edge-clamp rail, persisted to a single JSON file (by default -/// %APPDATA%\OpenNest\clamps.json). Off by default: until is set -/// with at least one center, new nests get no clamps and behave exactly as before. +/// An edge-clamp rail in given units, as a machine gives new nests (see +/// ) and as the legacy single +/// %APPDATA%\OpenNest\clamps.json held it before each machine kept its own; that file is now +/// read only to copy it onto a machine once (). Off by default: +/// until is set with at least one center, new nests get no clamps. /// Loading never throws; values are validated field by field. /// public sealed class ClampSettings diff --git a/OpenNest.Data/DrawingLibraryBrowseSession.cs b/OpenNest.Data/DrawingLibraryBrowseSession.cs index 04a6e786..8d89785c 100644 --- a/OpenNest.Data/DrawingLibraryBrowseSession.cs +++ b/OpenNest.Data/DrawingLibraryBrowseSession.cs @@ -46,7 +46,7 @@ public sealed class DrawingLibraryBrowseSession : BrowseSession PageSummary("drawings", Search.Length > 0 ? "No drawings match the search." - : IsFilteredToNest ? "No library drawings match this nest's material and thickness. Choose Show all to see every drawing." + : IsFilteredToNest ? "No library drawings match this nest's material and thickness. Tick Show all materials to see every drawing." : "No drawings in the library."); /// Lifts or restores the nest filter and returns to the first page. diff --git a/OpenNest.Data/DrawingLibraryEditSession.cs b/OpenNest.Data/DrawingLibraryEditSession.cs index 2e98628a..ba6115a5 100644 --- a/OpenNest.Data/DrawingLibraryEditSession.cs +++ b/OpenNest.Data/DrawingLibraryEditSession.cs @@ -30,7 +30,7 @@ public sealed class DrawingLibraryEditSession if (listed.Id == Guid.Empty || listed.Revision < 1) throw new ArgumentException("Choose a listed library drawing to edit.", nameof(listed)); if (listed.Archived) - throw new ArgumentException("An archived library drawing cannot be edited. Restore it first.", nameof(listed)); + throw new ArgumentException("An archived library drawing cannot be edited.", nameof(listed)); SavedBy = savedBy ?? ""; } diff --git a/OpenNest.Data/LegacyClampMigration.cs b/OpenNest.Data/LegacyClampMigration.cs new file mode 100644 index 00000000..e4a2d254 --- /dev/null +++ b/OpenNest.Data/LegacyClampMigration.cs @@ -0,0 +1,32 @@ +namespace OpenNest.Data; + +/// +/// Moves the single legacy clamps.json (or its shared copy) onto a machine once. The legacy +/// rail is copied only while no machine has clamps of its own; after that it is never read. +/// +public static class LegacyClampMigration +{ + /// + /// Whether (null when there is no legacy file) still has to be + /// copied: it lists at least one clamp and none of has clamps yet. + /// + public static bool IsNeeded(ClampSettings? legacy, IReadOnlyCollection machines) => + legacy is { ClampCount: > 0 } && machines.Count > 0 && machines.All(m => m.Clamps == null); + + /// + /// The machine that takes the legacy rail without asking: the nest defaults' machine when it + /// is on file, otherwise the only machine. Null when there are several and none is the + /// default, so the user has to choose. + /// + public static MachineConfig? Target(IReadOnlyCollection machines, Guid? defaultMachineId) => + machines.FirstOrDefault(m => m.Id == defaultMachineId) + ?? (machines.Count == 1 ? machines.First() : null); + + /// Gives the legacy rail, converted to the machine's units. + public static void Apply(ClampSettings legacy, MachineConfig machine) + { + ArgumentNullException.ThrowIfNull(legacy); + ArgumentNullException.ThrowIfNull(machine); + machine.Clamps = MachineClamps.FromSettings(legacy, machine.Units); + } +} diff --git a/OpenNest.Data/MachineClamps.cs b/OpenNest.Data/MachineClamps.cs new file mode 100644 index 00000000..806ab687 --- /dev/null +++ b/OpenNest.Data/MachineClamps.cs @@ -0,0 +1,85 @@ +namespace OpenNest.Data; + +/// +/// A machine's fixed edge-clamp rail, stored on its in the machine's +/// units. New nests assigned the machine copy it as their own rail; editing it never changes an +/// existing nest. validates the stored values field by field. +/// +public sealed class MachineClamps +{ + /// Whether new nests assigned this machine receive the rail. Default off. + public bool Enabled { get; set; } + + /// Clamp extent along its edge. + public double Width { get; set; } = ClampSettings.DefaultWidth; + + /// Clamp intrusion into the sheet from its edge. + public double Depth { get; set; } = ClampSettings.DefaultDepth; + + /// Minutes to remove one clamp and put it back after cutting; never scaled. + public double RemovalMinutes { get; set; } = ClampRail.DefaultRemovalMinutes; + + /// Origin-side clamp centers along X, measured from the plate origin. + public List Centers { get; set; } = new(); + + /// Far-side clamp centers along X, measured from the plate origin. + public List FarSideCenters { get; set; } = new(); + + /// Origin-end clamp centers along Y, measured from the plate origin. + public List OriginEndCenters { get; set; } = new(); + + /// Far-end clamp centers along Y, measured from the plate origin. + public List FarEndCenters { get; set; } = new(); + + /// The matching a machine's . + public static Units UnitsOf(UnitSystem units) => + units == UnitSystem.Millimeters ? Units.Millimeters : Units.Inches; + + /// + /// converted to a machine in , e.g. for + /// "Save as Machine Defaults" from a nest in other units or the clamps.json migration. + /// + public static MachineClamps FromSettings(ClampSettings settings, UnitSystem units) + { + ArgumentNullException.ThrowIfNull(settings); + var converted = settings.ConvertedTo(UnitsOf(units)); + return new MachineClamps + { + Enabled = converted.Enabled, + Width = converted.Width, + Depth = converted.Depth, + RemovalMinutes = converted.RemovalMinutes, + Centers = converted.Centers.ToList(), + FarSideCenters = converted.FarSideCenters.ToList(), + OriginEndCenters = converted.OriginEndCenters.ToList(), + FarEndCenters = converted.FarEndCenters.ToList(), + }; + } + + /// + /// The rail as clamp settings in the machine's . An invalid size or + /// removal time falls back to the default, and an invalid center is dropped, as when + /// reads a file. + /// + public ClampSettings ToSettings(UnitSystem units) + { + var defaults = ClampSettings.FromRail(null, UnitsOf(units), Enabled); + if (IsLength(Width) && Width > 0) + defaults.Width = Width; + if (IsLength(Depth) && Depth > 0) + defaults.Depth = Depth; + if (IsLength(RemovalMinutes) && RemovalMinutes >= 0) + defaults.RemovalMinutes = RemovalMinutes; + defaults.Centers = Valid(Centers); + defaults.FarSideCenters = Valid(FarSideCenters); + defaults.OriginEndCenters = Valid(OriginEndCenters); + defaults.FarEndCenters = Valid(FarEndCenters); + return defaults; + } + + private static double[] Valid(IEnumerable? centers) => + (centers ?? Enumerable.Empty()).Where(c => IsLength(c) && c >= 0).Distinct().Order().ToArray(); + + // Finite in either unit, so converting to an inch or millimeter nest cannot overflow. + private static bool IsLength(double value) => double.IsFinite(value) && double.IsFinite(value * 25.4); +} diff --git a/OpenNest.Data/MachineConfig.cs b/OpenNest.Data/MachineConfig.cs index 7cf1671b..3859b984 100644 --- a/OpenNest.Data/MachineConfig.cs +++ b/OpenNest.Data/MachineConfig.cs @@ -20,8 +20,18 @@ public class MachineConfig /// public SupportGridSettings? SupportGrid { get; set; } + /// + /// The edge-clamp rail new nests assigned this machine receive, in ; null + /// until set (the machine then gives nests no clamps). + /// + public MachineClamps? Clamps { get; set; } + public MotionConfig GetMotionOrPlaceholder() => Motion ?? MotionConfig.Placeholder(Units); + /// The machine's clamps in its units; off, at the default clamp size, when it has none. + public ClampSettings GetClampSettings() => + Clamps?.ToSettings(Units) ?? ClampSettings.FromRail(null, MachineClamps.UnitsOf(Units), enabled: false); + public ThicknessConfig? GetParameters(string material, double thickness) => GetParameters(material, null, thickness); diff --git a/OpenNest.Data/SharedSettings.cs b/OpenNest.Data/SharedSettings.cs index fa0e9f5f..490ebc68 100644 --- a/OpenNest.Data/SharedSettings.cs +++ b/OpenNest.Data/SharedSettings.cs @@ -40,7 +40,10 @@ public static class SharedSettingKinds /// A post processor's settings, keyed by the post's type name. public const string Post = "post"; - /// The new nests start from, under . + /// + /// The legacy new nests started from before each machine held its + /// clamps, under ; read only to copy them onto a machine once. + /// public const string Clamps = "clamps"; /// The new nests start from, under . diff --git a/OpenNest.Engine/CuttingPlanning/CuttingPlanBatch.cs b/OpenNest.Engine/CuttingPlanning/CuttingPlanBatch.cs index e0224b98..cf75f755 100644 --- a/OpenNest.Engine/CuttingPlanning/CuttingPlanBatch.cs +++ b/OpenNest.Engine/CuttingPlanning/CuttingPlanBatch.cs @@ -447,6 +447,8 @@ public sealed class CuttingPlanProposal Quadrant = source.Quadrant, PartSpacing = source.PartSpacing, EdgeSpacing = source.EdgeSpacing, + // View > Draw Support shows the proposal on the same bed. + SupportBed = source.SupportBed, }; // Machine clamps stay visible while inspecting the proposal; zones are immutable. foreach (var zone in source.ClampZones) diff --git a/OpenNest.Engine/CuttingPlanning/JointCuttingPlanSearch.cs b/OpenNest.Engine/CuttingPlanning/JointCuttingPlanSearch.cs index 782bde45..c4321d06 100644 --- a/OpenNest.Engine/CuttingPlanning/JointCuttingPlanSearch.cs +++ b/OpenNest.Engine/CuttingPlanning/JointCuttingPlanSearch.cs @@ -52,7 +52,7 @@ internal static class JointCuttingPlanSearch { var inserted = CutOffInsertion.Insert(snapshot, outcome.Order, attached, walk.CountExpansion, token); if (inserted != null) - return walk.Ready(inserted); + return walk.Ready(walk.FollowSegments(inserted)); } catch (BudgetExceededException) { @@ -196,26 +196,35 @@ internal static class JointCuttingPlanSearch } // "Cut the blocked part before every part whose cut contour its approach crossed", unless that - // would contradict an order already required. False when nothing new was learned. + // would contradict an order already required. When every such rule would (a sheet separator + // is cut after everything), the blocked part cannot come earlier, so the tool must arrive + // from beyond those parts instead: "cut the part it left from before them". False when + // nothing new was learned. private static bool Learn(Attempt attempt, HashSet[] prerequisites) { - if (attempt.Blocked is not int blocked) - return false; - var learned = false; - foreach (var crossed in attempt.Crossed.Order()) - { - if (crossed == blocked || prerequisites[crossed].Contains(blocked) || Precedes(crossed, blocked, prerequisites)) - continue; - prerequisites[crossed].Add(blocked); - learned = true; - } - return learned; + var rules = Rules(attempt, prerequisites).ToArray(); + foreach (var (first, then) in rules) + prerequisites[then].Add(first); + return rules.Length != 0; } // True when a crossing of the blocked part's approach would teach a new order rule. private static bool CanLearn(Attempt attempt, HashSet[] prerequisites) => - attempt.Blocked is int blocked && attempt.Crossed.Any(crossed => crossed != blocked - && !prerequisites[crossed].Contains(blocked) && !Precedes(crossed, blocked, prerequisites)); + Rules(attempt, prerequisites).Any(); + + // The rules Learn would add, as (cut first, cut then) pairs. + private static IEnumerable<(int First, int Then)> Rules(Attempt attempt, HashSet[] prerequisites) + { + if (attempt.Blocked is not int blocked) + return []; + var before = New(blocked); + return before.Length != 0 || attempt.LastCut?.SourceOrdinal is not int departed ? before : New(departed); + + (int, int)[] New(int first) => attempt.Crossed.Order() + .Where(crossed => crossed != blocked && crossed != first && !prerequisites[crossed].Contains(first) + && !Precedes(crossed, first, prerequisites)) + .Select(crossed => (first, crossed)).ToArray(); + } // True when 'first' must already come before 'second' through the prerequisite chain. private static bool Precedes(int first, int second, HashSet[] prerequisites) @@ -334,10 +343,10 @@ internal static class JointCuttingPlanSearch } // A cutoff is a fixed program cut the same way wherever it goes, so replanning // the parts before it can only change where its approach starts. Cutting it - // earlier never makes its own cut harder; learn that rather than stall here. + // earlier never makes its own cut harder, and a sheet separator that cannot come + // earlier needs the approach from elsewhere; learn that rather than stall here. if (prerequisites != null && sequence != null && attempt.Blocked is int blocked - && snapshot.Placements[blocked] is { IsCutOff: true, SeparatesSheet: false } - && CanLearn(attempt, prerequisites)) + && snapshot.Placements[blocked].IsCutOff && CanLearn(attempt, prerequisites)) return attempt; if (attempt.Advance(node)) progressExpansions = Expansions; @@ -523,8 +532,9 @@ internal static class JointCuttingPlanSearch CountExpansion(source); var checker = node.Checker.Copy(); if (Check(cut, cut.Execution, node.Position, checker, attempt)) - // A segment is transparent: the part after it ranks its entries and hole route - // from where the tool was before the segment, as planned without it. + // A segment is transparent to the part after it: that part ranks its outside entry + // from where the tool was before the segment, as planned without it. Its hole + // route starts where the tool is, the segment's end, as FollowSegments plans it. yield return new(new([.. node.Order, cut], cut.Execution.DeparturePoint, checker, null, node, IsSegment(cut) ? node.RoutePosition : null), cut.Execution.RapidDistanceFrom(node.Position), cut.SourceOrdinal, -1, -1); @@ -559,7 +569,7 @@ internal static class JointCuttingPlanSearch } var preference = node.Active?.Preference; if (node.Active?.Perimeter is { } outside && preference == null) - preference = PlanHoles(node.Active, outside); + preference = PlanHoles(node.Active.Source, node.Active.Boundary.Position, outside); var choices = node.Active?.Choices ?? []; var arrival = node.Active?.Arrival ?? node.Position; var before = node.Active?.Before ?? node.Checker; @@ -1216,12 +1226,13 @@ internal static class JointCuttingPlanSearch return ordered; } - private HolePreference PlanHoles(ActivePart active, ContourChoice perimeter) + // The hole route and preferred hole entries from the tool's global arrival onto the part, + // ending at the outside entry. + private HolePreference PlanHoles(FixedProgramPlacement source, Vector arrival, ContourChoice perimeter) { - var source = active.Source; var prepared = source.Prepared; var holes = Enumerable.Range(0, prepared.PerimeterOrdinal).ToArray(); - var localArrival = active.Boundary.RoutePosition - source.Location; + var localArrival = arrival - source.Location; var centres = CuttingHoleOrder.Centres(prepared, localArrival, token); var endpoint = perimeter.Point; var entries = new Dictionary(); @@ -1255,6 +1266,72 @@ internal static class JointCuttingPlanSearch return new(route, entries, pierces, endpoint); } + /// + /// The order with segments placed, where each holed part cut straight after a segment + /// takes the hole route and entries planned from the segment's end, where the tool + /// really is. The free search planned the part as if the segment were not there, from + /// where the tool was before it. The part's outside entry and the order stay, so the + /// route is still the one planned without the lines; a kept order replanned later plans + /// the same holes from the same point. A part keeps its planned holes when the new + /// route has no preferred entry for every hole or does not pass the checks. + /// + internal IReadOnlyList FollowSegments(IReadOnlyList order) + { + var followed = order.ToArray(); + var checker = new ReleasedContourState(reportMissingLeadIns: false); + var position = snapshot.StartPoint; + try + { + for (var index = 0; index < followed.Length; index++) + { + if (index > 0 && IsSegment(followed[index - 1]) + && FromSegment(followed[index], position, checker) is { } replanned) + followed[index] = replanned; + var placement = followed[index]; + checker.Check(placement.Execution, position, placement.SourceOrdinal + 1, placement.IsCutOff, + placement.FixedMotions(placement.Execution), token); + position = placement.Execution.DeparturePoint; + } + } + catch (BudgetExceededException) + { + // The plan is complete without this refinement; keep it as placed. + return order; + } + return followed; + } + + // The part re-planned from arrival with its outside entry kept, or null to keep it. + private FixedProgramPlacement FromSegment(FixedProgramPlacement placement, Vector arrival, + ReleasedContourState checker) + { + var source = snapshot.Placements[placement.SourceOrdinal]; + var prepared = source.Prepared; + if (prepared is not { HasCutPerimeter: true } || prepared.PerimeterOrdinal == 0 + || placement.ContourChoices.Count != prepared.Count + || placement.ContourChoices[^1].ContourOrdinal != prepared.PerimeterOrdinal) + return null; + var perimeter = placement.ContourChoices[^1]; + var preference = PlanHoles(source, arrival, perimeter); + if (preference.Entries.Count != prepared.PerimeterOrdinal) + return null; + var choices = preference.Route.Select(hole => preference.Entries[hole]).Append(perimeter).ToArray(); + Program program; + OwnedExecution execution; + try + { + CountExpansion(source); + program = prepared.Emit(choices); + execution = ExecutionMotionReader.Read(program, source.Location, arrival, token); + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or ArithmeticException or NotSupportedException) + { + return null; + } + return Check(source, execution, arrival, checker.Copy(), new Attempt(null), choices) + ? source.Propose(program, execution, choices, token) : null; + } + // The placements cut at a node, and the excluded ones, which count as cut throughout. private HashSet Finished(Node node) { @@ -1568,8 +1645,8 @@ internal static class JointCuttingPlanSearch ContourChoice Perimeter = null, HolePreference Preference = null); /// /// A search state; Previous links a whole-part boundary to the boundary before it. Anchor, - /// when set, is where the tool was before the cut-off segments cut last: entries and hole - /// routes rank from , every rapid is checked from Position. + /// when set, is where the tool was before the cut-off segments cut last: outside entries + /// rank from ; hole routes and every rapid start from Position. /// private sealed record Node(FixedProgramPlacement[] Order, Vector Position, ReleasedContourState Checker, ActivePart Active, Node Previous, Vector? Anchor = null) diff --git a/OpenNest.Tests/CuttingPlanning/ClampZonePreviewTests.cs b/OpenNest.Tests/CuttingPlanning/ClampZonePreviewTests.cs index 26c1de67..dd4972e8 100644 --- a/OpenNest.Tests/CuttingPlanning/ClampZonePreviewTests.cs +++ b/OpenNest.Tests/CuttingPlanning/ClampZonePreviewTests.cs @@ -19,4 +19,17 @@ public class ClampZonePreviewTests Assert.Equal(2, preview.ClampZones.Count); Assert.Null(preview.ClampRail); // a detached display copy never re-resolves } + + [Fact] + public void PreviewCarriesThePlatesSupportBed() + { + var plate = BestEffortCuttingPlanTests.Plate(BestEffortCuttingPlanTests.TouchingContours()); + plate.SupportBed = new OpenNest.Support.SupportGrid(25, 100, 2, 2, stabilityMargin: 0.1); + + var proposal = CuttingPlanBatch.Capture([plate], ExplicitContourTests.Parameters(), false).Plan(); + var preview = proposal.BuildPreview(0); + + Assert.NotNull(preview); + Assert.Same(plate.SupportBed, preview.SupportBed); + } } diff --git a/OpenNest.Tests/CuttingPlanning/ContourEntryCandidateTests.cs b/OpenNest.Tests/CuttingPlanning/ContourEntryCandidateTests.cs index ef4da05b..ea3eb3de 100644 --- a/OpenNest.Tests/CuttingPlanning/ContourEntryCandidateTests.cs +++ b/OpenNest.Tests/CuttingPlanning/ContourEntryCandidateTests.cs @@ -67,6 +67,97 @@ public class ContourEntryCandidateTests Assert.Equal(8, forward.Count); } + /// Square 0..10 whose corners are 0.5-radius fillets, counterclockwise or clockwise. + internal static Program RoundedSquare(bool clockwise) + { + var p = new Program(); + p.MoveTo(0.5, 0); + if (clockwise) + { + p.ArcTo(new Vector(0, 0.5), new Vector(0.5, 0.5), RotationType.CW); + p.LineTo(0, 9.5); + p.ArcTo(new Vector(0.5, 10), new Vector(0.5, 9.5), RotationType.CW); + p.LineTo(9.5, 10); + p.ArcTo(new Vector(10, 9.5), new Vector(9.5, 9.5), RotationType.CW); + p.LineTo(10, 0.5); + p.ArcTo(new Vector(9.5, 0), new Vector(9.5, 0.5), RotationType.CW); + p.LineTo(0.5, 0); + return p; + } + p.LineTo(9.5, 0); + p.ArcTo(new Vector(10, 0.5), new Vector(9.5, 0.5), RotationType.CCW); + p.LineTo(10, 9.5); + p.ArcTo(new Vector(9.5, 10), new Vector(9.5, 9.5), RotationType.CCW); + p.LineTo(0.5, 10); + p.ArcTo(new Vector(0, 9.5), new Vector(0.5, 9.5), RotationType.CCW); + p.LineTo(0, 0.5); + p.ArcTo(new Vector(0.5, 0), new Vector(0.5, 0.5), RotationType.CCW); + return p; + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void CornerFilletJoints_AreConvexCorners(bool clockwise) + { + var prepared = Capture(RoundedSquare(clockwise)); + + var candidates = prepared.AutomaticEntryCandidates(prepared.PerimeterOrdinal); + + // Both joints of each fillet start the cut at its corner, one radius from the sharp corner. + var corners = candidates.Where(c => c.Kind == AutomaticEntryKind.ConvexCorner).ToList(); + Assert.Equal(8, corners.Count); + Assert.All(corners, c => Assert.Equal(0.5, c.CornerReach, 9)); + Assert.Contains(corners, c => Distance(c.Choice.Point, new Vector(10, 9.5)) < 1e-6); + Assert.Contains(corners, c => Distance(c.Choice.Point, new Vector(9.5, 10)) < 1e-6); + Assert.DoesNotContain(candidates, c => c.Kind == AutomaticEntryKind.TangentJoint); + Assert.Equal(4, candidates.Count(c => c.Kind == AutomaticEntryKind.StraightMidpoint)); + Assert.All(candidates.Where(c => c.Kind == AutomaticEntryKind.StraightMidpoint), + c => Assert.Equal(0, c.CornerReach)); + } + + [Fact] + public void FilletLongerThanItsEdge_StaysATangentJoint() + { + // A 5-radius quarter arc after a 1-long bottom edge is a curve, not a rounded corner. + var p = new Program(); + p.MoveTo(0, 0); + p.LineTo(1, 0); + p.ArcTo(new Vector(6, 5), new Vector(1, 5), RotationType.CCW); + p.LineTo(6, 6); + p.LineTo(0, 6); + p.LineTo(0, 0); + var prepared = Capture(p); + + var candidates = prepared.AutomaticEntryCandidates(prepared.PerimeterOrdinal); + + Assert.Equal(2, candidates.Count(c => c.Kind == AutomaticEntryKind.TangentJoint)); + Assert.DoesNotContain(candidates, c => c.Kind == AutomaticEntryKind.ConvexCorner + && (Distance(c.Choice.Point, new Vector(1, 0)) < 1e-6 || Distance(c.Choice.Point, new Vector(6, 5)) < 1e-6)); + } + + [Fact] + public void InsideCornerFillet_StaysATangentJoint() + { + // An L whose inside corner is rounded: that fillet turns the reflex way. + var p = new Program(); + p.MoveTo(0, 0); + p.LineTo(10, 0); + p.LineTo(10, 4); + p.LineTo(5, 4); + p.ArcTo(new Vector(4, 5), new Vector(5, 5), RotationType.CW); + p.LineTo(4, 10); + p.LineTo(0, 10); + p.LineTo(0, 0); + var prepared = Capture(p); + + var candidates = prepared.AutomaticEntryCandidates(prepared.PerimeterOrdinal); + + var joints = candidates.Where(c => c.Kind == AutomaticEntryKind.TangentJoint).ToList(); + Assert.Contains(joints, c => Distance(c.Choice.Point, new Vector(5, 4)) < 1e-6); + Assert.Contains(joints, c => Distance(c.Choice.Point, new Vector(4, 5)) < 1e-6); + } + [Fact] public void TangentLineArcJoint_IsTangentJoint_NotACorner() { diff --git a/OpenNest.Tests/CuttingPlanning/ContourEntryRankingTests.cs b/OpenNest.Tests/CuttingPlanning/ContourEntryRankingTests.cs index b91440e9..739fc740 100644 --- a/OpenNest.Tests/CuttingPlanning/ContourEntryRankingTests.cs +++ b/OpenNest.Tests/CuttingPlanning/ContourEntryRankingTests.cs @@ -93,6 +93,22 @@ public class ContourEntryRankingTests Assert.True(rightMid < bottomMid); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void FilletedCorner_BeatsAFacingMidpointNearerTheRoute(bool clockwise) + { + // Travel favours the right edge's midpoint, but a long edge's middle is a last resort: + // the joints of the facing rounded corner count on both of its sides and lead. + var ranked = Catalogue(ContourEntryCandidateTests.RoundedSquare(clockwise)) + .RankTowardNextCut(new Vector(14, 6), new Vector(12, 5)).ToList(); + + Assert.Equal(AutomaticEntryKind.ConvexCorner, ranked[0].Kind); + Assert.True(At(ranked[0], 10, 9.5) || At(ranked[0], 9.5, 10)); + var rightMid = ranked.FindIndex(c => c.Kind == AutomaticEntryKind.StraightMidpoint && At(c, 10, 5)); + Assert.True(ranked.FindIndex(c => At(c, 10, 0.5)) < rightMid); + } + [Fact] public void TangentAndMidpoint_ShareARankTier() { diff --git a/OpenNest.Tests/CuttingPlanning/CutOffSegmentPlanningTests.cs b/OpenNest.Tests/CuttingPlanning/CutOffSegmentPlanningTests.cs index 714af7ee..f9144293 100644 --- a/OpenNest.Tests/CuttingPlanning/CutOffSegmentPlanningTests.cs +++ b/OpenNest.Tests/CuttingPlanning/CutOffSegmentPlanningTests.cs @@ -109,6 +109,65 @@ public class CutOffSegmentPlanningTests Assert.Equal(result.RapidDistance, kept.RapidDistance, 6); } + // A frame with two small holes on its left strip, one above the other, and a window, + // between a locked square A at the top left, cut before it, and a locked square B to its + // right, cut after it. A line through the frame's right strip stops halfway up, so its one + // segment runs from the bottom edge to just below the frame and is cut straight before it. + // Planned without the segment, from A, the frame would cut its upper hole first; the tool + // is really at the bottom, so it cuts the lower hole first instead of crossing its own + // rapid. Replanned with the order kept, the frame plans the same holes from the same point. + [Fact] + public void PartAfterSegment_PlansItsHolesFromTheSegmentsEnd() + { + var parameters = ExplicitContourTests.Parameters(); + var nest = new Nest(); + var plate = nest.CreatePlate(); + plate.Size = new Size(60, 120); + plate.Parts.Add(LockedSquare("A", new Vector(2, 42), topLeft: false)); + var frame = new Part(new Drawing("frame", Frame()), new Vector(30, 5)); + plate.Parts.Add(frame); + plate.Parts.Add(LockedSquare("B", new Vector(80, 40), topLeft: false)); + var cutOff = new CutOff(new Vector(65, 0), CutOffAxis.Vertical) { EndLimit = 25 }; + plate.CutOffs.Add(cutOff); + plate.RegenerateCutOffs(new CutOffSettings()); + PlateSequencing.PlaceCutOffs(plate, [cutOff]); + Assert.Single(CutOffSegments.Of(plate, cutOff)); + + var result = CuttingPlanService.Plan(CuttingPlanRequest.ForPlate(plate, confirmedParameters: parameters)); + + Assert.True(result.Status == CuttingPlanStatus.Ready && result.IndependentlyReplayed, Describe(result)); + var order = result.ProposedOrder.Select(o => o.SourcePart.BaseDrawing.IsCutOff ? "s" : o.SourcePart.BaseDrawing.Name); + Assert.Equal("A s frame B", string.Join(" ", order)); + var planned = result.ProposedOrder[2]; + var rapids = planned.Execution.Motions.Where(m => m.Rapid).Select(m => m.End).ToArray(); + // Into the lower hole (y 14.5 to 15.1 on the sheet), then the upper one (34.5 to 35.1). + Assert.InRange(rapids[0].Y, 14, 16); + Assert.InRange(rapids[1].Y, 34, 36); + + Assert.Equal(CuttingCommitStatus.Applied, CuttingPlanService.Apply([result]).Status); + var kept = CuttingPlanService.Plan(CuttingPlanRequest.ForPlate(plate, confirmedParameters: parameters, + preservePartOrder: true)); + Assert.True(kept.Status == CuttingPlanStatus.Ready && kept.IndependentlyReplayed, Describe(kept)); + Assert.Equal(result.RapidDistance, kept.RapidDistance, 6); + } + + // 40 x 40 with 0.6 square holes at (2.5, 9.5) and (2.5, 29.5) and an 18 x 30 window. + private static Program Frame() + { + var program = new Program(); + void Loop(params Vector[] points) + { + program.MoveTo(points[0].X, points[0].Y); + foreach (var point in points.Skip(1).Append(points[0])) + program.LineTo(point.X, point.Y); + } + Loop(new(0, 0), new(0, 40), new(40, 40), new(40, 0)); + foreach (var y in new[] { 29.5, 9.5 }) + Loop(new(2.5, y), new(3.1, y), new(3.1, y + 0.6), new(2.5, y + 0.6)); + Loop(new(12, 5), new(30, 5), new(30, 35), new(12, 35)); + return program; + } + private const double Gap = 0.25, Width = 10.6, Neck = 5.6, Height = 20, Margin = 0.25; // The slanted shoulders need more horizontal room than the gap. private const double Pitch = (Width + Neck) / 2 + 2 * Gap; diff --git a/OpenNest.Tests/CuttingPlanning/CuttingDependencyTests.cs b/OpenNest.Tests/CuttingPlanning/CuttingDependencyTests.cs index 2b99b341..35832fa6 100644 --- a/OpenNest.Tests/CuttingPlanning/CuttingDependencyTests.cs +++ b/OpenNest.Tests/CuttingPlanning/CuttingDependencyTests.cs @@ -79,6 +79,43 @@ public class CuttingDependencyTests && f.Message.Contains("before the sheet is separated")); } + // A column of two wide parts under three narrow ones, beside a sheet separator at X 12.5 + // pierced at (12.5, 0). Climbing the column ends at the top, where the straight approach to + // that pierce crosses the wide parts, and the separator cannot be cut any earlier. The search + // learns the other way round, the part the approach left from before the parts it crossed, + // and so finishes beside the pierce. It used to learn nothing and spend its whole budget. + [Fact] + public void Plan_ApproachIntoASeparatorCrossingCutParts_LearnsToLeaveFromBeyondThem() + { + var (plate, column, separator) = ColumnBesideSeparator(); + + var result = CuttingPlanService.Plan(CuttingPlanRequest.ForPlate(plate, + confirmedParameters: ExplicitContourTests.Parameters())); + + Assert.True(result.Status == CuttingPlanStatus.Ready, Describe(result)); + var order = result.ProposedOrder.Select(o => o.SourcePart).ToList(); + Assert.Same(separator, order[^1]); + Assert.Contains(order[^2], column[..2]); + Assert.True(result.Expansions < 400, Describe(result)); + } + + private static (Plate, Part[] Column, Part Separator) ColumnBesideSeparator() + { + var nest = new Nest(); + var plate = nest.CreatePlate(); + plate.Size = new Size(100, 100); + Part[] column = + [ + Rectangle(2, 2, 10, 10), Rectangle(2, 14, 10, 10), + Rectangle(2, 26, 5, 10), Rectangle(2, 38, 5, 10), Rectangle(2, 50, 5, 10), + ]; + foreach (var part in column) + plate.Parts.Add(part); + plate.CutOffs.Add(new CutOff(new Vector(12.5, 0), CutOffAxis.Vertical)); + plate.RegenerateCutOffs(new CutOffSettings()); + return (plate, column, plate.Parts.Single(p => p.BaseDrawing.IsCutOff)); + } + // The tour cuts B, then the locked rectangle A (leaving right), then the cutoff pierced at // (10, 0) below-left of A: that approach crosses A. Replanning B's entries can never fix it, // so the search learns "cutoff first" at once instead of retrying each of B's entries. diff --git a/OpenNest.Tests/Data/DrawingLibraryBrowseSessionTests.cs b/OpenNest.Tests/Data/DrawingLibraryBrowseSessionTests.cs index dcc80792..8166c30c 100644 --- a/OpenNest.Tests/Data/DrawingLibraryBrowseSessionTests.cs +++ b/OpenNest.Tests/Data/DrawingLibraryBrowseSessionTests.cs @@ -100,7 +100,7 @@ public class DrawingLibraryBrowseSessionTests } [Theory] - [InlineData(false, "", "No library drawings match this nest's material and thickness. Choose Show all to see every drawing.")] + [InlineData(false, "", "No library drawings match this nest's material and thickness. Tick Show all materials to see every drawing.")] [InlineData(true, "", "No drawings in the library.")] [InlineData(false, "no such text", "No drawings match the search.")] public async Task Summary_ExplainsAnEmptyResult(bool showAll, string search, string expected) diff --git a/OpenNest.Tests/Data/MachineClampsTests.cs b/OpenNest.Tests/Data/MachineClampsTests.cs new file mode 100644 index 00000000..7ee73984 --- /dev/null +++ b/OpenNest.Tests/Data/MachineClampsTests.cs @@ -0,0 +1,230 @@ +using OpenNest.Data; + +namespace OpenNest.Tests.Data; + +/// +/// Each machine's own clamp rail (, in the machine's units), +/// the rail new nests copy from it, and the one-time copy of the legacy clamps.json onto a machine. +/// +public class MachineClampsTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "OpenNestTests", Guid.NewGuid().ToString()); + + public MachineClampsTests() => Directory.CreateDirectory(_directory); + + public void Dispose() + { + if (Directory.Exists(_directory)) + Directory.Delete(_directory, recursive: true); + } + + private static MachineClamps Rail(bool enabled = true) => new() + { + Enabled = enabled, + Width = 1.5, + Depth = 0.625, + RemovalMinutes = 3, + Centers = new List { 6, 21, 36 }, + FarEndCenters = new List { 10 }, + }; + + private static ClampSettings Legacy(Units units = Units.Inches) => new() + { + Enabled = true, + Units = units, + Width = 2, + Depth = 0.5, + RemovalMinutes = 4, + Centers = new double[] { 12, 24 }, + }; + + [Fact] + public void SaveMachine_RoundTripsTheClamps() + { + var provider = new LocalJsonProvider(_directory); + var machine = new MachineConfig { Name = "Laser", Clamps = Rail() }; + + provider.SaveMachine(machine); + var clamps = provider.GetMachine(machine.Id)!.Clamps!; + + Assert.True(clamps.Enabled); + Assert.Equal(1.5, clamps.Width); + Assert.Equal(0.625, clamps.Depth); + Assert.Equal(3, clamps.RemovalMinutes); + Assert.Equal(new double[] { 6, 21, 36 }, clamps.Centers); + Assert.Empty(clamps.FarSideCenters); + Assert.Equal(new double[] { 10 }, clamps.FarEndCenters); + } + + [Fact] + public void MachineSavedBeforeClamps_LoadsWithoutClamps() + { + var provider = new LocalJsonProvider(_directory); + var machine = new MachineConfig { Name = "Laser" }; + provider.SaveMachine(machine); + + var loaded = provider.GetMachine(machine.Id)!; + + Assert.Null(loaded.Clamps); + Assert.Null(loaded.GetClampSettings().RailFor(Units.Inches)); + } + + [Fact] + public void MachineWithoutClamps_GivesNoRailAtTheDefaultSizeInItsUnits() + { + var machine = new MachineConfig { Units = UnitSystem.Millimeters }; + + var settings = machine.GetClampSettings(); + + Assert.False(settings.Enabled); + Assert.Equal(Units.Millimeters, settings.Units); + Assert.Equal(ClampSettings.DefaultWidth * 25.4, settings.Width, 9); + Assert.Equal(0, settings.ClampCount); + } + + [Fact] + public void DisabledClamps_GiveNewNestsNoRail() + { + var machine = new MachineConfig { Clamps = Rail(enabled: false) }; + var nest = new Nest { Units = Units.Inches }; + + machine.GetClampSettings().ApplyToNewNest(nest); + + Assert.Null(nest.PlateDefaults.ClampRail); + } + + [Fact] + public void MillimeterMachine_GivesAnInchNestItsRailConverted() + { + var machine = new MachineConfig + { + Units = UnitSystem.Millimeters, + Clamps = new MachineClamps + { + Enabled = true, + Width = 38.1, + Depth = 12.7, + RemovalMinutes = 2, + Centers = new List { 254 }, + }, + }; + var nest = new Nest { Units = Units.Inches }; + + machine.GetClampSettings().ApplyToNewNest(nest); + + var rail = nest.PlateDefaults.ClampRail!; + Assert.Equal(1.5, rail.Width, 9); + Assert.Equal(0.5, rail.Depth, 9); + Assert.Equal(2, rail.RemovalMinutes); + Assert.Equal(10, Assert.Single(rail.Clamps).Center, 9); + } + + [Fact] + public void EditingTheMachine_NeverMovesAnExistingNestsClamps() + { + var machine = new MachineConfig { Clamps = Rail() }; + var nest = new Nest { Units = Units.Inches }; + machine.GetClampSettings().ApplyToNewNest(nest); + + machine.Clamps!.Centers = new List { 50 }; + machine.Clamps.Width = 3; + + var rail = nest.PlateDefaults.ClampRail!; + Assert.Equal(1.5, rail.Width); + Assert.Equal(new double[] { 6, 21, 36 }, + rail.Clamps.Where(c => c.Edge == ClampEdge.OriginSide).Select(c => c.Center)); + } + + [Fact] + public void InvalidStoredValues_FallBackOrAreDropped() + { + var clamps = new MachineClamps + { + Enabled = true, + Width = -1, + Depth = double.NaN, + RemovalMinutes = -2, + Centers = new List { 30, -5, double.PositiveInfinity, 10, 30 }, + FarSideCenters = null!, + }; + + var settings = clamps.ToSettings(UnitSystem.Inches); + + Assert.Equal(ClampSettings.DefaultWidth, settings.Width); + Assert.Equal(ClampSettings.DefaultDepth, settings.Depth); + Assert.Equal(ClampRail.DefaultRemovalMinutes, settings.RemovalMinutes); + Assert.Equal(new double[] { 10, 30 }, settings.Centers); + Assert.Empty(settings.FarSideCenters); + } + + [Fact] + public void FromSettings_ConvertsToTheMachineUnits() + { + var clamps = MachineClamps.FromSettings(Legacy(), UnitSystem.Millimeters); + + Assert.True(clamps.Enabled); + Assert.Equal(50.8, clamps.Width, 9); + Assert.Equal(12.7, clamps.Depth, 9); + Assert.Equal(4, clamps.RemovalMinutes); + Assert.Equal(new[] { 304.8, 609.6 }, clamps.Centers.Select(c => System.Math.Round(c, 9))); + } + + [Fact] + public void Migration_IsNeededOnlyWhileNoMachineHasClamps() + { + var a = new MachineConfig { Name = "A" }; + var b = new MachineConfig { Name = "B" }; + + Assert.True(LegacyClampMigration.IsNeeded(Legacy(), new[] { a, b })); + Assert.False(LegacyClampMigration.IsNeeded(null, new[] { a, b })); + Assert.False(LegacyClampMigration.IsNeeded(new ClampSettings { Enabled = true }, new[] { a, b })); + Assert.False(LegacyClampMigration.IsNeeded(Legacy(), Array.Empty())); + + LegacyClampMigration.Apply(Legacy(), a); + + Assert.False(LegacyClampMigration.IsNeeded(Legacy(), new[] { a, b })); + } + + [Fact] + public void Migration_TargetsTheDefaultMachine() + { + var a = new MachineConfig { Name = "A" }; + var b = new MachineConfig { Name = "B" }; + + Assert.Same(b, LegacyClampMigration.Target(new[] { a, b }, b.Id)); + } + + [Fact] + public void Migration_TargetsTheOnlyMachine() + { + var only = new MachineConfig { Name = "Only" }; + + Assert.Same(only, LegacyClampMigration.Target(new[] { only }, null)); + Assert.Same(only, LegacyClampMigration.Target(new[] { only }, Guid.NewGuid())); + } + + [Fact] + public void Migration_WithSeveralMachinesAndNoDefault_LeavesTheChoiceToTheUser() + { + var machines = new[] { new MachineConfig { Name = "A" }, new MachineConfig { Name = "B" } }; + + Assert.Null(LegacyClampMigration.Target(machines, null)); + Assert.Null(LegacyClampMigration.Target(machines, Guid.NewGuid())); + } + + [Fact] + public void Migration_CopiesTheLegacyFileIntoTheMachineUnits() + { + var path = Path.Combine(_directory, "clamps.json"); + Legacy().Save(path); + var machine = new MachineConfig { Units = UnitSystem.Millimeters }; + + LegacyClampMigration.Apply(ClampSettings.Load(path), machine); + + var rail = machine.GetClampSettings().RailFor(Units.Inches)!; + Assert.Equal(2, rail.Width, 9); + Assert.Equal(4, rail.RemovalMinutes); + Assert.Equal(new[] { 12.0, 24.0 }, rail.Clamps.Select(c => System.Math.Round(c.Center, 9))); + Assert.Equal(new[] { 304.8, 609.6 }, machine.Clamps!.Centers.Select(c => System.Math.Round(c, 9))); + } +} diff --git a/OpenNest.WinForms.Tests/Controls/BendLinePlacementTests.cs b/OpenNest.WinForms.Tests/Controls/BendLinePlacementTests.cs new file mode 100644 index 00000000..a1f088cc --- /dev/null +++ b/OpenNest.WinForms.Tests/Controls/BendLinePlacementTests.cs @@ -0,0 +1,40 @@ +using OpenNest.Bending; +using OpenNest.Controls; +using OpenNest.Geometry; +using OpenNest.Math; + +namespace OpenNest.WinForms.Tests.Controls; + +/// +/// Bends are kept in the drawing's source frame while its program starts at the origin, so a +/// placed part draws them with Source.Offset removed. +/// +public class BendLinePlacementTests +{ + [Fact] + public void BendToWorld_RemovesSourceOffsetBeforePlacing() + { + var drawing = new Drawing("bent", new CNC.Program()); + drawing.Source.Offset = new Vector(100, 50); + // In the source frame the bend runs across the part at local x = 5. + var bend = new Bend { StartPoint = new Vector(105, 50), EndPoint = new Vector(105, 60) }; + var part = new Part(drawing, new Vector(10, 20)); + + Assert.Equal(new Vector(15, 20), PlateRenderer.BendToWorld(part, bend.StartPoint)); + Assert.Equal(new Vector(15, 30), PlateRenderer.BendToWorld(part, bend.EndPoint)); + } + + [Fact] + public void BendToWorld_RotatesAboutTheProgramOrigin() + { + var drawing = new Drawing("bent", new CNC.Program()); + drawing.Source.Offset = new Vector(100, 50); + var part = new Part(drawing, new Vector(10, 20)); + part.Rotate(Angle.HalfPI, part.Location); + + var world = PlateRenderer.BendToWorld(part, new Vector(105, 50)); + + Assert.Equal(10, world.X, 9); + Assert.Equal(25, world.Y, 9); + } +} diff --git a/OpenNest.WinForms.Tests/Forms/MachineClampsFormsTests.cs b/OpenNest.WinForms.Tests/Forms/MachineClampsFormsTests.cs new file mode 100644 index 00000000..96482832 --- /dev/null +++ b/OpenNest.WinForms.Tests/Forms/MachineClampsFormsTests.cs @@ -0,0 +1,110 @@ +using System.Windows.Forms; +using OpenNest.Data; +using OpenNest.Forms; + +namespace OpenNest.WinForms.Tests.Forms; + +/// +/// Machine clamps in the desktop: the Clamps tab of Machine Configuration edits a machine's rail, +/// and Nest > Clamps saves its machine defaults to the nest's machine. +/// +public class MachineClampsFormsTests +{ + [Fact] + public void ClampsTab_EditsTheMachineRail() + { + RunSta(() => + { + var directory = Path.Combine(Path.GetTempPath(), "OpenNestTests", Guid.NewGuid().ToString()); + Directory.CreateDirectory(directory); + try + { + var provider = new LocalJsonProvider(directory); + var machine = new MachineConfig { Name = "Laser" }; + provider.SaveMachine(machine); + + using var form = new MachineConfigForm(provider); + var node = Find(form, "_tree").Nodes.Cast().Single(n => n.Tag is MachineConfig); + // A hidden tree raises no AfterSelect, so show the machine as selecting it would. + typeof(MachineConfigForm) + .GetMethod("Tree_AfterSelect", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)! + .Invoke(form, new object[] { null, new TreeViewEventArgs(node) }); + var shown = (MachineConfig)node.Tag; + Assert.Null(shown.Clamps); + + var tab = All(form).Single().TabPages.Cast().Single(p => p.Text == "Clamps"); + All(tab).Single(c => c.Text == "Give new nests these clamps").Checked = true; + var add = All