diff --git a/AGENTS.md b/AGENTS.md index 58d1742d..be7f5e63 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -54,6 +54,7 @@ Releases: follow [the release procedure](docs/releasing.md) and `scripts/Publish - Cutoffs persist as definitions on `Plate.CutOffs`; apply through `RegenerateCutOffs`, never preview parts. Preserve sequence positions. Batch planning must finish before mutation and roll back on failure. Use `PlateSequencing.Apply` for automatic cutoff dependencies, with nominal spans/reference identity rather than trimmed geometry/names. - A cutoff starts only at the origin-side edge: stock can be oversize, so the far edge is unknown. Only a head-locked overcut (`CutOff.HeadLockOvercut`, `HeadHeightLock` markers) may start its far-edge segment there; posts refuse it without lock codes. - Fixed emissions (locked programs, drawing-pinned contours) are accepted as given: their violations warn on an UNVERIFIED proposal and never steer the search, while every planner-chosen motion stays strict. Plates without them must keep the `PlanningCharacterizationTests` digests. +- A `HeadRaise` marker (a rapid made head-up over cut parts) is the safest-route fallback's last resort, added only after the strict search fails; the strict search never marks a rapid. Every post must raise before a marked rapid or refuse the nest. - An empty diagnostic is not a clear result unless `IsComplete`. Posting must run checks before writing CNC output; warnings require explicit per-attempt consent, never a persisted bypass. Keep inputs stable through analysis/cancellation. - Preserve symbolic G-code variable definitions/references in file round trips. Keep training bitmaps by default; inference checks predictor availability before scalar-only extraction. diff --git a/OpenNest.Core/CNC/CuttingPlanning/ExecutionMotionReader.cs b/OpenNest.Core/CNC/CuttingPlanning/ExecutionMotionReader.cs index f4d32acc..ca5386cb 100644 --- a/OpenNest.Core/CNC/CuttingPlanning/ExecutionMotionReader.cs +++ b/OpenNest.Core/CNC/CuttingPlanning/ExecutionMotionReader.cs @@ -41,8 +41,10 @@ public static class ExecutionMotionReader var pos = frame; var first = true; var countBefore = moves.Count; - foreach (var code in current.Codes) + var raised = HeadRaise.RaisedMask(current.Codes); + for (var codeIndex = 0; codeIndex < current.Codes.Count; codeIndex++) { + var code = current.Codes[codeIndex]; token.ThrowIfCancellationRequested(); if (--budget < 0) throw new ArgumentException("Program expansion exceeds the verification limit."); @@ -106,7 +108,8 @@ public static class ExecutionMotionReader var curve = rapid ? null : PostVerificationGeometry.Curve.Create(pos, end, motion is ArcMove arcMove ? reference + arcMove.CenterPoint : null, motion is ArcMove { Rotation: RotationType.CW }); - moves.Add(new(start, end, rapid, layer, curve)); + moves.Add(new(start, end, rapid, layer, curve, raised[codeIndex], + ReferenceEquals(current, program) ? codeIndex : null)); pos = end; first = false; } diff --git a/OpenNest.Core/CNC/CuttingPlanning/OwnedExecution.cs b/OpenNest.Core/CNC/CuttingPlanning/OwnedExecution.cs index e3fef39f..0620cb6e 100644 --- a/OpenNest.Core/CNC/CuttingPlanning/OwnedExecution.cs +++ b/OpenNest.Core/CNC/CuttingPlanning/OwnedExecution.cs @@ -38,20 +38,31 @@ public sealed class OwnedExecution public sealed class ExecutionMotion { internal ExecutionMotion(Vector? start, Vector end, bool rapid, LayerType layer, - PostVerificationGeometry.Curve curve) + PostVerificationGeometry.Curve curve, bool headRaised = false, int? code = null) { Start = start; End = end; Rapid = rapid; Layer = layer; Curve = curve; + HeadRaised = headRaised; + Code = code; } public Vector? Start { get; } public Vector End { get; } public bool Rapid { get; } public LayerType Layer { get; } + + /// A rapid made with the head raised over parts already cut (). + public bool HeadRaised { get; } + + /// + /// The index of the code this motion runs in the read program's own codes; null for a motion + /// inside a sub-program and for the rapid a program that opens with a cut is given. + /// + public int? Code { get; } public double Length => Curve?.Length ?? 0; internal PostVerificationGeometry.Curve Curve { get; } - internal ExecutionMotion WithStart(Vector? start) => new(start, End, Rapid, Layer, Curve); + internal ExecutionMotion WithStart(Vector? start) => new(start, End, Rapid, Layer, Curve, HeadRaised, Code); } diff --git a/OpenNest.Core/CNC/CuttingPlanning/ReleasedContourState.cs b/OpenNest.Core/CNC/CuttingPlanning/ReleasedContourState.cs index 8f106e26..34fcb6ce 100644 --- a/OpenNest.Core/CNC/CuttingPlanning/ReleasedContourState.cs +++ b/OpenNest.Core/CNC/CuttingPlanning/ReleasedContourState.cs @@ -54,9 +54,11 @@ public sealed class ReleasedContourState /// As , but a /// finding whose offending motion owns (by motion index) is /// returned apart: a fixed emission is accepted as given and only reported. The checker - /// state advances exactly as it would without ownership. + /// state advances exactly as it would without ownership. Crossings made by a rapid with the + /// head raised are returned apart as well, as Raised: they are the raise's reason, not a fault. /// - internal (IReadOnlyList Strict, IReadOnlyList Fixed) Check( + internal (IReadOnlyList Strict, IReadOnlyList Fixed, + IReadOnlyList Raised) Check( OwnedExecution execution, Vector? arrival, int partNumber, bool cutoff, Func isFixed, CancellationToken token) { @@ -67,8 +69,10 @@ public sealed class ReleasedContourState moves[0] = moves[0].WithStart(arrival); var findings = new List(); var fixedFindings = new List(); - AnalyzeMoves(moves, cutoff, findings, 1, partNumber, token, isFixed, fixedFindings); - return (findings.AsReadOnly(), fixedFindings.AsReadOnly()); + var raisedFindings = new List(); + AnalyzeMoves(moves, cutoff, findings, 1, partNumber, token, isFixed, fixedFindings, + raisedFindings: raisedFindings); + return (findings.AsReadOnly(), fixedFindings.AsReadOnly(), raisedFindings.AsReadOnly()); } /// @@ -97,7 +101,7 @@ public sealed class ReleasedContourState internal void AnalyzeMoves(IReadOnlyList moves, bool cutoff, List findings, int plate, int part, CancellationToken token, Func isFixed = null, List fixedFindings = null, - bool proveOpenCuts = false, int contoursBefore = 0) + bool proveOpenCuts = false, int contoursBefore = 0, List raisedFindings = null) { var current = new CutGroup(); var unfinished = new List(); @@ -166,16 +170,22 @@ public sealed class ReleasedContourState if (obstacle.OvercutEnd is { } tailEnd && tailEnd.DistanceTo(start) <= PostVerificationGeometry.Epsilon && start.DistanceTo(move.End) > PostVerificationGeometry.RaySeamTolerance) from = start + (move.End - start) * (PostVerificationGeometry.RaySeamTolerance / start.DistanceTo(move.End)); - if (PostVerificationGeometry.Crosses(from, move.End, obstacle.Curves, token)) - Add(new(PostVerificationKind.RapidCrossing, plate, part, obstacle.Part, - $"Direct XY rapid crosses or touches completed untabbed contour {obstacle.Contour} " + - $"of part {obstacle.Part}.") - { - Location = (start + move.End) * 0.5, - RapidStart = start, - RapidEnd = move.End, - ContactPoints = PostVerificationGeometry.ContactPoints(from, move.End, obstacle.Curves, token) - }, owned); + if (!PostVerificationGeometry.Crosses(from, move.End, obstacle.Curves, token)) + continue; + var crossing = new PostVerificationFinding(PostVerificationKind.RapidCrossing, plate, part, + obstacle.Part, (move.HeadRaised ? "Head-raised" : "Direct") + " XY rapid crosses or touches " + + $"completed untabbed contour {obstacle.Contour} of part {obstacle.Part}.") + { + Location = (start + move.End) * 0.5, + RapidStart = start, + RapidEnd = move.End, + ContactPoints = PostVerificationGeometry.ContactPoints(from, move.End, obstacle.Curves, token) + }; + // The head clears a cut part on a raised rapid; the crossing is the raise's reason. + if (move.HeadRaised) + raisedFindings?.Add(crossing); + else + Add(crossing, owned); } } else if (move.Layer == LayerType.Leadin) diff --git a/OpenNest.Core/CNC/HeadRaise.cs b/OpenNest.Core/CNC/HeadRaise.cs new file mode 100644 index 00000000..e88b4b0c --- /dev/null +++ b/OpenNest.Core/CNC/HeadRaise.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace OpenNest.CNC +{ + /// + /// A rapid the head must make raised because it passes over parts already cut, which may have + /// tipped. Plan Cutting marks such a rapid only when no route avoids the crossing: a + /// comment immediately before the . Rapid checks accept + /// a crossing on a marked rapid. Posts write their machine's head raise before every marked rapid, + /// and refuse to post a marked program when they have none, since the rapid is unsafe head down. + /// See docs/cutting-planner.md. + /// + public static class HeadRaise + { + /// The comment immediately before a rapid made with the head raised. + public const string Marker = "HEAD RAISE"; + + public static bool IsMarker(ICode code) => code is Comment { Value: Marker }; + + /// Whether 's own codes hold a marker. + public static bool IsMarked(Program program) + { + if (program?.Codes == null) + return false; + foreach (var code in program.Codes) + if (IsMarker(code)) + return true; + return false; + } + + /// + /// For each of , whether it is a rapid made with the head raised. A + /// marker must be followed directly by a rapid; anything else is a malformed program + /// (), since a post could raise before the wrong move. + /// + public static bool[] RaisedMask(IReadOnlyList codes) + { + ArgumentNullException.ThrowIfNull(codes); + var mask = new bool[codes.Count]; + for (var i = 0; i < codes.Count; i++) + { + if (!IsMarker(codes[i])) + continue; + if (i + 1 >= codes.Count || codes[i + 1] is not RapidMove) + throw new ArgumentException("A head-raise marker is not followed by a rapid."); + mask[i + 1] = true; + } + return mask; + } + + /// + /// A copy of with a marker before each of its own codes at + /// , which must be rapids not marked already. + /// + public static Program Mark(Program program, IReadOnlyCollection rapids) + { + ArgumentNullException.ThrowIfNull(program); + ArgumentNullException.ThrowIfNull(rapids); + var marked = RaisedMask(program.Codes); + var copy = (Program)program.Clone(); + for (var i = copy.Codes.Count - 1; i >= 0; i--) + { + if (!rapids.Contains(i)) + continue; + if (copy.Codes[i] is not RapidMove || marked[i]) + throw new ArgumentException("Only an unmarked rapid can be marked for a head raise."); + copy.Codes.Insert(i, new Comment(Marker)); + } + return copy; + } + + /// + /// Refuses a nest a post cannot write, before any output is created: a marked rapid needs + /// the post's head-raise code, and its markers must be well formed. + /// + public static void EnsurePostable(Nest nest, bool hasCode, string postName) + { + ArgumentNullException.ThrowIfNull(nest); + foreach (var plate in nest.Plates) + { + foreach (var part in plate.Parts) + { + if (part?.Program == null || !IsMarked(part.Program)) + continue; + var name = DisplayPerimeterTail.PartName(part); + if (!hasCode) + throw new InvalidOperationException( + $"{name} has rapids that must raise the head over parts already cut, but the {postName} " + + "post has no head-raise code. Enter it in the post's configuration before posting."); + try + { + RaisedMask(part.Program.Codes); + } + catch (ArgumentException ex) + { + throw new InvalidOperationException($"{name} cannot be posted: {ex.Message}", ex); + } + } + } + } + } +} diff --git a/OpenNest.Engine/CuttingPlanning/CuttingPlanBatch.cs b/OpenNest.Engine/CuttingPlanning/CuttingPlanBatch.cs index cf75f755..44fb06a9 100644 --- a/OpenNest.Engine/CuttingPlanning/CuttingPlanBatch.cs +++ b/OpenNest.Engine/CuttingPlanning/CuttingPlanBatch.cs @@ -212,9 +212,10 @@ public sealed class CuttingPlanBatch /// /// Safest first, then fastest: the replayed safest route from the free order and from the - /// current order, whichever breaks fewer checks (most severe first), then has less rapid - /// travel. A route whose planner-chosen motions pass every check is taken at once, even - /// when fixed lead-ins still warn. Null when neither walk finds a route. + /// current order, whichever breaks fewer checks (most severe first), then raises the head + /// fewer times, then has less rapid travel. A route whose planner-chosen motions pass every + /// check head-down is taken at once, even when fixed lead-ins still warn. Null when neither + /// walk finds a route. /// private static (CuttingPlanResult Result, bool FreeOrder)? SafestRoute(Entry entry, CancellationToken token) { @@ -225,10 +226,9 @@ public sealed class CuttingPlanBatch { if (CuttingPlanService.PlanSafestRoute(snapshot, token) is not { } candidate) continue; - if (!candidate.IsSafestRouteFallback) + if (!candidate.IsSafestRouteFallback && candidate.HeadRaises == 0) return (candidate, freeOrder); - if (best is not { } known || candidate.SafestRoute < known.Result.SafestRoute - || candidate.SafestRoute == known.Result.SafestRoute && candidate.RapidDistance < known.Result.RapidDistance) + if (best is not { } known || Safer(candidate, known.Result)) best = (candidate, freeOrder); } } @@ -239,6 +239,17 @@ public sealed class CuttingPlanBatch return best; } + // Fewer broken checks (a route that breaks none first), then fewer head raises, then less travel. + private static bool Safer(CuttingPlanResult candidate, CuttingPlanResult known) + { + var severity = (candidate.SafestRoute ?? default).CompareTo(known.SafestRoute ?? default); + if (severity != 0) + return severity < 0; + if (candidate.HeadRaises != known.HeadRaises) + return candidate.HeadRaises < known.HeadRaises; + return candidate.RapidDistance < known.RapidDistance; + } + internal static CuttingPlanResult PlanReorder(CuttingPlanSnapshot snapshot, CancellationToken token, int firstPassBudget = FirstPassBudget) { @@ -514,8 +525,11 @@ public sealed class CuttingPlanProposal + $"regenerated, {kept} kept as is; rapid travel " + $"{result.RapidDistance.ToString("0.##", CultureInfo.CurrentCulture)} {unit}. {order}" + (plate.ReversedCutOffCount == 0 ? "" - : $" {Count(plate.ReversedCutOffCount, "cutoff segment")} at the far edge change direction."); - // A ready plan's findings are advisory notes (support tabs that may not hold a part level). + : $" {Count(plate.ReversedCutOffCount, "cutoff segment")} at the far edge change direction.") + + (result.HeadRaises == 0 ? "" + : $" No route found keeps the head down over every cut part, so {Count(result.HeadRaises, "rapid")} " + + $"{(result.HeadRaises == 1 ? "raises" : "raise")} the head; each is listed below."); + // A ready plan's findings are advisory notes (head raises, support tabs that may not hold a part level). foreach (var line in Limit(result.Findings.Select(DescribeFinding))) yield return line; yield break; diff --git a/OpenNest.Engine/CuttingPlanning/CuttingPlanModels.cs b/OpenNest.Engine/CuttingPlanning/CuttingPlanModels.cs index 5f405974..c3c1028d 100644 --- a/OpenNest.Engine/CuttingPlanning/CuttingPlanModels.cs +++ b/OpenNest.Engine/CuttingPlanning/CuttingPlanModels.cs @@ -367,6 +367,12 @@ public sealed class CuttingPlanResult /// Whether this is a safest-route fallback rather than a route that passed every check. public bool IsSafestRouteFallback => SafestRoute != null; + /// + /// The rapids that raise the head over parts already cut, each listed in . + /// Only a safest-route fallback marks them, when no search kept every rapid head-down. + /// + public int HeadRaises { get; init; } + /// The captured input this result was planned from; binds Apply to its freshness record. internal CuttingPlanSnapshot Snapshot { get; set; } } diff --git a/OpenNest.Engine/CuttingPlanning/CuttingPlanService.cs b/OpenNest.Engine/CuttingPlanning/CuttingPlanService.cs index 95267e1a..471d64af 100644 --- a/OpenNest.Engine/CuttingPlanning/CuttingPlanService.cs +++ b/OpenNest.Engine/CuttingPlanning/CuttingPlanService.cs @@ -350,10 +350,13 @@ public static class CuttingPlanService /// /// The safest route the greedy walk finds, independently replayed; null when there is none. - /// A route that passes every check is Ready. One that does not is an UNVERIFIED BestEffort - /// carrying every violation, applicable only with explicit acceptance. A route the replay - /// cannot check completely, or with any motion into material (a lead that does not fit, - /// a cut-order or nested-lead conflict), is never offered: the strict refusal stands. + /// Its planner-chosen rapids that still cross parts already cut raise the head + /// (): only here, after the strict search found no route avoiding + /// them. A route that then passes every check is Ready, listing its raises. One that does not + /// is an UNVERIFIED BestEffort carrying every violation, applicable only with explicit + /// acceptance. A route the replay cannot check completely, or with any motion into material + /// (a lead that does not fit, a cut-order or nested-lead conflict), is never offered: the + /// strict refusal stands. /// internal static CuttingPlanResult PlanSafestRoute(CuttingPlanSnapshot snapshot, CancellationToken token) { @@ -366,6 +369,14 @@ public static class CuttingPlanService var order = JointCuttingPlanSearch.SafestRoute(snapshot.WithSearchLimits(budget, snapshot.MaxEntries), token); if (order == null) return null; + try + { + order = RaisedRapids.Mark(snapshot, order, token); + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException) + { + // A route that cannot be read for marking keeps its crossings as findings. + } var result = ReplayPrograms(snapshot, order, 0, token, safestRoute: true); if (result.Status is not (CuttingPlanStatus.Ready or CuttingPlanStatus.BestEffort) || result.SafestRoute is { Severe: > 0 }) @@ -397,6 +408,9 @@ public static class CuttingPlanService // Violations inside fixed emissions: accepted as given, reported, never refused (D1a). // Capture adds the drawing pins it could not honour; their contours were planned normally. var warnings = new List(snapshot.Findings); + // Rapids that raise the head over cut parts are listed, never refused. + var raises = new List(); + var raisedRapids = 0; var materialOwners = snapshot.Placements.Where(p => !p.IsCutOff).ToArray(); var materials = materialOwners.Select(p => p.Material).ToArray(); foreach (var proposal in order) @@ -433,8 +447,10 @@ public static class CuttingPlanService findings: [JointCuttingPlanSearch.Finding(source, PostVerificationKind.Incomplete, ex.Message)], expansions: expansions); } var isFixed = proposal.FixedMotions(execution); - var (strict, fixedFindings) = checker.Check(execution, position, source.SourceOrdinal + 1, + var (strict, fixedFindings, raised) = checker.Check(execution, position, source.SourceOrdinal + 1, source.IsCutOff, isFixed, token); + raises.AddRange(RaisedRapids.Notes(snapshot, source, raised)); + raisedRapids += RaisedRapids.Count(raised); findings.AddRange(JointCuttingPlanSearch.Map(snapshot, strict)); warnings.AddRange(fixedFindings.Select(f => FixedLeadWarnings.FromChecker(snapshot, source, f))); var fixedLeads = new List(); @@ -464,12 +480,14 @@ public static class CuttingPlanService } token.ThrowIfCancellationRequested(); // Support tabs that cannot hold their part level are noted, never refused. - var notes = order.SelectMany(SupportTabCapture.Notes).Concat(SupportTabCapture.Skipped(snapshot)).ToList(); + var notes = raises.Concat(order.SelectMany(SupportTabCapture.Notes)) + .Concat(SupportTabCapture.Skipped(snapshot)).ToList(); if (safestRoute && findings.Count != 0 && findings.All(f => f.Kind != PostVerificationKind.Incomplete)) return new(CuttingPlanStatus.BestEffort, order, findings.Concat(warnings).Concat(notes).Distinct(), expansions, distance) { SafestRoute = RouteSeverity.Of(findings.Distinct().Select(f => f.Kind)), + HeadRaises = raisedRapids, }; if (findings.Count != 0) return new(findings.Any(f => f.Kind == PostVerificationKind.Incomplete) @@ -479,9 +497,11 @@ public static class CuttingPlanService // UNVERIFIED: never Ready, applicable only through explicit warning acceptance. if (warnings.Count != 0) return new(CuttingPlanStatus.BestEffort, order, warnings.Concat(notes).Distinct(), expansions, - distance, independentlyReplayed: true); + distance, independentlyReplayed: true) + { HeadRaises = raisedRapids }; return new(CuttingPlanStatus.Ready, order, notes, expansions: expansions, - rapidDistance: distance, independentlyReplayed: true); + rapidDistance: distance, independentlyReplayed: true) + { HeadRaises = raisedRapids }; } private static CuttingPlanFinding DependencyFinding(CuttingPlanSnapshot snapshot, diff --git a/OpenNest.Engine/CuttingPlanning/RaisedRapids.cs b/OpenNest.Engine/CuttingPlanning/RaisedRapids.cs new file mode 100644 index 00000000..5da77c51 --- /dev/null +++ b/OpenNest.Engine/CuttingPlanning/RaisedRapids.cs @@ -0,0 +1,93 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using OpenNest.CNC; +using OpenNest.CNC.CuttingPlanning; +using OpenNest.Diagnostics; +using OpenNest.Geometry; + +namespace OpenNest.Engine.CuttingPlanning; + +/// +/// The last resort for a route no search could keep head-down: each planner-chosen rapid that +/// crosses parts already cut is marked to raise the head (). Only the +/// safest-route fallback uses it, after the strict search found no route avoiding every crossing, +/// so a plate that can be cut head-down never gets a raise. Rapids into or inside a fixed emission, +/// and rapids inside sub-programs, are never marked: their crossings stay findings. +/// +internal static class RaisedRapids +{ + /// + /// with the crossing rapids of regenerated parts marked, walked as + /// replay walks it. Parts with nothing to mark keep their proposal. + /// + internal static IReadOnlyList Mark(CuttingPlanSnapshot snapshot, + IReadOnlyList order, CancellationToken token) + { + var checker = new ReleasedContourState(reportMissingLeadIns: false); + var position = snapshot.StartPoint; + var marked = new List(order.Count); + foreach (var proposal in order) + { + token.ThrowIfCancellationRequested(); + var program = proposal.CopyProgram(); + var execution = ExecutionMotionReader.Read(program, proposal.Location, position, token); + var placement = proposal; + var rapids = proposal.Prepared == null || proposal.IsCutOff ? [] + : Crossing(checker.Copy(), proposal, execution, position, token); + if (rapids.Count != 0) + { + var raised = HeadRaise.Mark(program, rapids); + execution = ExecutionMotionReader.Read(raised, proposal.Location, position, token); + placement = proposal.Propose(raised, execution, proposal.ContourChoices, token); + } + checker.Check(execution, position, proposal.SourceOrdinal + 1, proposal.IsCutOff, + proposal.FixedMotions(execution), token); + marked.Add(placement); + position = execution.DeparturePoint; + } + return marked; + } + + // The own-code indices of the planner's rapids that cross parts already cut. + private static HashSet Crossing(ReleasedContourState checker, FixedProgramPlacement proposal, + OwnedExecution execution, Vector arrival, CancellationToken token) + { + var isFixed = proposal.FixedMotions(execution); + var strict = checker.Check(execution, arrival, proposal.SourceOrdinal + 1, false, isFixed, token).Strict; + var codes = new HashSet(); + foreach (var finding in strict) + { + if (finding.Kind != PostVerificationKind.RapidCrossing || finding.RapidEnd is not { } end) + continue; + for (var index = 0; index < execution.Motions.Count; index++) + { + var motion = execution.Motions[index]; + if (motion.Rapid && motion.Code is int code && isFixed?.Invoke(index) != true + && motion.End == end && (index == 0 ? arrival : motion.Start) == finding.RapidStart) + codes.Add(code); + } + } + return codes; + } + + /// + /// One advisory note per raised rapid of , naming the cut parts it + /// passes over, from the replay's raised crossings (check positions are source ordinals + 1). + /// + internal static IEnumerable Notes(CuttingPlanSnapshot snapshot, + FixedProgramPlacement source, IReadOnlyList raised) => + raised.GroupBy(f => (f.RapidStart, f.RapidEnd)).Select(rapid => + { + var parts = rapid.Select(f => f.OtherPartNumber).OfType().Distinct().Order().ToArray(); + var other = parts.Length == 1 ? snapshot.Placements[parts[0] - 1] : null; + var over = other != null ? "a part already cut" : $"parts {string.Join(", ", parts)}, already cut,"; + return new CuttingPlanFinding(source.SourceOrdinal, source.SourcePart, other?.SourceOrdinal, + other?.SourcePart, null, $"A rapid raises the head over {over} because no route found keeps the head down.") + { Witness = rapid.First() }; + }); + + /// The raised rapids in : crossings of one rapid count once. + internal static int Count(IEnumerable raised) => + raised.Select(f => (f.RapidStart, f.RapidEnd)).Distinct().Count(); +} diff --git a/OpenNest.Tests/Cincinnati/HeadRaisePostTests.cs b/OpenNest.Tests/Cincinnati/HeadRaisePostTests.cs new file mode 100644 index 00000000..95838984 --- /dev/null +++ b/OpenNest.Tests/Cincinnati/HeadRaisePostTests.cs @@ -0,0 +1,108 @@ +using System.Text; +using OpenNest.CNC; +using OpenNest.Geometry; +using OpenNest.Posts.Cincinnati; +using OpenNest.Posts.CincinnatiCIFiber; + +namespace OpenNest.Tests.Cincinnati; + +/// +/// Both Cincinnati posts raise the head before a rapid Plan Cutting marked to pass over parts +/// already cut, whatever the operator's head-raise settings; the CI Fiber post refuses the nest +/// while its head-raise block is not set. +/// +public class HeadRaisePostTests +{ + private const string RaiseCode = "M210 (RAISE HEAD)"; + + [Theory] + [InlineData(M47Mode.None)] + [InlineData(M47Mode.BlockDelete)] + [InlineData(M47Mode.Auto)] + public void ClPost_RaisesBeforeAMarkedRapid_WhateverTheM47Mode(M47Mode mode) + { + var lines = ClLines(Nest(markSecond: true), mode); + + var second = lines.FindIndex(l => l.Contains("G0 X10.75 Y1")); + Assert.True(second > 0, string.Join("\n", lines)); + Assert.Equal("M47", lines[second - 1]); + } + + [Fact] + public void ClPost_WithoutAMarker_FollowsTheM47Mode() + { + var lines = ClLines(Nest(markSecond: false), M47Mode.None); + + var second = lines.FindIndex(l => l.Contains("G0 X10.75 Y1")); + Assert.True(second > 0, string.Join("\n", lines)); + Assert.DoesNotContain("M47", lines[second - 1]); + } + + [Fact] + public void CiFiberPost_WritesTheRaiseBeforeOnlyTheMarkedRapid() + { + var post = new CIFiberPostProcessor(new CIFiberPostConfig { HeadRaiseCode = RaiseCode }); + using var stream = new MemoryStream(); + post.Post(Nest(markSecond: true), stream); + var lines = Lines(stream); + + var raise = Assert.Single(lines, l => l == RaiseCode); + Assert.Equal("G0X10.75Y1", lines[lines.IndexOf(raise) + 1]); + } + + [Fact] + public void CiFiberPost_WithoutARaiseCode_RefusesAMarkedNest() + { + var post = new CIFiberPostProcessor(new CIFiberPostConfig()); + + var refusal = Assert.Throws(() => post.Post(Nest(markSecond: true), new MemoryStream())); + + Assert.Contains("head-raise code", refusal.Message); + post.Post(Nest(markSecond: false), new MemoryStream()); // Nothing marked: nothing to refuse. + } + + // Two squares side by side, each with a line lead-in on its left; the second one's rapid marked. + private static Nest Nest(bool markSecond) + { + var nest = new Nest("RAISE"); + var plate = new Plate(60, 120); + nest.Plates.Add(plate); + foreach (var x in new[] { 1.0, 11.0 }) + { + var part = new Part(new Drawing("square", Square()), new Vector(x, 0)); + var program = LeadIn(); + if (markSecond && x > 1) + program = HeadRaise.Mark(program, [0]); + Assert.True(part.RestoreLeadInProgram(program, true)); + plate.Parts.Add(part); + } + return nest; + } + + private static Program Square() + { + var p = new Program(); + p.MoveTo(0, 0); p.LineTo(0, 2); p.LineTo(2, 2); p.LineTo(2, 0); p.LineTo(0, 0); + return p; + } + + private static Program LeadIn() + { + var p = new Program(); + p.MoveTo(-0.25, 1); + p.Codes.Add(new LinearMove(0, 1) { Layer = LayerType.Leadin }); + p.LineTo(0, 2); p.LineTo(2, 2); p.LineTo(2, 0); p.LineTo(0, 0); p.LineTo(0, 1); + return p; + } + + private static List ClLines(Nest nest, M47Mode mode) + { + var post = new CincinnatiPostProcessor(new CincinnatiPostConfig { ExteriorM47 = mode, InteriorM47 = mode }); + using var stream = new MemoryStream(); + post.Post(nest, stream); + return Lines(stream); + } + + private static List Lines(MemoryStream stream) => + Encoding.UTF8.GetString(stream.ToArray()).Replace("\r\n", "\n").Split('\n').Select(l => l.Trim()).ToList(); +} diff --git a/OpenNest.Tests/CuttingPlanning/HeadRaisePlanningTests.cs b/OpenNest.Tests/CuttingPlanning/HeadRaisePlanningTests.cs new file mode 100644 index 00000000..b2151ab6 --- /dev/null +++ b/OpenNest.Tests/CuttingPlanning/HeadRaisePlanningTests.cs @@ -0,0 +1,123 @@ +using OpenNest.CNC; +using OpenNest.CNC.CuttingPlanning; +using OpenNest.Diagnostics; +using OpenNest.Engine.CuttingPlanning; +using OpenNest.Geometry; + +namespace OpenNest.Tests.CuttingPlanning; + +/// +/// Plan Cutting raises the head over cut parts only as a last resort: a route that keeps the +/// head down always wins, and only the rapids no route could keep clear are marked. +/// +public class HeadRaisePlanningTests +{ + [Fact] + public void KeptOrderThatMustCrossAWall_IsReadyWithOneRaise() + { + // A tall wall is cut first, then the square left of it, then the one right of it: + // every rapid from the left square to the right one passes over the wall. + var (nest, plate) = WallPlate(); + + var proposal = CuttingPlanBatch.Capture([plate], ExplicitContourTests.Parameters(), preservePartOrder: true).Plan(); + var result = proposal.Plates[0].Result; + + Assert.True(proposal.Plates[0].IsReady, string.Join("\n", proposal.Describe("in"))); + Assert.Equal(1, result.HeadRaises); + Assert.False(result.IsSafestRouteFallback); + var note = Assert.Single(result.Findings); + Assert.Contains("raises the head", note.Message); + Assert.Equal(0, note.OtherSourceOrdinal); // The wall. + Assert.Equal(new[] { false, false, true }, + result.ProposedOrder.Select(p => HeadRaise.IsMarked(p.CopyProgram()))); + Assert.Contains(proposal.Describe("in"), line => line.Contains("1 rapid raises the head")); + + Assert.Equal(CuttingCommitStatus.Applied, proposal.Apply().Status); + Assert.True(HeadRaise.IsMarked(plate.Parts[2].Program)); + // The pre-post check accepts the raised crossing; nothing else crosses. + Assert.DoesNotContain(PostVerificationAnalyzer.Analyze(nest, Vector.Zero).Findings, + f => f.Kind == PostVerificationKind.RapidCrossing); + } + + [Fact] + public void FreeOrder_CutsAroundTheWall_WithoutRaisingTheHead() + { + var (_, plate) = WallPlate(); + + var proposal = CuttingPlanBatch.Capture([plate], ExplicitContourTests.Parameters(), preservePartOrder: false).Plan(); + var result = proposal.Plates[0].Result; + + Assert.True(proposal.Plates[0].IsReady, string.Join("\n", proposal.Describe("in"))); + Assert.Equal(0, result.HeadRaises); + Assert.All(result.ProposedOrder, p => Assert.False(HeadRaise.IsMarked(p.CopyProgram()))); + } + + [Fact] + public void StrictPlan_NeverMarksARapid() + { + var (_, plate) = WallPlate(); + + var result = CuttingPlanService.Plan(CuttingPlanRequest.ForPlate(plate, + confirmedParameters: ExplicitContourTests.Parameters(), preservePartOrder: true)); + + Assert.NotEqual(CuttingPlanStatus.Ready, result.Status); + Assert.Equal(0, result.HeadRaises); + } + + [Fact] + public void Checker_SetsARaisedRapidsCrossingsApart() + { + var wall = LeadPathValidationTests.Rectangle(3, 0, 5, 22); + var rapid = new Program(); + rapid.Codes.Add(new Comment(HeadRaise.Marker)); + rapid.MoveTo(8, 11); + rapid.LineTo(8, 12); + var checker = new ReleasedContourState(reportMissingLeadIns: false); + checker.Check(ExecutionMotionReader.Read(wall, Vector.Zero, null, default), null, 1); + + var execution = ExecutionMotionReader.Read(rapid, Vector.Zero, new Vector(0, 11), default); + var (strict, _, raised) = checker.Check(execution, new Vector(0, 11), 2, false, null, default); + + Assert.True(execution.Motions[0].HeadRaised); + Assert.Equal(1, execution.Motions[0].Code); + Assert.Empty(strict); + Assert.Contains(raised, f => f.Kind == PostVerificationKind.RapidCrossing && f.OtherPartNumber == 1); + } + + [Fact] + public void Marker_MustBeFollowedByARapid() + { + var program = new Program(); + program.Codes.Add(new Comment(HeadRaise.Marker)); + program.LineTo(1, 1); + + Assert.Throws(() => HeadRaise.RaisedMask(program.Codes)); + Assert.Throws(() => ExecutionMotionReader.Read(program, Vector.Zero, null, default)); + } + + [Fact] + public void Mark_CopiesTheProgramWithAMarkerBeforeEachRapid() + { + var program = LeadPathValidationTests.Rectangle(0, 0, 2, 2); + + var marked = HeadRaise.Mark(program, [0]); + + Assert.False(HeadRaise.IsMarked(program)); + Assert.True(HeadRaise.IsMarker(marked.Codes[0])); + Assert.IsType(marked.Codes[1]); + Assert.Throws(() => HeadRaise.Mark(marked, [1])); // Already marked. + Assert.Throws(() => HeadRaise.Mark(program, [1])); // Not a rapid. + } + + // Plate order: the wall, the square left of it, the square right of it. + private static (Nest Nest, Plate Plate) WallPlate() + { + var nest = new Nest(); + var plate = nest.CreatePlate(); + plate.Size = new Size(40, 40); + plate.Parts.Add(new Part(new Drawing("wall", LeadPathValidationTests.Rectangle(0, 0, 2, 22)), new Vector(5, 1))); + plate.Parts.Add(new Part(new Drawing("left", LeadPathValidationTests.Rectangle(0, 0, 2, 2)), new Vector(1, 11))); + plate.Parts.Add(new Part(new Drawing("right", LeadPathValidationTests.Rectangle(0, 0, 2, 2)), new Vector(9, 11))); + return (nest, plate); + } +} diff --git a/OpenNest.Tests/CuttingPlanning/SafestRouteFallbackTests.cs b/OpenNest.Tests/CuttingPlanning/SafestRouteFallbackTests.cs index 3961d701..3701a027 100644 --- a/OpenNest.Tests/CuttingPlanning/SafestRouteFallbackTests.cs +++ b/OpenNest.Tests/CuttingPlanning/SafestRouteFallbackTests.cs @@ -9,9 +9,10 @@ namespace OpenNest.Tests.CuttingPlanning; public class SafestRouteFallbackTests { [Fact] - public void KeptOrderThroughAWall_OffersTheSafestRouteAsAnUnverifiedPlan() + public void KeptOrderThroughAWall_IntoALockedPart_OffersTheSafestRouteAsAnUnverifiedPlan() { - var plate = WalledPlate(); + // The rapid into a locked program cannot be marked to raise the head, so it stays a finding. + var plate = WalledPlate(lockRight: true); var proposal = CuttingPlanBatch.Capture([plate], ExplicitContourTests.Parameters(), preservePartOrder: true).Plan(); var planned = Assert.Single(proposal.Plates); @@ -22,6 +23,7 @@ public class SafestRouteFallbackTests Assert.False(planned.HasOnlyFixedLeadWarnings); Assert.False(planned.SearchLimitReached); Assert.Equal(plate.Parts, planned.Result.ProposedOrder.Select(p => p.SourcePart)); + Assert.Equal(0, planned.Result.HeadRaises); // Only the rapid from the left square to the right one has to cross the cut bar. var crossing = Assert.Single(planned.Result.Findings, f => f.Kind == PostVerificationKind.RapidCrossing); Assert.Equal(2, crossing.SourceOrdinal); @@ -37,11 +39,11 @@ public class SafestRouteFallbackTests [Fact] public void SafestRoute_AppliesOnlyWithExplicitAcceptance() { - var plate = WalledPlate(); + var plate = WalledPlate(lockRight: true); var proposal = CuttingPlanBatch.Capture([plate], ExplicitContourTests.Parameters(), preservePartOrder: true).Plan(); Assert.Equal(CuttingCommitStatus.InvalidInput, proposal.Apply().Status); - Assert.All(plate.Parts, part => Assert.False(part.HasManualLeadIns)); + Assert.All(plate.Parts.Take(2), part => Assert.False(part.HasManualLeadIns)); Assert.Equal(CuttingCommitStatus.Applied, proposal.Apply(acceptWarnings: true).Status); Assert.All(plate.Parts, part => Assert.True(part.HasManualLeadIns)); @@ -55,6 +57,7 @@ public class SafestRouteFallbackTests var planned = Assert.Single(proposal.Plates); Assert.True(planned.IsReady); Assert.False(planned.Result.IsSafestRouteFallback); + Assert.Equal(0, planned.Result.HeadRaises); } [Fact] @@ -104,13 +107,16 @@ public class SafestRouteFallbackTests // A tall bar between two squares, in the order bar, left, right: once the bar is cut every // straight rapid from the left square to the right one crosses it. Cut last, it crosses nothing. - private static Plate WalledPlate() + private static Plate WalledPlate(bool lockRight = false) { var plate = new Nest().CreatePlate(); plate.Size = new Size(60, 60); plate.Parts.Add(new Part(new Drawing("bar", Rectangle(1, 50)), new Vector(25, 2))); plate.Parts.Add(new Part(new Drawing("left", ExplicitContourTests.Square(false)), new Vector(5, 20))); - plate.Parts.Add(new Part(new Drawing("right", ExplicitContourTests.Square(false)), new Vector(36, 20))); + var right = new Part(new Drawing("right", ExplicitContourTests.Square(false)), new Vector(36, 20)); + if (lockRight) + Assert.True(right.RestoreLeadInProgram((Program)right.Program.Clone(), true)); + plate.Parts.Add(right); return plate; } diff --git a/OpenNest/Forms/CuttingInspectionPanel.cs b/OpenNest/Forms/CuttingInspectionPanel.cs index e232acab..44e2a2f6 100644 --- a/OpenNest/Forms/CuttingInspectionPanel.cs +++ b/OpenNest/Forms/CuttingInspectionPanel.cs @@ -909,7 +909,10 @@ internal sealed class CuttingInspectionPanel : UserControl var order = planned.KeptCurrentOrder ? "current order kept (no better order found)" : planned.OrderChanged ? "new part order" : "part order unchanged"; var rapid = planned.Result.RapidDistance.ToString("0.#", CultureInfo.CurrentCulture); - return $"{name}: {Count(planned.PartCount, "part")}, {order}, {rapid} {UnitsHelper.GetShortString(units)} of rapids."; + var raises = planned.Result.HeadRaises == 0 ? "" + : $" {Count(planned.Result.HeadRaises, "rapid")} must raise the head over cut parts (listed below)."; + return $"{name}: {Count(planned.PartCount, "part")}, {order}, {rapid} {UnitsHelper.GetShortString(units)} of rapids." + + raises; } if (planned.CanApplyWithWarnings) return $"{name}: UNVERIFIED. Check its lead-ins and cut order before applying."; diff --git a/Posts/OpenNest.Posts.Cincinnati/CincinnatiFeatureWriter.cs b/Posts/OpenNest.Posts.Cincinnati/CincinnatiFeatureWriter.cs index 39dbd8dc..149f9d9a 100644 --- a/Posts/OpenNest.Posts.Cincinnati/CincinnatiFeatureWriter.cs +++ b/Posts/OpenNest.Posts.Cincinnati/CincinnatiFeatureWriter.cs @@ -31,6 +31,9 @@ public sealed class FeatureContext /// public double? RapidDistance { get; set; } + /// True when the rapid to the next pierce is marked to raise the head (). + public bool NextRapidRaised { get; set; } + /// /// Part location on the plate. Added to all output X/Y coordinates /// so part-relative programs become plate-absolute under G90. @@ -342,7 +345,7 @@ public sealed class CincinnatiFeatureWriter private void WriteM47(TextWriter writer, FeatureContext ctx) { - var line = CincinnatiHeadRaise.Line(_config, ctx.IsExteriorFeature, ctx.RapidDistance); + var line = CincinnatiHeadRaise.Line(_config, ctx.IsExteriorFeature, ctx.RapidDistance, ctx.NextRapidRaised); if (line != null) writer.WriteLine(line); } diff --git a/Posts/OpenNest.Posts.Cincinnati/CincinnatiHeadRaise.cs b/Posts/OpenNest.Posts.Cincinnati/CincinnatiHeadRaise.cs index 171fbf21..fc9f7534 100644 --- a/Posts/OpenNest.Posts.Cincinnati/CincinnatiHeadRaise.cs +++ b/Posts/OpenNest.Posts.Cincinnati/CincinnatiHeadRaise.cs @@ -1,3 +1,5 @@ +using OpenNest.CNC; + namespace OpenNest.Posts.Cincinnati; /// @@ -7,11 +9,18 @@ internal static class CincinnatiHeadRaise { /// True when the feature just cut is a part exterior. /// Travel to the next pierce; null when unknown. + /// + /// True when Plan Cutting marked the rapid to raise the head over parts already cut + /// (): it always gets a raise the operator cannot skip. + /// /// The block to write, or null for no head raise. - internal static string Line(CincinnatiPostConfig config, bool isExterior, double? rapidDistance) + internal static string Line(CincinnatiPostConfig config, bool isExterior, double? rapidDistance, + bool raised = false) { if (IsSafetyRapid(config, rapidDistance)) return SafetyLine(config); + if (raised) + return "M47"; var mode = isExterior ? config.ExteriorM47 : config.InteriorM47; return mode switch diff --git a/Posts/OpenNest.Posts.Cincinnati/CincinnatiPartSubprogramWriter.cs b/Posts/OpenNest.Posts.Cincinnati/CincinnatiPartSubprogramWriter.cs index 299713ba..d069eacb 100644 --- a/Posts/OpenNest.Posts.Cincinnati/CincinnatiPartSubprogramWriter.cs +++ b/Posts/OpenNest.Posts.Cincinnati/CincinnatiPartSubprogramWriter.cs @@ -97,6 +97,7 @@ public sealed class CincinnatiPartSubprogramWriter RapidDistance = isLastFeature ? null : FeatureUtils.EndPoint(codes).DistanceTo(FeatureUtils.StartPoint(ordered[i + 1].codes)), + NextRapidRaised = !isLastFeature && FeatureUtils.IsRaised(ordered[i + 1].codes), }; _featureWriter.Write(w, ctx); diff --git a/Posts/OpenNest.Posts.Cincinnati/CincinnatiPostProcessor.cs b/Posts/OpenNest.Posts.Cincinnati/CincinnatiPostProcessor.cs index 5c76fa63..84d0736f 100644 --- a/Posts/OpenNest.Posts.Cincinnati/CincinnatiPostProcessor.cs +++ b/Posts/OpenNest.Posts.Cincinnati/CincinnatiPostProcessor.cs @@ -104,6 +104,8 @@ namespace OpenNest.Posts.Cincinnati { // Refuse before writing anything: a head-locked overcut needs the lock codes. HeadHeightLock.EnsurePostable(nest, Config.HasHeadHeightLockCodes(), Name); + // M47 raises the head before a marked rapid; the markers must be well formed. + HeadRaise.EnsurePostable(nest, true, Name); // 1. Create variable manager and register standard variables var vars = CreateVariableManager(); @@ -263,6 +265,7 @@ namespace OpenNest.Posts.Cincinnati // Refuse before creating the file, so a refusal never empties an existing program. DisplayPerimeterTail.EnsurePostable(nest); HeadHeightLock.EnsurePostable(nest, Config.HasHeadHeightLockCodes(), Name); + HeadRaise.EnsurePostable(nest, true, Name); using var fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write); Post(nest, fs); } diff --git a/Posts/OpenNest.Posts.Cincinnati/CincinnatiSheetWriter.cs b/Posts/OpenNest.Posts.Cincinnati/CincinnatiSheetWriter.cs index a532bafb..fc09dc21 100644 --- a/Posts/OpenNest.Posts.Cincinnati/CincinnatiSheetWriter.cs +++ b/Posts/OpenNest.Posts.Cincinnati/CincinnatiSheetWriter.cs @@ -127,6 +127,9 @@ public sealed class CincinnatiSheetWriter /// Where the tool leaves from: back at the corner after a sub-program call. public Vector Exit { get; init; } + + /// Whether the rapid into this item raises the head (). + public bool Raised { get; init; } } private static List BuildItems( @@ -159,6 +162,7 @@ public sealed class CincinnatiSheetWriter Start = corner + FeatureUtils.StartPoint(subFeatures[0].codes), End = corner + FeatureUtils.EndPoint(subFeatures[^1].codes), Exit = corner, + Raised = FeatureUtils.IsRaised(subFeatures[0].codes), } ); continue; @@ -182,6 +186,7 @@ public sealed class CincinnatiSheetWriter Start = start, End = end, Exit = end, + Raised = FeatureUtils.IsRaised(codes), } ); } @@ -228,7 +233,8 @@ public sealed class CincinnatiSheetWriter i, partName, rapidDistance, - isLastFeature + isLastFeature, + next?.Raised == true ); continue; } @@ -266,6 +272,7 @@ public sealed class CincinnatiSheetWriter CutDistance = FeatureUtils.ComputeCutDistance(codes), SheetDiagonal = sheetDiagonal, RapidDistance = rapidDistance, + NextRapidRaised = next?.Raised == true, PartLocation = part.Location, UserVariableMapping = userVarMapping, DrawingId = part.BaseDrawing.Id, @@ -294,7 +301,8 @@ public sealed class CincinnatiSheetWriter int index, string partName, double? rapidDistance, - bool isLastPart + bool isLastPart, + bool nextRaised ) { var x = _fmt.FormatCoord(item.Entry.X); @@ -321,7 +329,7 @@ public sealed class CincinnatiSheetWriter // One head raise covers the rapid back and the rapid on. The part is complete, // so the raise follows the exterior M47 mode. - var raise = CincinnatiHeadRaise.Line(_config, true, rapidDistance); + var raise = CincinnatiHeadRaise.Line(_config, true, rapidDistance, nextRaised); if (raise != null) w.WriteLine(raise); diff --git a/Posts/OpenNest.Posts.Cincinnati/FeatureUtils.cs b/Posts/OpenNest.Posts.Cincinnati/FeatureUtils.cs index c8c5d9fd..eda2bd26 100644 --- a/Posts/OpenNest.Posts.Cincinnati/FeatureUtils.cs +++ b/Posts/OpenNest.Posts.Cincinnati/FeatureUtils.cs @@ -30,8 +30,20 @@ public static class FeatureUtils features.Add(new List { code }); current = null; } + else if (HeadRaise.IsMarker(code)) + { + // The marker opens the feature its rapid starts, so it stays with that rapid. + if (current != null) + features.Add(current); + current = new List { code }; + } else if (code is RapidMove) { + if (current is [var marker] && HeadRaise.IsMarker(marker)) + { + current.Add(code); + continue; + } if (current != null) features.Add(current); current = new List { code }; @@ -49,6 +61,9 @@ public static class FeatureUtils return features; } + /// Whether the rapid that starts raises the head (). + public static bool IsRaised(List feature) => feature.Count > 0 && HeadRaise.IsMarker(feature[0]); + /// /// Classifies features as etch or cut and orders etch features before cut features. /// diff --git a/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberContourExtractor.cs b/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberContourExtractor.cs index ee1a27b2..67d277c3 100644 --- a/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberContourExtractor.cs +++ b/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberContourExtractor.cs @@ -42,6 +42,9 @@ namespace OpenNest.Posts.CincinnatiCIFiber /// Lock is true and unlocking otherwise. /// public List<(int Before, bool Lock)> HeadLocks { get; } = new(); + + /// Whether the rapid to the pierce raises the head over parts already cut (). + public bool Raised { get; set; } } /// @@ -95,6 +98,7 @@ namespace OpenNest.Posts.CincinnatiCIFiber } CIFiberContour current = null; + var raise = false; void Flush() { @@ -108,6 +112,13 @@ namespace OpenNest.Posts.CincinnatiCIFiber if (code is Motion suppressed && suppressed.Suppressed) continue; + // A marker raises the head for the rapid straight after it. + if (HeadRaise.IsMarker(code)) + { + raise = true; + continue; + } + if (HeadHeightLock.IsLock(code) || HeadHeightLock.IsUnlock(code)) { current ??= new CIFiberContour { Pierce = origin }; @@ -119,7 +130,8 @@ namespace OpenNest.Posts.CincinnatiCIFiber { case RapidMove rapid: Flush(); - current = new CIFiberContour { Pierce = rapid.EndPoint + origin }; + current = new CIFiberContour { Pierce = rapid.EndPoint + origin, Raised = raise }; + raise = false; break; case SubProgramCall call: diff --git a/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberPostConfig.cs b/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberPostConfig.cs index bf0aa589..070b864c 100644 --- a/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberPostConfig.cs +++ b/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberPostConfig.cs @@ -187,6 +187,20 @@ namespace OpenNest.Posts.CincinnatiCIFiber [PostSetting(MacrosSection, 8)] public string HeadHeightUnlockCode { get; set; } = ""; + /// + /// Block that raises the head before a rapid Plan Cutting marked to pass over parts already + /// cut (). + /// + [DisplayName("Head raise")] + [Description( + "Written before a rapid that must pass over parts already cut with the head raised. Blank = not set: a nest with such rapids is refused." + )] + [PostSetting(MacrosSection, 9)] + public string HeadRaiseCode { get; set; } = ""; + + /// Whether the head-raise block is set. + public bool HasHeadRaiseCode() => !string.IsNullOrWhiteSpace(HeadRaiseCode); + /// Whether both head-height lock blocks are set. public bool HasHeadHeightLockCodes() => !string.IsNullOrWhiteSpace(HeadHeightLockCode) && !string.IsNullOrWhiteSpace(HeadHeightUnlockCode); diff --git a/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberProgramWriter.cs b/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberProgramWriter.cs index 9072b9c0..0bde4ded 100644 --- a/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberProgramWriter.cs +++ b/Posts/OpenNest.Posts.CincinnatiCIFiber/CIFiberProgramWriter.cs @@ -74,6 +74,7 @@ namespace OpenNest.Posts.CincinnatiCIFiber throw new ArgumentNullException(nameof(nest)); HeadHeightLock.EnsurePostable(nest, _config.HasHeadHeightLockCodes(), "Cincinnati CI Fiber"); + HeadRaise.EnsurePostable(nest, _config.HasHeadRaiseCode(), "Cincinnati CI Fiber"); Write(nest, PostedSheets(nest), 1, w); } @@ -89,6 +90,7 @@ namespace OpenNest.Posts.CincinnatiCIFiber throw new ArgumentNullException(nameof(sheet)); HeadHeightLock.EnsurePostable(nest, _config.HasHeadHeightLockCodes(), "Cincinnati CI Fiber"); + HeadRaise.EnsurePostable(nest, _config.HasHeadRaiseCode(), "Cincinnati CI Fiber"); Write(nest, new[] { sheet }, sheetNumber, w); } @@ -239,12 +241,20 @@ namespace OpenNest.Posts.CincinnatiCIFiber return contourNumber; } + // A rapid marked to pass over parts already cut is made with the head raised. + private void WriteRapidToPierce(CIFiberContour contour, TextWriter w) + { + if (contour.Raised) + CIFiberFormatter.Line(w, _config.HeadRaiseCode); + CIFiberFormatter.Line(w, $"G0X{Fmt(contour.Pierce.X)}Y{Fmt(contour.Pierce.Y)}"); + } + private void WriteContour(CIFiberContour contour, bool isExterior, int contourNumber, TextWriter w) { CIFiberFormatter.Line(w, $"N{contourNumber}:"); CIFiberFormatter.Line(w, SkippableLine(_config.LayerCancel)); CIFiberFormatter.Line(w, $"V.E.R3={contourNumber}"); - CIFiberFormatter.Line(w, $"G0X{Fmt(contour.Pierce.X)}Y{Fmt(contour.Pierce.Y)}"); + WriteRapidToPierce(contour, w); if (contour.LeadIn == null) throw new InvalidOperationException( @@ -311,7 +321,7 @@ namespace OpenNest.Posts.CincinnatiCIFiber CIFiberFormatter.Line(w, $"N{contourNumber}:"); CIFiberFormatter.Line(w, SkippableLine(_config.LayerCancel)); CIFiberFormatter.Line(w, $"V.E.R3={contourNumber}"); - CIFiberFormatter.Line(w, $"G0X{Fmt(contour.Pierce.X)}Y{Fmt(contour.Pierce.Y)}"); + WriteRapidToPierce(contour, w); CIFiberFormatter.Line(w, SkippableLine(_config.LayerExteriorLeadin)); CIFiberFormatter.Line(w, SkippableLine(_config.LayerCut)); diff --git a/docs/cincinnati-ci-fiber-post-output.md b/docs/cincinnati-ci-fiber-post-output.md index c5f7e519..81692776 100644 --- a/docs/cincinnati-ci-fiber-post-output.md +++ b/docs/cincinnati-ci-fiber-post-output.md @@ -55,6 +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. +- A rapid Plan Cutting marked to pass over parts already cut (see + [the cutting planner](cutting-planner.md#safest-route-fallback-when-the-search-runs-out)) + writes the `Head raise` block just before its `G0`. The block is blank by default, + and a nest with a marked rapid is refused while it is blank. Which block raises the + head on the CI Fiber (whether `L "L0"` without block delete does) is unconfirmed; + enter and verify it on the machine. - Hole subprogram geometry is inlined. Suppressed moves and, by default, wholly scribe contours are omitted. - Files use UTF-8 without a BOM and CRLF lines. Default accuracy is three decimal diff --git a/docs/cincinnati-post-output.md b/docs/cincinnati-post-output.md index de7f2fa0..0b87782c 100644 --- a/docs/cincinnati-post-output.md +++ b/docs/cincinnati-post-output.md @@ -138,10 +138,15 @@ in this order (`CincinnatiHeadRaise`): 1. `M47 P (Safety Headraise)` when the rapid travel to the next pierce exceeds `SafetyHeadraiseRapidDistance` (program units, default - 12) and both settings are set. Long rapids cross more of a warped sheet, so - the head goes higher; which part or drawing comes next does not matter. - Unknown travel (a hole call's rapid inside a part sub-program) never takes it. -2. Otherwise the M47 mode for the feature just cut: `ExteriorM47` after a + 12) and both settings are set. Long rapids cross more of a warped sheet, and + height sensing cannot follow it at rapid speed, so the head goes higher; which + part or drawing comes next does not matter. Unknown travel (a hole call's rapid + inside a part sub-program) never takes it. +2. Otherwise `M47` when Plan Cutting marked the rapid to pass over parts already + cut (a `HEAD RAISE` comment before it; see + [the cutting planner](cutting-planner.md#safest-route-fallback-when-the-search-runs-out)), + whatever the M47 mode: block delete must not skip it. +3. Otherwise the M47 mode for the feature just cut: `ExteriorM47` after a part's exterior, `InteriorM47` after anything else. - `Always`: `M47`. - `BlockDelete`: `/M47`; the operator can skip it with block delete (§5.6). @@ -160,6 +165,11 @@ not vendor-documented behavior. Hole calls (see below) write `M47`, or the safety raise, after `G52 X0 Y0` regardless of the M47 mode. +**Use smart rapids** (`G121`) is off by default. With it on, the control replaces +each single `G0` between cuts with a blended high-feed move whose path is curved +and may leave the straight line (§2.121), so Plan Cutting's and pre-post +verification's straight-line rapid checks no longer describe the path cut. + ## Sub-program call patterns There are two distinct call-site patterns, depending on whether the call diff --git a/docs/cutting-planner.md b/docs/cutting-planner.md index 23dfd123..3467cf45 100644 --- a/docs/cutting-planner.md +++ b/docs/cutting-planner.md @@ -816,9 +816,24 @@ motions into material, cut-order and nested-lead conflicts and incomplete checks rapids across cut contours, then everything else (missing lead-ins, pierce zones, support). It gets twice the plate's expansion budget, so the planning effort scales it too. +Before replay, each rapid of the walk that still passes over parts already cut is marked to +raise the head (`RaisedRapids`, `OpenNest.CNC.HeadRaise`): a `HEAD RAISE` comment directly +before the rapid in the part's program, which saves with the nest. This is the only place a +raise is added, so a plate the strict search can plan never gets one: it is the last resort for +a route no search kept head-down, not a shortcut. Only rapids the planner chose in a +regenerated program are marked; a rapid into or inside a locked program, a cut-off or a hole +sub-program keeps its crossing as a finding. The checker sets a raised rapid's crossings apart +instead of reporting them, in replay and in pre-post verification alike. + The batch walks both the free order and the current order, replays each against its captured -input with fresh checks, and keeps the one with the lower severity, then the shorter rapid -travel. A route that passes every check on replay is an ordinary `Ready` proposal. Otherwise +input with fresh checks, and keeps the one with the lower severity, then fewer head raises, then +the shorter rapid travel; a route that passes every check without a raise is taken at once. +A route that passes every check on replay is an ordinary `Ready` proposal. One with raises +names them in its summary ("N rapids raise the head") and lists each as an advisory note naming +the cut part it passes over (`CuttingPlanResult.HeadRaises`). Posts raise the head before every +marked rapid: the Cincinnati CL post writes `M47` (or its safety raise for a long rapid) whatever +the M47 mode, and the CI Fiber post writes its **Head raise** block, refusing a marked nest while +that block is blank, as it does for the head-height lock. Otherwise the result is `BestEffort` with `IsSafestRouteFallback`, listing every violation; the summary calls it the safest route found, gives the number of checks it breaks and its rapid travel, and Apply requires explicit warning acceptance like any unverified plan. The fallback never diff --git a/docs/post-verification.md b/docs/post-verification.md index 255fe806..ed5fb5d6 100644 --- a/docs/post-verification.md +++ b/docs/post-verification.md @@ -88,7 +88,10 @@ shows the first three check categories, even when there are no findings: height/retracts are not modeled, so inspect the emitted route and machine setup. A clamp whose footprint covers the program start point warns on every posting attempt by design; there is no exemption for the first rapid and no persisted - bypass. + bypass. A rapid Plan Cutting marked to raise the head (see + [the safest-route fallback](cutting-planner.md#safest-route-fallback-when-the-search-runs-out)) + passes over cut contours with the head up, so its contour crossings are not warnings; its + clamp crossings still are. - **Fixed leads:** Plan Cutting accepts fixed emissions as given and only warns (see [cutting planner](cutting-planner.md#fixed-emissions-warn)), so posting checks them again: every lead-in and lead-out of a locked program, and of each contour a part's