From cd623ff1aa7843841c527b8435aa6737ea0e3226 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Wed, 11 Nov 2026 15:36:44 -0500 Subject: [PATCH 1/2] refactor(posts): share contour geometry between posts through Core Move the CI Fiber post's contour extraction and winding into Core as OpenNest.CNC.Posting.PostContours and ContourWinding, so every post can take sheet- or part-frame contours with the perimeter and kerf side already chosen instead of re-deriving them. CI Fiber now writes from the shared model; its golden output is unchanged. Scribe marks are never picked as the perimeter and get no kerf. A cut that resumes after suppressed moves starts a new contour where they end, so it is no longer cut as a chord across the gap. Add tests for a square with a hole in sheet coordinates, identical contours from absolute and incremental part/hole programs, rotation, and the kerf side for both windings. Co-Authored-By: Claude Opus 5.5 --- OpenNest.Core/CNC/Posting/ContourWinding.cs | 163 +++++++++++ OpenNest.Core/CNC/Posting/PostContour.cs | 59 ++++ OpenNest.Core/CNC/Posting/PostContours.cs | 162 ++++++++++ OpenNest.Tests/CNC/PostContoursTests.cs | 276 ++++++++++++++++++ .../CIFiberContourExtractor.cs | 184 ------------ .../CIFiberProgramWriter.cs | 48 +-- .../CIFiberWinding.cs | 198 ------------- docs/cincinnati-ci-fiber-post-output.md | 8 +- 8 files changed, 678 insertions(+), 420 deletions(-) create mode 100644 OpenNest.Core/CNC/Posting/ContourWinding.cs create mode 100644 OpenNest.Core/CNC/Posting/PostContour.cs create mode 100644 OpenNest.Core/CNC/Posting/PostContours.cs create mode 100644 OpenNest.Tests/CNC/PostContoursTests.cs delete mode 100644 Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberContourExtractor.cs delete mode 100644 Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberWinding.cs diff --git a/OpenNest.Core/CNC/Posting/ContourWinding.cs b/OpenNest.Core/CNC/Posting/ContourWinding.cs new file mode 100644 index 00000000..4317046d --- /dev/null +++ b/OpenNest.Core/CNC/Posting/ContourWinding.cs @@ -0,0 +1,163 @@ +using System.Collections.Generic; +using OpenNest.Geometry; + +namespace OpenNest.CNC.Posting; + +/// +/// Which posted contour is the perimeter, and which compensation side keeps the kerf in the +/// scrap. Imported drawings are wound perimeter CW and holes CCW +/// (), which puts the part right of travel and gives +/// G41 throughout; a contour wound the other way (built in code or edited by hand) needs G42. +/// Paths that enclose no area (open break cuts) get G41, a defensive default. +/// +public static class ContourWinding +{ + /// Signed shoelace area of the cut path; negative when clockwise, 0 when degenerate. + public static double SignedArea(PostContour contour) + { + var pts = SamplePoints(contour); + if (pts.Count < 3) + return 0.0; + + var sum = 0.0; + for (var i = 0; i < pts.Count; i++) + { + var a = pts[i]; + var b = pts[(i + 1) % pts.Count]; + sum += a.X * b.Y - b.X * a.Y; + } + + return sum / 2.0; + } + + /// + /// Index of the perimeter: the material contour enclosing the largest bounding box, as + /// picks it. -1 when none encloses any area. + /// + public static int PerimeterIndex(IReadOnlyList contours) + { + var best = -1; + var bestArea = 0.0; + for (var i = 0; i < contours.Count; i++) + { + if (contours[i].IsMark || !EnclosesArea(contours[i])) + continue; + + var area = BoundingBoxArea(SamplePoints(contours[i])); + if (best < 0 || area > bestArea) + { + best = i; + bestArea = area; + } + } + + return best; + } + + /// + /// (G41, part right of travel) for a CW perimeter, a CCW hole or + /// a path enclosing no area; otherwise (G42). + /// + public static KerfType CompensationSide(PostContour contour, bool isPerimeter) + { + if (!EnclosesArea(contour)) + return KerfType.Left; + + var clockwise = SignedArea(contour) < 0.0; + return clockwise == isPerimeter ? KerfType.Left : KerfType.Right; + } + + private static bool EnclosesArea(PostContour contour) => + System.Math.Abs(SignedArea(contour)) > 1e-9; + + private static double BoundingBoxArea(List pts) + { + double minX = double.MaxValue, minY = double.MaxValue; + double maxX = double.MinValue, maxY = double.MinValue; + foreach (var p in pts) + { + minX = System.Math.Min(minX, p.X); + minY = System.Math.Min(minY, p.Y); + maxX = System.Math.Max(maxX, p.X); + maxY = System.Math.Max(maxY, p.Y); + } + + return (maxX - minX) * (maxY - minY); + } + + /// + /// Ordered points along the path: the contour start, then each cut endpoint, with arc + /// interior samples at no more than 90-degree steps so full circles give a well-formed + /// polygon. Consecutive duplicates are dropped so zero-length lead-ins do not skew it. + /// + private static List SamplePoints(PostContour contour) + { + var pts = new List(); + + void Add(Vector v) + { + if (pts.Count == 0 || pts[^1].DistanceTo(v) > 1e-9) + pts.Add(v); + } + + var prev = contour.LeadIn != null ? contour.LeadIn.EndPoint : contour.Pierce; + Add(prev); + + foreach (var cut in contour.Cuts) + { + if (cut is ArcMove arc) + { + foreach (var mid in ArcSamplePoints(prev, arc)) + Add(mid); + } + Add(cut.EndPoint); + prev = cut.EndPoint; + } + + return pts; + } + + /// + /// Interior points on the arc from to its endpoint at no more than + /// ~90-degree steps. A full circle yields four, so its shoelace sign is its true winding. + /// + private static List ArcSamplePoints(Vector prev, ArcMove arc) + { + var points = new List(); + var center = arc.CenterPoint; + var radius = center.DistanceTo(arc.EndPoint); + if (radius < 1e-12) + return points; + + var a0 = System.Math.Atan2(prev.Y - center.Y, prev.X - center.X); + var a1 = System.Math.Atan2(arc.EndPoint.Y - center.Y, arc.EndPoint.X - center.X); + + var sweep = arc.Rotation == RotationType.CW ? a0 - a1 : a1 - a0; + if (sweep <= 0) + sweep += 2.0 * System.Math.PI; + + // Full circle (start == end) reads as zero sweep above. + if ( + sweep < 1e-9 + && System.Math.Abs(prev.X - arc.EndPoint.X) < 1e-9 + && System.Math.Abs(prev.Y - arc.EndPoint.Y) < 1e-9 + ) + sweep = 2.0 * System.Math.PI; + + var direction = arc.Rotation == RotationType.CW ? -1.0 : 1.0; + var steps = System.Math.Max(1, (int)System.Math.Ceiling(sweep / (System.Math.PI / 2.0))); + + for (var k = 1; k <= steps; k++) + { + var angle = a0 + direction * sweep * k / (steps + 1); + points.Add( + new Vector( + center.X + radius * System.Math.Cos(angle), + center.Y + radius * System.Math.Sin(angle) + ) + ); + } + + return points; + } +} diff --git a/OpenNest.Core/CNC/Posting/PostContour.cs b/OpenNest.Core/CNC/Posting/PostContour.cs new file mode 100644 index 00000000..9a112348 --- /dev/null +++ b/OpenNest.Core/CNC/Posting/PostContour.cs @@ -0,0 +1,59 @@ +using System.Collections.Generic; +using OpenNest.Geometry; + +namespace OpenNest.CNC.Posting; + +/// +/// One contour of a posted part: pierce, lead-in and cut path in a single absolute frame +/// (sheet coordinates from ). Arc moves keep their +/// absolute centres; each post formats I/J its own way. +/// +public sealed class PostContour +{ + /// Pierce point: the rapid target. + public Vector Pierce { get; set; } + + /// + /// First lead-in move, ending on the contour, or null when the contour starts cutting at + /// the pierce. + /// + public Motion LeadIn { get; set; } + + /// Lead-in moves after the first (e.g. the arc after a clean-hole line). + public List LeadInExtra { get; } = new(); + + /// Moves made with the cut layer on: cut, lead-out, display and scribe. + public List Cuts { get; } = new(); + + /// + /// Head-height lock changes in a cut-off's overcut: each comes before the cut at + /// Before (.Count: after the last cut), locking when Lock. + /// + public List<(int Before, bool Lock)> HeadLocks { get; } = new(); + + /// True for the part's outside edge; false for holes, marks and cut-offs. + public bool IsPerimeter { get; set; } + + /// + /// The compensation that keeps the kerf in the scrap: (G41) + /// leaves the part right of travel, (G42) left of it. + /// for marks and cut-offs, which have no inside. + /// + public KerfType Kerf { get; set; } + + /// True when every cut is on the scribe layer: a mark, not material. + public bool IsMark + { + get + { + if (Cuts.Count == 0) + return false; + foreach (var cut in Cuts) + { + if (PostContours.LayerOf(cut) != LayerType.Scribe) + return false; + } + return true; + } + } +} diff --git a/OpenNest.Core/CNC/Posting/PostContours.cs b/OpenNest.Core/CNC/Posting/PostContours.cs new file mode 100644 index 00000000..ac85ddd0 --- /dev/null +++ b/OpenNest.Core/CNC/Posting/PostContours.cs @@ -0,0 +1,162 @@ +using System; +using System.Collections.Generic; +using OpenNest.Geometry; + +namespace OpenNest.CNC.Posting; + +/// +/// Reduces a part program to the contours a post writes: hole calls and incremental programs +/// flattened to one absolute frame, each contour split into pierce, lead-in and cuts, the +/// perimeter picked out and the kerf side chosen. Posts format these; they do not redo the +/// geometry. Caller programs are never modified. +/// +public static class PostContours +{ + /// + /// The part's contours in sheet coordinates. A display perimeter's tail is never cut and an + /// unplanned one is refused (). Cut-off contours + /// are open lines on the beam centreline: no perimeter and no kerf. + /// + public static List Extract(Part part) + { + if (part == null) + throw new ArgumentNullException(nameof(part)); + + var program = DisplayPerimeterTail.ForPosting(part.Program, DisplayPerimeterTail.PartName(part)); + var contours = Extract(program, part.Location); + if (part.BaseDrawing?.IsCutOff == true) + { + foreach (var contour in contours) + { + contour.IsPerimeter = false; + contour.Kerf = KerfType.None; + } + } + return contours; + } + + /// + /// The program's contours with added to every point: the part + /// location for sheet coordinates, for the part's own frame. + /// + public static List Extract(Program program, Vector origin) + { + var contours = new List(); + Flatten(program, origin, contours); + Classify(contours); + return contours; + } + + /// Picks the perimeter (marks excluded) and each contour's kerf side. + private static void Classify(List contours) + { + var perimeter = ContourWinding.PerimeterIndex(contours); + for (var i = 0; i < contours.Count; i++) + { + var contour = contours[i]; + contour.IsPerimeter = i == perimeter; + contour.Kerf = contour.IsMark + ? KerfType.None + : ContourWinding.CompensationSide(contour, contour.IsPerimeter); + } + } + + /// + /// Walks one program whose coordinates are relative to ; hole calls + /// recurse with their offset added. A contour starts at each rapid. Moves before the first + /// rapid start at the frame origin, where an absolute program begins. A cut after a run of + /// suppressed moves starts a new contour pierced where the run ends, so the gap is crossed + /// with the beam off rather than cut as a chord. + /// + private static void Flatten(Program program, Vector origin, List contours) + { + if (program == null) + return; + + var codes = program.Codes; + if (program.Mode == Mode.Incremental) + { + var clone = (Program)program.Clone(); + clone.Mode = Mode.Absolute; + codes = clone.Codes; + } + + PostContour current = null; + Vector? resumeAt = null; + + void Flush() + { + if (current != null && (current.LeadIn != null || current.Cuts.Count > 0)) + contours.Add(current); + current = null; + } + + foreach (var code in codes) + { + if (code is Motion { Suppressed: true } suppressed) + { + resumeAt = suppressed.EndPoint; + continue; + } + + if (HeadHeightLock.IsLock(code) || HeadHeightLock.IsUnlock(code)) + { + current ??= new PostContour { Pierce = origin }; + current.HeadLocks.Add((current.Cuts.Count, HeadHeightLock.IsLock(code))); + continue; + } + + switch (code) + { + case RapidMove rapid: + Flush(); + resumeAt = null; + current = new PostContour { Pierce = rapid.EndPoint + origin }; + break; + + case SubProgramCall call: + // A hole call is its own contour. + Flush(); + resumeAt = null; + Flatten(call.Program, origin + call.Offset, contours); + break; + + case Motion motion: + if (resumeAt.HasValue) + { + Flush(); + current = new PostContour { Pierce = resumeAt.Value + origin }; + resumeAt = null; + } + current ??= new PostContour { Pierce = origin }; + + var absolute = (Motion)motion.Clone(); + absolute.Offset(origin); + + if (LayerOf(motion) == LayerType.Leadin) + { + if (current.LeadIn == null) + current.LeadIn = absolute; + else + current.LeadInExtra.Add(absolute); + } + else + { + // Contour moves are tagged Display by default and still cut. + current.Cuts.Add(absolute); + } + break; + } + } + + Flush(); + } + + internal static LayerType LayerOf(Motion motion) => + motion switch + { + LinearMove linear => linear.Layer, + ArcMove arc => arc.Layer, + _ => LayerType.Cut, + }; +} diff --git a/OpenNest.Tests/CNC/PostContoursTests.cs b/OpenNest.Tests/CNC/PostContoursTests.cs new file mode 100644 index 00000000..615a9667 --- /dev/null +++ b/OpenNest.Tests/CNC/PostContoursTests.cs @@ -0,0 +1,276 @@ +using OpenNest.CNC; +using OpenNest.CNC.Posting; +using OpenNest.Geometry; + +namespace OpenNest.Tests.CNC; + +/// +/// The geometry every post writes from: a square with a hole flattened to sheet coordinates, +/// the same contours whichever mode the part and hole programs are stored in, and a kerf side +/// that keeps the part out of the kerf. +/// +public class PostContoursTests +{ + private static readonly Vector Location = new(1, 2); + + /// + /// A 10x10 square cut CW from (0,0) after a linear lead-in, and a radius-0.5 hole at (5,5) + /// cut CCW as a hole call, the way the cutting strategy writes them. Built absolute, then + /// switched to the requested modes. + /// + private static Program SquareWithHole(Mode partMode = Mode.Absolute, Mode holeMode = Mode.Incremental, + bool reversed = false) + { + var holeRotation = reversed ? RotationType.CW : RotationType.CCW; + var hole = new Program(Mode.Absolute); + hole.Codes.Add(new RapidMove(new Vector(0, -0.6))); + hole.Codes.Add(new LinearMove(new Vector(0, -0.5)) { Layer = LayerType.Leadin }); + hole.Codes.Add(new ArcMove(new Vector(0, -0.5), Vector.Zero, holeRotation) { Layer = LayerType.Cut }); + hole.Mode = holeMode; + + var pgm = new Program(Mode.Absolute); + pgm.Codes.Add(new SubProgramCall { Id = 1, Program = hole, Offset = new Vector(5, 5) }); + pgm.Codes.Add(new RapidMove(new Vector(0, -0.5))); + pgm.Codes.Add(new LinearMove(new Vector(0, 0)) { Layer = LayerType.Leadin }); + var corners = reversed + ? new[] { new Vector(10, 0), new Vector(10, 10), new Vector(0, 10), Vector.Zero } + : new[] { new Vector(0, 10), new Vector(10, 10), new Vector(10, 0), Vector.Zero }; + foreach (var corner in corners) + pgm.Codes.Add(new LinearMove(corner) { Layer = LayerType.Cut }); + pgm.Mode = partMode; + return pgm; + } + + private static Part Place(Program program) => new(new Drawing("square-hole", program), Location); + + [Fact] + public void SquareWithHole_PostsInSheetCoordinates() + { + var contours = PostContours.Extract(Place(SquareWithHole())); + + Assert.Equal(2, contours.Count); + + // The hole: part location + call offset + hole-local points. + var hole = contours[0]; + Assert.False(hole.IsPerimeter); + AssertPoint(new Vector(6, 6.4), hole.Pierce); + AssertPoint(new Vector(6, 6.5), hole.LeadIn.EndPoint); + var arc = Assert.IsType(Assert.Single(hole.Cuts)); + AssertPoint(new Vector(6, 6.5), arc.EndPoint); + AssertPoint(new Vector(6, 7), arc.CenterPoint); + Assert.Equal(RotationType.CCW, arc.Rotation); + + var perimeter = contours[1]; + Assert.True(perimeter.IsPerimeter); + AssertPoint(new Vector(1, 1.5), perimeter.Pierce); + AssertPoint(new Vector(1, 2), perimeter.LeadIn.EndPoint); + Assert.Equal( + new[] { new Vector(1, 12), new Vector(11, 12), new Vector(11, 2), new Vector(1, 2) }, + perimeter.Cuts.Select(c => Round(c.EndPoint))); + } + + [Theory] + [InlineData(Mode.Absolute, Mode.Absolute)] + [InlineData(Mode.Absolute, Mode.Incremental)] + [InlineData(Mode.Incremental, Mode.Absolute)] + [InlineData(Mode.Incremental, Mode.Incremental)] + public void AbsoluteAndIncrementalPrograms_PostTheSameContours(Mode partMode, Mode holeMode) + { + var expected = PostContours.Extract(Place(SquareWithHole(Mode.Absolute, Mode.Absolute))); + var program = SquareWithHole(partMode, holeMode); + + var actual = PostContours.Extract(Place(program)); + + AssertSameContours(expected, actual); + Assert.Equal(partMode, program.Mode); + } + + [Fact] + public void RotatedPart_RotatesEveryPointAndKeepsTheKerfSide() + { + var expected = PostContours.Extract(Place(SquareWithHole())); + var part = Place(SquareWithHole()); + part.Rotate(OpenNest.Math.Angle.ToRadians(90)); + + var actual = PostContours.Extract(part); + + // A 90-degree CCW turn about the origin: (x, y) -> (-y, x). + static Vector Turn(Vector v) => new(-v.Y, v.X); + Assert.Equal(expected.Count, actual.Count); + for (var i = 0; i < expected.Count; i++) + { + AssertPoint(Turn(expected[i].Pierce), actual[i].Pierce); + AssertPoint(Turn(expected[i].LeadIn.EndPoint), actual[i].LeadIn.EndPoint); + Assert.Equal(expected[i].Cuts.Count, actual[i].Cuts.Count); + for (var c = 0; c < expected[i].Cuts.Count; c++) + AssertPoint(Turn(expected[i].Cuts[c].EndPoint), actual[i].Cuts[c].EndPoint); + Assert.Equal(expected[i].Kerf, actual[i].Kerf); + Assert.Equal(expected[i].IsPerimeter, actual[i].IsPerimeter); + } + } + + [Theory] + [InlineData(false, KerfType.Left)] + [InlineData(true, KerfType.Right)] + public void KerfSide_KeepsThePartOutOfTheKerf(bool reversed, KerfType expected) + { + var contours = PostContours.Extract(Place(SquareWithHole(reversed: reversed))); + + Assert.Equal(2, contours.Count); + foreach (var contour in contours) + { + Assert.Equal(expected, contour.Kerf); + AssertPartOnCompensatedSide(contour); + } + } + + [Fact] + public void PartFrame_LeavesThePartLocationOut() + { + var sheet = PostContours.Extract(Place(SquareWithHole())); + var local = PostContours.Extract(SquareWithHole(), Vector.Zero); + + Assert.Equal(sheet.Count, local.Count); + for (var i = 0; i < sheet.Count; i++) + { + AssertPoint(sheet[i].Pierce - Location, local[i].Pierce); + for (var c = 0; c < sheet[i].Cuts.Count; c++) + AssertPoint(sheet[i].Cuts[c].EndPoint - Location, local[i].Cuts[c].EndPoint); + } + } + + [Fact] + public void SuppressedSide_IsCrossedWithTheBeamOffNotCutAsAChord() + { + var pgm = new Program(Mode.Absolute); + pgm.Codes.Add(new RapidMove(new Vector(0, -0.5))); + pgm.Codes.Add(new LinearMove(new Vector(0, 0)) { Layer = LayerType.Leadin }); + pgm.Codes.Add(new LinearMove(new Vector(0, 10))); + pgm.Codes.Add(new LinearMove(new Vector(10, 10)) { Suppressed = true }); + pgm.Codes.Add(new LinearMove(new Vector(10, 0))); + pgm.Codes.Add(new LinearMove(new Vector(0, 0))); + + var contours = PostContours.Extract(pgm, Vector.Zero); + + Assert.Equal(2, contours.Count); + Assert.Equal(new[] { new Vector(0, 10) }, contours[0].Cuts.Select(c => Round(c.EndPoint))); + AssertPoint(new Vector(10, 10), contours[1].Pierce); + Assert.Equal( + new[] { new Vector(10, 0), new Vector(0, 0) }, + contours[1].Cuts.Select(c => Round(c.EndPoint))); + } + + [Fact] + public void ScribeMark_IsNeverThePerimeterAndHasNoKerf() + { + var pgm = SquareWithHole(); + // A mark wider than the part. + pgm.Codes.Add(new RapidMove(new Vector(-5, -5))); + pgm.Codes.Add(new LinearMove(new Vector(20, -5)) { Layer = LayerType.Scribe }); + pgm.Codes.Add(new LinearMove(new Vector(20, 20)) { Layer = LayerType.Scribe }); + pgm.Codes.Add(new LinearMove(new Vector(-5, -5)) { Layer = LayerType.Scribe }); + + var contours = PostContours.Extract(pgm, Vector.Zero); + + var mark = Assert.Single(contours, c => c.IsMark); + Assert.False(mark.IsPerimeter); + Assert.Equal(KerfType.None, mark.Kerf); + Assert.True(contours[1].IsPerimeter); + } + + [Fact] + public void CutOff_HasNoPerimeterOrKerf() + { + var plate = new Plate(60, 120); + var cutOff = new CutOff(new Vector(20, 0), CutOffAxis.Vertical); + cutOff.Regenerate(plate, new CutOffSettings()); + + var contours = PostContours.Extract(new Part(cutOff.Drawing, Vector.Zero)); + + Assert.NotEmpty(contours); + Assert.All(contours, c => + { + Assert.False(c.IsPerimeter); + Assert.Equal(KerfType.None, c.Kerf); + }); + } + + [Fact] + public void Extract_LeavesThePartProgramUnchanged() + { + var program = SquareWithHole(Mode.Incremental, Mode.Incremental); + var hole = ((SubProgramCall)program.Codes[0]).Program; + var before = program.Codes.Select(c => c.ToString()).ToList(); + + PostContours.Extract(Place(program)); + + Assert.Equal(Mode.Incremental, program.Mode); + Assert.Equal(Mode.Incremental, hole.Mode); + Assert.Equal(before, program.Codes.Select(c => c.ToString())); + } + + /// + /// On the first cut (mid-line, away from corners), the point just right of travel is in the + /// part for G41 and the point just left of it is in the part for G42; the other side is the + /// kerf's. + /// + private static void AssertPartOnCompensatedSide(PostContour contour) + { + var from = contour.LeadIn.EndPoint; + var cut = contour.Cuts[0]; + var start = cut is ArcMove ? from : (from + cut.EndPoint) * 0.5; + var travel = cut is ArcMove arc + ? Tangent(from, arc) + : cut.EndPoint - from; + var length = System.Math.Sqrt(travel.X * travel.X + travel.Y * travel.Y); + var right = new Vector(travel.Y / length, -travel.X / length); + var partSide = contour.Kerf == KerfType.Left ? right : new Vector(-right.X, -right.Y); + + Assert.True(InPart(start + partSide * 0.01), $"Part is not on the compensated side at {start}"); + Assert.False(InPart(start - partSide * 0.01), $"Kerf side is in the part at {start}"); + } + + private static Vector Tangent(Vector start, ArcMove arc) + { + var radial = start - arc.CenterPoint; + return arc.Rotation == RotationType.CCW + ? new Vector(-radial.Y, radial.X) + : new Vector(radial.Y, -radial.X); + } + + private static bool InPart(Vector p) => + p.X > Location.X && p.X < Location.X + 10 + && p.Y > Location.Y && p.Y < Location.Y + 10 + && p.DistanceTo(Location + new Vector(5, 5)) > 0.5; + + private static void AssertSameContours(IReadOnlyList expected, IReadOnlyList actual) + { + Assert.Equal(expected.Count, actual.Count); + for (var i = 0; i < expected.Count; i++) + { + AssertPoint(expected[i].Pierce, actual[i].Pierce); + AssertPoint(expected[i].LeadIn.EndPoint, actual[i].LeadIn.EndPoint); + Assert.Equal(expected[i].Cuts.Count, actual[i].Cuts.Count); + for (var c = 0; c < expected[i].Cuts.Count; c++) + { + var want = expected[i].Cuts[c]; + var got = actual[i].Cuts[c]; + Assert.Equal(want.GetType(), got.GetType()); + AssertPoint(want.EndPoint, got.EndPoint); + if (want is ArcMove wantArc) + { + var gotArc = (ArcMove)got; + AssertPoint(wantArc.CenterPoint, gotArc.CenterPoint); + Assert.Equal(wantArc.Rotation, gotArc.Rotation); + } + } + Assert.Equal(expected[i].IsPerimeter, actual[i].IsPerimeter); + Assert.Equal(expected[i].Kerf, actual[i].Kerf); + } + } + + private static void AssertPoint(Vector expected, Vector actual) => + Assert.True(expected.DistanceTo(actual) < 1e-9, $"Expected {expected}, got {actual}"); + + private static Vector Round(Vector v) => new(System.Math.Round(v.X, 9), System.Math.Round(v.Y, 9)); +} diff --git a/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberContourExtractor.cs b/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberContourExtractor.cs deleted file mode 100644 index ee1a27b2..00000000 --- a/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberContourExtractor.cs +++ /dev/null @@ -1,184 +0,0 @@ -using System; -using System.Collections.Generic; -using OpenNest.CNC; -using OpenNest.Geometry; - -namespace OpenNest.Posts.CincinnatiCIFiber -{ - /// - /// One contour (pierce + lead-in + cut path) reduced to sheet-absolute - /// moves, ready to emit as a TF5200 N-label block. - /// - public sealed class CIFiberContour - { - /// Pierce point (sheet-absolute) — rapid target. - public Vector Pierce { get; set; } - - /// - /// Lead-in move to the contour start (sheet-absolute endpoint), or - /// null when the contour begins cutting immediately at the pierce. - /// Per TF5200 §13.2.4.1 the first motion block after G41/G42 selection - /// must be LINEAR, so callers must reject contours whose lead-in is an - /// arc unless the config tolerates it. - /// - public Motion LeadIn { get; set; } - - /// - /// Additional lead-in layer moves after the first (e.g. the arc that - /// follows CleanHoleLeadIn's line). Emitted before the cut layer turns - /// on, like the sample's lead block. - /// - public List LeadInExtra { get; } = new(); - - /// Cutting moves (sheet-absolute) executed after the cut layer turns on. - public List Cuts { get; } = new(); - - /// True when the contour is an external perimeter (exterior). - public bool IsExterior { get; set; } - - /// - /// Head-height lock changes in a cut-off's overcut: each is written before the cut at - /// Before (.Count: after the last cut), locking when - /// Lock is true and unlocking otherwise. - /// - public List<(int Before, bool Lock)> HeadLocks { get; } = new(); - } - - /// - /// Extracts cut contours for one part in sheet coordinates. - /// Circular holes arrive as s in an incremental - /// hole-local program; they are flattened here to sheet-absolute moves the - /// same way walks them for HPGL output. - /// Moves with are skipped. - /// - public static class CIFiberContourExtractor - { - public static List Extract(Part part) - { - if (part == null) - throw new ArgumentNullException(nameof(part)); - - var contours = new List(); - // A display perimeter's tail is never cut; an unplanned one is refused. - var program = DisplayPerimeterTail.ForPosting(part.Program, DisplayPerimeterTail.PartName(part)); - Flatten(program, part.Location, Vector.Zero, contours); - return contours; - } - - /// - /// Walk one program whose coordinates are relative to (partLocation + - /// callOffset). Sub-program calls recurse with the extra offset. - /// A contour starts at each rapid move; moves before the first rapid - /// form a contour whose pierce is the last move's endpoint (closed-loop - /// continuation), matching FeatureUtils' synthetic-rapid convention. - /// - private static void Flatten( - Program program, - Vector partLocation, - Vector subOffset, - List contours - ) - { - if (program == null) - return; - - var origin = partLocation + subOffset; - - // Work on a clone when conversion is needed so caller programs are - // never mutated (the CI sample inlines absolute moves). - var codes = program.Codes; - if (program.Mode == Mode.Incremental) - { - var clone = (Program)program.Clone(); - clone.Mode = Mode.Absolute; - codes = clone.Codes; - } - - CIFiberContour current = null; - - void Flush() - { - if (current != null && (current.LeadIn != null || current.Cuts.Count > 0)) - contours.Add(current); - current = null; - } - - foreach (var code in codes) - { - if (code is Motion suppressed && suppressed.Suppressed) - continue; - - if (HeadHeightLock.IsLock(code) || HeadHeightLock.IsUnlock(code)) - { - current ??= new CIFiberContour { Pierce = origin }; - current.HeadLocks.Add((current.Cuts.Count, HeadHeightLock.IsLock(code))); - continue; - } - - switch (code) - { - case RapidMove rapid: - Flush(); - current = new CIFiberContour { Pierce = rapid.EndPoint + origin }; - break; - - case SubProgramCall call: - // A hole call is its own contour: flatten into a temp - // list, then merge as one contour anchored at the call - // offset. - Flush(); - var sub = new List(); - Flatten(call.Program, partLocation, subOffset + call.Offset, sub); - contours.AddRange(sub); - break; - - case Motion motion: - if (current == null) - { - // Contour with no explicit rapid (program starts - // mid-contour): in absolute mode the implicit - // start position is the frame origin, which is the - // closure point of a closed contour = the pierce. - current = new CIFiberContour { Pierce = origin }; - } - - var absolute = (Motion)motion.Clone(); - absolute.Offset(origin); - - var layer = LayerOf(motion); - if (layer == LayerType.Leadin) - { - // First lead-in move opens the lead block; further - // lead-in moves (CleanHole line+arc) extend it. - if (current.LeadIn == null) - current.LeadIn = absolute; - else - current.LeadInExtra.Add(absolute); - } - else - { - // Cut, Leadout and Display all cut: OpenNest tags - // contour moves Display by default (see - // ContourCuttingStrategy.ConvertShapeToMoves), - // only Scribe is reliably a mark. Scribe contours - // are dropped by the writer when SkipScribe is on. - current.Cuts.Add(absolute); - } - break; - } - } - - Flush(); - } - - private static LayerType LayerOf(Motion motion) - { - return motion switch - { - LinearMove l => l.Layer, - ArcMove a => a.Layer, - _ => LayerType.Cut, - }; - } - } -} diff --git a/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberProgramWriter.cs b/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberProgramWriter.cs index 9072b9c0..00ac9f38 100644 --- a/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberProgramWriter.cs +++ b/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberProgramWriter.cs @@ -5,6 +5,7 @@ using System.IO; using System.Linq; using OpenNest; using OpenNest.CNC; +using OpenNest.CNC.Posting; using OpenNest.Geometry; namespace OpenNest.Posts.CincinnatiCIFiber @@ -220,26 +221,25 @@ namespace OpenNest.Posts.CincinnatiCIFiber CIFiberFormatter.Line(w, $"V.E.R4={partNumber}"); - var contours = CIFiberContourExtractor.Extract(part); + var contours = PostContours.Extract(part); if (_config.SkipScribe) - contours = contours.Where(c => !IsScribeContour(c)).ToList(); + contours = contours.Where(c => !c.IsMark).ToList(); var isCutOff = part.BaseDrawing.IsCutOff; - var perimeter = CIFiberWinding.PerimeterIndex(contours); - for (var i = 0; i < contours.Count; i++) + foreach (var contour in contours) { contourNumber++; if (isCutOff) - WriteCutOffContour(contours[i], contourNumber, w); + WriteCutOffContour(contour, contourNumber, w); else - WriteContour(contours[i], contours[i].IsExterior || i == perimeter, contourNumber, w); + WriteContour(contour, contourNumber, w); } CIFiberFormatter.Line(w, "( PART END )"); return contourNumber; } - private void WriteContour(CIFiberContour contour, bool isExterior, int contourNumber, TextWriter w) + private void WriteContour(PostContour contour, int contourNumber, TextWriter w) { CIFiberFormatter.Line(w, $"N{contourNumber}:"); CIFiberFormatter.Line(w, SkippableLine(_config.LayerCancel)); @@ -263,16 +263,13 @@ namespace OpenNest.Posts.CincinnatiCIFiber CIFiberFormatter.Line( w, SkippableLine( - isExterior ? _config.LayerExteriorLeadin : _config.LayerInteriorLeadin + contour.IsPerimeter ? _config.LayerExteriorLeadin : _config.LayerInteriorLeadin ) ); // G41 leaves the product right of travel, G42 left (Cincinnati CNC - // handbook). Pick the side that puts the kerf in the scrap for the - // way this contour actually runs. - CIFiberFormatter.Line( - w, - CIFiberWinding.CompensatesLeft(contour, isExterior) ? "G41" : "G42" - ); + // handbook); the contour's kerf side puts the kerf in the scrap. A + // posted scribe mark has none and keeps G41. + CIFiberFormatter.Line(w, contour.Kerf == KerfType.Right ? "G42" : "G41"); var prev = contour.LeadIn.EndPoint; CIFiberFormatter.Line( @@ -306,7 +303,7 @@ namespace OpenNest.Posts.CincinnatiCIFiber /// and the §13.2.4.1 linear-lead-in rule does not apply. The exterior /// lead layer still runs so the pierce sequence matches a perimeter. /// - private void WriteCutOffContour(CIFiberContour contour, int contourNumber, TextWriter w) + private void WriteCutOffContour(PostContour contour, int contourNumber, TextWriter w) { CIFiberFormatter.Line(w, $"N{contourNumber}:"); CIFiberFormatter.Line(w, SkippableLine(_config.LayerCancel)); @@ -353,27 +350,6 @@ namespace OpenNest.Posts.CincinnatiCIFiber return name; } - private static bool IsScribeContour(CIFiberContour contour) - { - var hasAny = false; - foreach (var cut in contour.Cuts) - { - var layer = LayerOf(cut); - if (layer != LayerType.Scribe) - return false; - hasAny = true; - } - return hasAny; - } - - private static LayerType LayerOf(Motion motion) => - motion switch - { - LinearMove l => l.Layer, - ArcMove a => a.Layer, - _ => LayerType.Cut, - }; - private string Fmt(double value) => _fmt.Coord(value); /// diff --git a/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberWinding.cs b/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberWinding.cs deleted file mode 100644 index ef6125ac..00000000 --- a/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberWinding.cs +++ /dev/null @@ -1,198 +0,0 @@ -using System; -using System.Collections.Generic; -using OpenNest.CNC; -using OpenNest.Geometry; - -namespace OpenNest.Posts.CincinnatiCIFiber -{ - /// - /// Works out, from a part's flattened contours, which one is the perimeter - /// (L4 lead-in macro, the rest are holes on L2) and which compensation - /// side keeps the kerf in the scrap. - /// - /// G41 leaves the product right of travel. Imported drawings are wound - /// perimeter CW and holes CCW (ShapeProfile.NormalizeWinding), which puts - /// the part on the right and gives G41 throughout; a drawing that reaches - /// the post wound the other way (built in code or edited by hand) needs G42. - /// Paths that enclose no area (open break cuts) count as holes with G41, - /// a defensive default. - /// - public static class CIFiberWinding - { - /// - /// Signed shoelace area of the contour path (arcs sampled at their - /// arc-mid point). 0 for degenerate paths. - /// - public static double SignedArea(CIFiberContour contour) - { - var pts = SamplePoints(contour); - if (pts.Count < 3) - return 0.0; - - var sum = 0.0; - for (var i = 0; i < pts.Count; i++) - { - var a = pts[i]; - var b = pts[(i + 1) % pts.Count]; - sum += a.X * b.Y - b.X * a.Y; - } - - return sum / 2.0; - } - - /// - /// Index of the part's perimeter: the contour enclosing the largest - /// bounding box, as ShapeProfile picks it. -1 when no contour encloses - /// any area. - /// - public static int PerimeterIndex(IReadOnlyList contours) - { - var best = -1; - var bestArea = 0.0; - for (var i = 0; i < contours.Count; i++) - { - if (!EnclosesArea(contours[i])) - continue; - - var area = BoundingBoxArea(SamplePoints(contours[i])); - if (best < 0 || area > bestArea) - { - best = i; - bestArea = area; - } - } - - return best; - } - - /// - /// True when G41 (product right of travel) keeps the kerf in the scrap: - /// a CW perimeter or a CCW hole. False calls for G42. - /// - public static bool CompensatesLeft(CIFiberContour contour, bool isPerimeter) - { - if (!EnclosesArea(contour)) - return true; - - var clockwise = SignedArea(contour) < 0.0; - return clockwise == isPerimeter; - } - - private static bool EnclosesArea(CIFiberContour contour) => - System.Math.Abs(SignedArea(contour)) > 1e-9; - - private static double BoundingBoxArea(List pts) - { - double minX = double.MaxValue, minY = double.MaxValue; - double maxX = double.MinValue, maxY = double.MinValue; - foreach (var p in pts) - { - minX = System.Math.Min(minX, p.X); - minY = System.Math.Min(minY, p.Y); - maxX = System.Math.Max(maxX, p.X); - maxY = System.Math.Max(maxY, p.Y); - } - - return (maxX - minX) * (maxY - minY); - } - - /// True when the cut path returns to its start point. - public static bool IsClosed(CIFiberContour contour, double tolerance = 1e-6) - { - var pts = SamplePoints(contour); - if (pts.Count < 3) - return false; - - return pts[0].DistanceTo(pts[^1]) <= tolerance; - } - - /// - /// Ordered points along the path: lead-in endpoint, then each cut move - /// endpoint, with arc interior samples at <=90-degree steps (so full - /// circles produce a well-formed polygon). Consecutive duplicates are - /// dropped so zero-length lead-ins do not skew the sample. - /// - public static List SamplePoints(CIFiberContour contour) - { - var pts = new List(); - - void Add(Vector v) - { - if (pts.Count == 0 || pts[^1].DistanceTo(v) > 1e-9) - pts.Add(v); - } - - var prev = contour.LeadIn != null ? contour.LeadIn.EndPoint : contour.Pierce; - Add(prev); - - foreach (var cut in contour.Cuts) - { - if (cut is ArcMove arc) - { - foreach (var mid in ArcSamplePoints(prev, arc)) - Add(mid); - } - Add(cut.EndPoint); - prev = cut.EndPoint; - } - - return pts; - } - - /// - /// Interior points on the arc from to the arc - /// endpoint at no more than ~90-degree sweep intervals. A full circle - /// yields four interior points, giving the shoelace a non-degenerate - /// polygon whose sign is the circle's true winding. - /// - public static List ArcSamplePoints(Vector prev, ArcMove arc) - { - var points = new List(); - var center = arc.CenterPoint; - var radius = center.DistanceTo(arc.EndPoint); - if (radius < 1e-12) - return points; - - var a0 = System.Math.Atan2(prev.Y - center.Y, prev.X - center.X); - var a1 = System.Math.Atan2(arc.EndPoint.Y - center.Y, arc.EndPoint.X - center.X); - - double sweep; - if (arc.Rotation == RotationType.CW) - { - sweep = a0 - a1; - if (sweep <= 0) - sweep += 2.0 * System.Math.PI; - } - else - { - sweep = a1 - a0; - if (sweep <= 0) - sweep += 2.0 * System.Math.PI; - } - - // Full circle (start == end) reads as zero sweep above. - if ( - sweep < 1e-9 - && System.Math.Abs(prev.X - arc.EndPoint.X) < 1e-9 - && System.Math.Abs(prev.Y - arc.EndPoint.Y) < 1e-9 - ) - sweep = 2.0 * System.Math.PI; - - var direction = arc.Rotation == RotationType.CW ? -1.0 : 1.0; - var steps = System.Math.Max(1, (int)System.Math.Ceiling(sweep / (System.Math.PI / 2.0))); - - for (var k = 1; k <= steps; k++) - { - var angle = a0 + direction * sweep * k / (steps + 1); - points.Add( - new Vector( - center.X + radius * System.Math.Cos(angle), - center.Y + radius * System.Math.Sin(angle) - ) - ); - } - - return points; - } - } -} diff --git a/docs/cincinnati-ci-fiber-post-output.md b/docs/cincinnati-ci-fiber-post-output.md index c5f7e519..dd2a2018 100644 --- a/docs/cincinnati-ci-fiber-post-output.md +++ b/docs/cincinnati-ci-fiber-post-output.md @@ -55,8 +55,12 @@ uses the Cincinnati machine-sample convention, not a generic TF5200 laser API: `G1` toward the origin. Both blocks are blank by default, and a nest with a head-locked cut-off is refused while either is blank. Whether `ZHSOFF` and the next contour's `L0` keep a locked head down for the rapid back is unconfirmed. -- Hole subprogram geometry is inlined. Suppressed moves and, by default, - wholly scribe contours are omitted. +- Contour geometry comes from Core's shared `PostContours` (`OpenNest.CNC.Posting`): + hole subprograms and incremental programs are flattened to sheet coordinates, + and it picks the perimeter (never a scribe mark) and each contour's kerf side. + Suppressed moves are omitted; a cut that resumes after them starts a new contour + pierced where they end, which this post refuses without a lead-in rather than + cutting a chord across the gap. By default, wholly scribe contours are omitted. - Files use UTF-8 without a BOM and CRLF lines. Default accuracy is three decimal places: coordinates trim trailing zeros; dimensional header values retain them. From fa6f66429632fec3cea3d017b4b7e2196174172f Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Wed, 11 Nov 2026 15:52:10 -0500 Subject: [PATCH 2/2] fix(posts): pick Cincinnati CL kerf side from the shared contour winding The CL post wrote the configured default side (G41) on every contour, so a contour wound against OpenNest's convention was compensated into the part. It now takes each feature's side from Core's shared PostContours winding rule, as the CI Fiber post does: the perimeter is picked across the part's cut features and hole sub-program contours are always holes. Correctly wound drawings post unchanged. Remove the "Default kerf side" post setting; saved configs that still carry it load as before. Expose PostContours.Flatten and Classify so a post can classify one part's features itself. Add CL tests for a square with a hole: the exact inline program, cuts that match the shared contours on the sheet, G41/G42 keeping the part out of the kerf inline and through part sub-programs, and identical output from absolute and incremental part and hole programs. The replay now records the compensation in force on each cut. Co-Authored-By: Claude Opus 5.5 --- OpenNest.Core/CNC/Posting/PostContours.cs | 23 +- .../CincinnatiFeatureWriterTests.cs | 5 +- .../CincinnatiKerfAndCoordinateTests.cs | 200 ++++++++++++++++++ OpenNest.Tests/Cincinnati/CincinnatiReplay.cs | 21 ++ .../CincinnatiFeatureWriter.cs | 25 +-- .../CincinnatiPartSubprogramWriter.cs | 6 +- .../CincinnatiPostConfig.cs | 17 -- .../CincinnatiPostProcessor.cs | 3 +- .../CincinnatiSheetWriter.cs | 4 + .../OpenNest.Posts.Cincinnati/FeatureUtils.cs | 47 ++++ .../OpenNest.Posts.Cincinnati.json | 1 - docs/cincinnati-post-output.md | 8 +- 12 files changed, 318 insertions(+), 42 deletions(-) create mode 100644 OpenNest.Tests/Cincinnati/CincinnatiKerfAndCoordinateTests.cs diff --git a/OpenNest.Core/CNC/Posting/PostContours.cs b/OpenNest.Core/CNC/Posting/PostContours.cs index ac85ddd0..388a4e41 100644 --- a/OpenNest.Core/CNC/Posting/PostContours.cs +++ b/OpenNest.Core/CNC/Posting/PostContours.cs @@ -41,14 +41,25 @@ public static class PostContours /// public static List Extract(Program program, Vector origin) { - var contours = new List(); - Flatten(program, origin, contours); + var contours = Flatten(program, origin); Classify(contours); return contours; } - /// Picks the perimeter (marks excluded) and each contour's kerf side. - private static void Classify(List contours) + /// + /// The program's contours in the frame, with no perimeter or kerf + /// side chosen yet. A post that splits one part across several calls gathers them here and + /// classifies the whole part with . + /// + public static List Flatten(Program program, Vector origin) + { + var contours = new List(); + FlattenInto(program, origin, contours); + return contours; + } + + /// Picks one part's perimeter (marks excluded) and each contour's kerf side. + public static void Classify(IReadOnlyList contours) { var perimeter = ContourWinding.PerimeterIndex(contours); for (var i = 0; i < contours.Count; i++) @@ -68,7 +79,7 @@ public static class PostContours /// suppressed moves starts a new contour pierced where the run ends, so the gap is crossed /// with the beam off rather than cut as a chord. /// - private static void Flatten(Program program, Vector origin, List contours) + private static void FlattenInto(Program program, Vector origin, List contours) { if (program == null) return; @@ -118,7 +129,7 @@ public static class PostContours // A hole call is its own contour. Flush(); resumeAt = null; - Flatten(call.Program, origin + call.Offset, contours); + FlattenInto(call.Program, origin + call.Offset, contours); break; case Motion motion: diff --git a/OpenNest.Tests/Cincinnati/CincinnatiFeatureWriterTests.cs b/OpenNest.Tests/Cincinnati/CincinnatiFeatureWriterTests.cs index b7e8ef70..20d36507 100644 --- a/OpenNest.Tests/Cincinnati/CincinnatiFeatureWriterTests.cs +++ b/OpenNest.Tests/Cincinnati/CincinnatiFeatureWriterTests.cs @@ -13,7 +13,6 @@ public class CincinnatiFeatureWriterTests FeatureLineNumberStart = 1, UseAntiDive = true, KerfCompensation = KerfMode.ControllerSide, - DefaultKerfSide = KerfSide.Left, InteriorM47 = M47Mode.Always, ExteriorM47 = M47Mode.Always, UseSpeedGas = false, @@ -112,8 +111,8 @@ public class CincinnatiFeatureWriterTests { var config = DefaultConfig(); config.KerfCompensation = KerfMode.ControllerSide; - config.DefaultKerfSide = KerfSide.Left; var ctx = SimpleContext(); + ctx.Kerf = KerfType.Left; var output = WriteFeature(config, ctx); Assert.Contains("G41", output); @@ -125,8 +124,8 @@ public class CincinnatiFeatureWriterTests { var config = DefaultConfig(); config.KerfCompensation = KerfMode.ControllerSide; - config.DefaultKerfSide = KerfSide.Right; var ctx = SimpleContext(); + ctx.Kerf = KerfType.Right; var output = WriteFeature(config, ctx); Assert.Contains("G42", output); diff --git a/OpenNest.Tests/Cincinnati/CincinnatiKerfAndCoordinateTests.cs b/OpenNest.Tests/Cincinnati/CincinnatiKerfAndCoordinateTests.cs new file mode 100644 index 00000000..c50a2a78 --- /dev/null +++ b/OpenNest.Tests/Cincinnati/CincinnatiKerfAndCoordinateTests.cs @@ -0,0 +1,200 @@ +using OpenNest.CNC; +using OpenNest.CNC.Posting; +using OpenNest.Geometry; + +namespace OpenNest.Tests.Cincinnati; + +/// +/// A square with a hole through the CL post: the exact program, where the replayed G-code cuts +/// against Core's shared contours, a kerf side that keeps the part out of the kerf in inline +/// posting, part sub-programs and the hole sub-program, and the same program whichever mode +/// the part and hole programs are stored in. +/// +public class CincinnatiKerfAndCoordinateTests +{ + private static readonly Vector Location = new(1, 2); + + /// + /// A 10x10 square cut CW from (0,0) after a linear lead-in, and a radius-0.5 hole at (5,5) + /// cut CCW as a hole call; winds both the other way. + /// + private static Nest SquareWithHole(Mode partMode = Mode.Absolute, Mode holeMode = Mode.Incremental, + bool reversed = false) + { + var hole = new Program(Mode.Absolute); + hole.Codes.Add(new RapidMove(new Vector(0, -0.6))); + hole.Codes.Add(new LinearMove(new Vector(0, -0.5)) { Layer = LayerType.Leadin }); + hole.Codes.Add(new ArcMove(new Vector(0, -0.5), Vector.Zero, reversed ? RotationType.CW : RotationType.CCW) + { + Layer = LayerType.Cut, + }); + hole.Mode = holeMode; + + var pgm = new Program(Mode.Absolute); + pgm.Codes.Add(new SubProgramCall { Id = 1, Program = hole, Offset = new Vector(5, 5) }); + pgm.Codes.Add(new RapidMove(new Vector(0, -0.5))); + pgm.Codes.Add(new LinearMove(new Vector(0, 0)) { Layer = LayerType.Leadin }); + var corners = reversed + ? new[] { new Vector(10, 0), new Vector(10, 10), new Vector(0, 10), Vector.Zero } + : new[] { new Vector(0, 10), new Vector(10, 10), new Vector(10, 0), Vector.Zero }; + foreach (var corner in corners) + pgm.Codes.Add(new LinearMove(corner) { Layer = LayerType.Cut }); + pgm.Mode = partMode; + + var plate = new Plate(60, 120); + plate.Parts.Add(new Part(new Drawing("square-hole", pgm), Location)); + var nest = new Nest("N"); + nest.Plates.Add(plate); + return nest; + } + + [Fact] + public void SquareWithHole_Inline_PostsTheExactProgram() + { + var output = CincinnatiReplay.Post(SquareWithHole(), partSubprograms: false); + + var body = output[output.IndexOf("GOTO1( Goto Feature )", StringComparison.Ordinal)..]; + Assert.Equal( + """ + GOTO1( Goto Feature ) + N1 G52 X6 Y7 + ( PART: square-hole ) + M98 P200 + G52 X0 Y0 + M47 + N1002 G0 X1 Y1.5 + (WARNING: No library found) + G84 + G41 G1 X1 Y2 F#126 + G1 X1 Y12 F#148 + G1 X11 Y12 + G1 X11 Y2 + G1 X1 Y2 + G40 + M35 + M42 + M99 (END OF N.001) + (*****************************************************) + :200 + ( PART: HOLE ) + N1 G0 X0 Y-0.6 + (WARNING: No library found) + G84 + G41 G1 X0 Y-0.5 F#126 + G3 X0 Y-0.5 I0 J0.5 F[#148*#128] + G40 + M35 + M99 (END OF HOLE) + + """, + body); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void SquareWithHole_CutsTheSharedContoursOnTheSheet(bool partSubprograms) + { + var nest = SquareWithHole(); + var contours = PostContours.Extract(nest.Plates[0].Parts[0]); + + var run = CincinnatiReplay.Run(CincinnatiReplay.Post(nest, partSubprograms)); + + AssertPoints(contours.Select(c => c.Pierce), run.PierceLog.Select(p => p.Point)); + var expected = contours.SelectMany(c => new[] { c.LeadIn }.Concat(c.Cuts)).ToList(); + Assert.Equal(expected.Count, run.Moves.Count); + for (var i = 0; i < expected.Count; i++) + { + Assert.True(CincinnatiReplay.Near(expected[i].EndPoint, run.Moves[i].To), + $"Move {i} ends at {run.Moves[i].To}, expected {expected[i].EndPoint}"); + if (expected[i] is ArcMove arc) + { + Assert.True(CincinnatiReplay.Near(arc.CenterPoint, run.Moves[i].Center!.Value)); + Assert.Equal(arc.Rotation == RotationType.CW, run.Moves[i].Clockwise); + } + } + } + + [Theory] + [InlineData(false, false, "G41")] + [InlineData(true, false, "G41")] + [InlineData(false, true, "G42")] + [InlineData(true, true, "G42")] + public void KerfSide_KeepsThePartOutOfTheKerf(bool partSubprograms, bool reversed, string expected) + { + var run = CincinnatiReplay.Run(CincinnatiReplay.Post(SquareWithHole(reversed: reversed), partSubprograms)); + + Assert.Equal(2, run.Pierces); + Assert.All(run.Moves, move => Assert.Equal(expected, move.Compensation)); + + // The first move after each pierce is the lead-in, which runs through scrap. + var checkedCuts = 0; + foreach (var move in run.Moves.Where((m, i) => i > 0 && run.Moves[i - 1].Pierce == m.Pierce)) + { + AssertPartOnCompensatedSide(move); + checkedCuts++; + } + Assert.Equal(5, checkedCuts); + } + + [Theory] + [InlineData(false, Mode.Absolute, Mode.Absolute)] + [InlineData(false, Mode.Incremental, Mode.Absolute)] + [InlineData(false, Mode.Incremental, Mode.Incremental)] + [InlineData(true, Mode.Absolute, Mode.Absolute)] + [InlineData(true, Mode.Incremental, Mode.Absolute)] + [InlineData(true, Mode.Incremental, Mode.Incremental)] + public void AbsoluteAndIncrementalPrograms_PostTheSameProgram(bool partSubprograms, Mode partMode, Mode holeMode) + { + var expected = WithoutDate(CincinnatiReplay.Post(SquareWithHole(Mode.Absolute, Mode.Incremental), partSubprograms)); + + var actual = WithoutDate(CincinnatiReplay.Post(SquareWithHole(partMode, holeMode), partSubprograms)); + + Assert.Equal(expected, actual); + } + + // The header's third line is the posting time. + private static string WithoutDate(string output) => + string.Join('\n', output.Split('\n').Where((_, i) => i != 2)); + + /// + /// Mid-line (or at an arc's start), the point just right of travel is in the part under G41 + /// and the point just left of it under G42; the other side is the kerf's. + /// + private static void AssertPartOnCompensatedSide(CincinnatiReplay.CutMove move) + { + Vector at, travel; + if (move.Center is { } center) + { + at = move.From; + var radial = move.From - center; + travel = move.Clockwise ? new Vector(radial.Y, -radial.X) : new Vector(-radial.Y, radial.X); + } + else + { + at = (move.From + move.To) * 0.5; + travel = move.To - move.From; + } + + var length = System.Math.Sqrt(travel.X * travel.X + travel.Y * travel.Y); + var right = new Vector(travel.Y / length, -travel.X / length); + var partSide = move.Compensation == "G41" ? right : new Vector(-right.X, -right.Y); + + Assert.True(InPart(at + partSide * 0.01), $"Part is not on the compensated side at {at}"); + Assert.False(InPart(at - partSide * 0.01), $"Kerf side is in the part at {at}"); + } + + private static bool InPart(Vector p) => + p.X > Location.X && p.X < Location.X + 10 + && p.Y > Location.Y && p.Y < Location.Y + 10 + && p.DistanceTo(Location + new Vector(5, 5)) > 0.5; + + private static void AssertPoints(IEnumerable expected, IEnumerable actual) + { + var want = expected.ToList(); + var got = actual.ToList(); + Assert.Equal(want.Count, got.Count); + for (var i = 0; i < want.Count; i++) + Assert.True(CincinnatiReplay.Near(want[i], got[i]), $"Point {i} is {got[i]}, expected {want[i]}"); + } +} diff --git a/OpenNest.Tests/Cincinnati/CincinnatiReplay.cs b/OpenNest.Tests/Cincinnati/CincinnatiReplay.cs index 4cb4c062..67df6309 100644 --- a/OpenNest.Tests/Cincinnati/CincinnatiReplay.cs +++ b/OpenNest.Tests/Cincinnati/CincinnatiReplay.cs @@ -43,6 +43,12 @@ internal static class CincinnatiReplay /// Every cutting move, start to end, in machine coordinates. public List<(Vector From, Vector To)> Cuts { get; } = new(); + /// + /// Every cutting move with the pierce it follows (1-based), its arc centre (null for + /// a line), direction and the compensation in force: "G41", "G42" or null after G40. + /// + public List Moves { get; } = new(); + /// Head raises posted while the head was already raised. public int DoubleRaises { get; set; } @@ -50,6 +56,8 @@ internal static class CincinnatiReplay public int HeadDownRapids { get; set; } } + internal sealed record CutMove(int Pierce, Vector From, Vector To, Vector? Center, bool Clockwise, string? Compensation); + /// /// Minimal replay of the post's own dialect: M98/M99 calls, G52/G92 frames, /// G0-G3 under G90 with incremental I/J, and M47 head raises (a block-deleted @@ -74,6 +82,7 @@ internal static class CincinnatiReplay var cutSincePierce = false; string? raise = null; // raise posted since the last pierce var headDown = false; + string? compensation = null; var pc = 0; while (pc < lines.Count) @@ -89,6 +98,10 @@ internal static class CincinnatiReplay line = line[1..]; var words = Words(line); + if (line.Contains("G41", System.StringComparison.Ordinal)) + compensation = "G41"; + else if (line.Contains("G42", System.StringComparison.Ordinal)) + compensation = "G42"; if (words.TryGetValue("M", out var m)) { if (m == "30") @@ -127,6 +140,9 @@ internal static class CincinnatiReplay switch (g) { + case "40": + compensation = null; + break; case "84": case "85": run.Pierces++; @@ -150,9 +166,11 @@ internal static class CincinnatiReplay case "3": { var target = g92 + g52 + new Vector(Num(words["X"]), Num(words["Y"])); + Vector? arcCenter = null; if (g is "2" or "3") { var center = position + new Vector(Num(words["I"]), Num(words["J"])); + arcCenter = center; var radius = position.DistanceTo(center); Assert.True( System.Math.Abs(target.DistanceTo(center) - radius) < 1e-3, @@ -167,7 +185,10 @@ internal static class CincinnatiReplay { cutSincePierce = true; if (pierced) + { run.Cuts.Add((position, target)); + run.Moves.Add(new CutMove(run.Pierces, position, target, arcCenter, g == "2", compensation)); + } } position = target; break; diff --git a/Posts/OpenNest.Posts.Cincinnati/CincinnatiFeatureWriter.cs b/Posts/OpenNest.Posts.Cincinnati/CincinnatiFeatureWriter.cs index 39dbd8dc..3311976b 100644 --- a/Posts/OpenNest.Posts.Cincinnati/CincinnatiFeatureWriter.cs +++ b/Posts/OpenNest.Posts.Cincinnati/CincinnatiFeatureWriter.cs @@ -21,6 +21,12 @@ public sealed class FeatureContext /// True when this feature cuts the part's exterior (selects ExteriorM47). public bool IsExteriorFeature { get; set; } public bool IsEtch { get; set; } + + /// + /// Compensation that keeps the kerf in the scrap for the way this contour runs + /// (): Left posts G41, Right G42, None neither. + /// + public KerfType Kerf { get; set; } = KerfType.Left; public string LibraryFile { get; set; } = ""; public double CutDistance { get; set; } public double SheetDiagonal { get; set; } @@ -148,13 +154,9 @@ public sealed class CincinnatiFeatureWriter var sb = new StringBuilder(); // Kerf compensation on first cutting move (skip for etch) - if ( - !ctx.IsEtch - && !kerfEmitted - && _config.KerfCompensation == KerfMode.ControllerSide - ) + if (!kerfEmitted && Compensates(ctx)) { - sb.Append(_config.DefaultKerfSide == KerfSide.Left ? "G41 " : "G42 "); + sb.Append(ctx.Kerf == KerfType.Left ? "G41 " : "G42 "); kerfEmitted = true; } @@ -188,13 +190,9 @@ public sealed class CincinnatiFeatureWriter var sb = new StringBuilder(); // Kerf compensation on first cutting move (skip for etch) - if ( - !ctx.IsEtch - && !kerfEmitted - && _config.KerfCompensation == KerfMode.ControllerSide - ) + if (!kerfEmitted && Compensates(ctx)) { - sb.Append(_config.DefaultKerfSide == KerfSide.Left ? "G41 " : "G42 "); + sb.Append(ctx.Kerf == KerfType.Left ? "G41 " : "G42 "); kerfEmitted = true; } @@ -303,6 +301,9 @@ public sealed class CincinnatiFeatureWriter return null; } + private bool Compensates(FeatureContext ctx) => + !ctx.IsEtch && ctx.Kerf != KerfType.None && _config.KerfCompensation == KerfMode.ControllerSide; + private Vector FindPiercePoint(List codes) { foreach (var code in codes) diff --git a/Posts/OpenNest.Posts.Cincinnati/CincinnatiPartSubprogramWriter.cs b/Posts/OpenNest.Posts.Cincinnati/CincinnatiPartSubprogramWriter.cs index 299713ba..75450ecd 100644 --- a/Posts/OpenNest.Posts.Cincinnati/CincinnatiPartSubprogramWriter.cs +++ b/Posts/OpenNest.Posts.Cincinnati/CincinnatiPartSubprogramWriter.cs @@ -42,6 +42,7 @@ public sealed class CincinnatiPartSubprogramWriter /// /// Writes a complete part sub-program for the given normalized program. /// The program must be in absolute mode with coordinates normalized to origin (0,0). + /// With every contour is a hole, as in a hole sub-program. /// public void Write( TextWriter w, @@ -50,7 +51,8 @@ public sealed class CincinnatiPartSubprogramWriter int subNumber, string cutLibrary, string etchLibrary, - double sheetDiagonal + double sheetDiagonal, + bool holes = false ) { var allFeatures = FeatureUtils.SplitByRapids(normalizedProgram.Codes); @@ -60,6 +62,7 @@ public sealed class CincinnatiPartSubprogramWriter // Classify and order: etch features first, then cut features var ordered = FeatureUtils.ClassifyAndOrder(allFeatures); var exterior = FeatureUtils.FindExterior(ordered); + var kerf = FeatureUtils.KerfSides(ordered, holes); w.WriteLine("(*****************************************************)"); w.WriteLine($":{subNumber}"); @@ -90,6 +93,7 @@ public sealed class CincinnatiPartSubprogramWriter IsFirstFeatureOfPart = false, IsLastFeatureOnSheet = isLastFeature, IsExteriorFeature = exterior[i], + Kerf = kerf[i], IsEtch = isEtch, LibraryFile = isEtch ? etchLibrary : cutLibrary, CutDistance = cutDistance, diff --git a/Posts/OpenNest.Posts.Cincinnati/CincinnatiPostConfig.cs b/Posts/OpenNest.Posts.Cincinnati/CincinnatiPostConfig.cs index 35811918..1e515367 100644 --- a/Posts/OpenNest.Posts.Cincinnati/CincinnatiPostConfig.cs +++ b/Posts/OpenNest.Posts.Cincinnati/CincinnatiPostConfig.cs @@ -18,18 +18,6 @@ namespace OpenNest.Posts.Cincinnati PreApplied, } - /// - /// Specifies which side of the cut line kerf compensation is applied to. - /// - public enum KerfSide - { - /// Kerf applied to the left side of the cut. - Left, - - /// Kerf applied to the right side of the cut. - Right, - } - /// /// Specifies how the M47 head raise before each rapid is posted. /// @@ -209,11 +197,6 @@ namespace OpenNest.Posts.Cincinnati [PostSetting(KerfSection, 0)] public KerfMode KerfCompensation { get; set; } = KerfMode.ControllerSide; - [DisplayName("Default kerf side")] - [Description("Default side for kerf compensation (Left or Right).")] - [PostSetting(KerfSection, 1)] - public KerfSide DefaultKerfSide { get; set; } = KerfSide.Left; - [DisplayName("Interior M47")] [Description("How M47 is posted after features other than a part's exterior, such as cutouts and etch.")] [PostSetting(HeadRaiseSection, 0)] diff --git a/Posts/OpenNest.Posts.Cincinnati/CincinnatiPostProcessor.cs b/Posts/OpenNest.Posts.Cincinnati/CincinnatiPostProcessor.cs index 5c76fa63..ccbd0392 100644 --- a/Posts/OpenNest.Posts.Cincinnati/CincinnatiPostProcessor.cs +++ b/Posts/OpenNest.Posts.Cincinnati/CincinnatiPostProcessor.cs @@ -250,7 +250,8 @@ namespace OpenNest.Posts.Cincinnati subNum, initialCutLibrary, etchLibrary, - sheetDiagonal + sheetDiagonal, + holes: true ); } } diff --git a/Posts/OpenNest.Posts.Cincinnati/CincinnatiSheetWriter.cs b/Posts/OpenNest.Posts.Cincinnati/CincinnatiSheetWriter.cs index a532bafb..7086ffe1 100644 --- a/Posts/OpenNest.Posts.Cincinnati/CincinnatiSheetWriter.cs +++ b/Posts/OpenNest.Posts.Cincinnati/CincinnatiSheetWriter.cs @@ -117,6 +117,7 @@ public sealed class CincinnatiSheetWriter public List Codes { get; init; } public bool IsEtch { get; init; } public bool IsExterior { get; init; } + public KerfType Kerf { get; init; } public PartSubprogram Subprogram { get; init; } /// First rapid target: the sub-program corner, else the first pierce. @@ -166,6 +167,7 @@ public sealed class CincinnatiSheetWriter var features = FeatureUtils.SplitAndClassify(part); var exterior = FeatureUtils.FindExterior(features); + var kerf = FeatureUtils.KerfSides(features); for (var f = 0; f < features.Count; f++) { var (codes, isEtch) = features[f]; @@ -178,6 +180,7 @@ public sealed class CincinnatiSheetWriter Codes = codes, IsEtch = isEtch, IsExterior = exterior[f], + Kerf = kerf[f], Entry = start, Start = start, End = end, @@ -261,6 +264,7 @@ public sealed class CincinnatiSheetWriter IsFirstFeatureOfPart = isFirstFeatureOfPart, IsLastFeatureOnSheet = isLastFeature, IsExteriorFeature = item.IsExterior, + Kerf = item.Kerf, IsEtch = item.IsEtch, LibraryFile = item.IsEtch ? etchLibrary : cutLibrary, CutDistance = FeatureUtils.ComputeCutDistance(codes), diff --git a/Posts/OpenNest.Posts.Cincinnati/FeatureUtils.cs b/Posts/OpenNest.Posts.Cincinnati/FeatureUtils.cs index c8c5d9fd..ad71c580 100644 --- a/Posts/OpenNest.Posts.Cincinnati/FeatureUtils.cs +++ b/Posts/OpenNest.Posts.Cincinnati/FeatureUtils.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using OpenNest.CNC; +using OpenNest.CNC.Posting; using OpenNest.Geometry; using OpenNest.Math; @@ -239,6 +240,52 @@ public static class FeatureUtils return result; } + /// + /// Each feature's kerf side from Core's shared winding rule (): + /// the side that keeps the kerf in the scrap the way the contour actually runs. The part's + /// perimeter is picked across all its cut features; with every + /// feature is a hole, as in a hole sub-program. Etch features and hole calls get + /// : etch is never compensated and a hole sub-program picks its own. + /// + public static KerfType[] KerfSides( + IReadOnlyList<(List codes, bool isEtch)> features, + bool holes = false + ) + { + var contours = new List(); + var owners = new List(); + for (var i = 0; i < features.Count; i++) + { + var (codes, isEtch) = features[i]; + if (isEtch || (codes.Count == 1 && codes[0] is SubProgramCall)) + continue; + + var program = new Program(Mode.Absolute); + program.Codes.AddRange(codes); + foreach (var contour in PostContours.Flatten(program, Vector.Zero)) + { + contours.Add(contour); + owners.Add(i); + } + } + + if (holes) + { + foreach (var contour in contours) + contour.Kerf = ContourWinding.CompensationSide(contour, isPerimeter: false); + } + else + { + PostContours.Classify(contours); + } + + // A feature is one contour; its first contour decides if it ever splits. + var sides = new KerfType[features.Count]; + for (var k = contours.Count - 1; k >= 0; k--) + sides[owners[k]] = contours[k].Kerf; + return sides; + } + private static Box CutBounds(List codes) { var cut = new Program(Mode.Absolute); diff --git a/Posts/OpenNest.Posts.Cincinnati/OpenNest.Posts.Cincinnati.json b/Posts/OpenNest.Posts.Cincinnati/OpenNest.Posts.Cincinnati.json index f771701f..86f555c4 100644 --- a/Posts/OpenNest.Posts.Cincinnati/OpenNest.Posts.Cincinnati.json +++ b/Posts/OpenNest.Posts.Cincinnati/OpenNest.Posts.Cincinnati.json @@ -15,7 +15,6 @@ "UseAntiDive": true, "UseSmartRapids": false, "KerfCompensation": "ControllerSide", - "DefaultKerfSide": "Left", "InteriorM47": "Always", "ExteriorM47": "Always", "M47OverrideDistanceThreshold": null, diff --git a/docs/cincinnati-post-output.md b/docs/cincinnati-post-output.md index de7f2fa0..cf9dd5c7 100644 --- a/docs/cincinnati-post-output.md +++ b/docs/cincinnati-post-output.md @@ -104,7 +104,13 @@ block in a sheet or sub-program output follows this order 5. `M130 (ANTI DIVE OFF)` — disable anti-dive, only if configured (§3.130). 6. Contour moves: - `G41` (left) or `G42` (right) kerf compensation on the first cut move - (§1.41 / §1.42), suppressed for etch features. + (§1.41 / §1.42), suppressed for etch features. The side comes from Core's + shared `PostContours` winding rule, the same one the CI Fiber post uses: + whichever keeps the kerf in the scrap for the way the contour runs. Imported + drawings (perimeter CW, holes CCW) get `G41` throughout; a contour wound the + other way gets `G42`. The perimeter is the part's cut feature with the + largest bounding box; contours in a hole sub-program are always holes. + Paths that enclose no area, such as cut-off lines, keep `G41`. - `G1 X_ Y_ [F]` — linear cut move (§1.01). Feedrate references a machine variable such as `#148` and is emitted only when it changes. - `G2 X_ Y_ I_ J_ [F]` (CW) or `G3` (CCW) — arc (§1.02 / §1.03).