refactor(sequencing): remove the automatic part sequencers

The cut order comes from Plan Cutting or the user (Manual Sequence,
Sequence by Path). The PEP-era sequencers (Right/Left/Bottom Side, Edge
Start, Least Code, Advanced) and the parked heat-aware one predate the
cutting planner. Only Auto Sequence still ran one (Least Code), and its
order was replaced as soon as the plate was planned.

Removes Plate > Sequence Parts > Auto Sequence and Nest > Auto Sequence
All Plates, the sequencers and their factory, and the old PlateProcessor
with its rapid planners, which only tests used. The cutoff ordering
rules stay (OrderCutOffsFirst, PlaceCutOffs) and are now tested on
given routes. SequenceMethod and SequenceParameters stay so saved
cutting settings keep loading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-12-02 10:43:46 -05:00
1 parent 0a2b1c64cf
commit 9ea495edca
43 files changed
+111 -2048

No files matched your search

-18
View File
@@ -1,18 +0,0 @@
using System.Collections.Generic;
using OpenNest.CNC;
using OpenNest.Engine.RapidPlanning;
namespace OpenNest.Engine
{
public class PlateProcessingResult
{
public List<ProcessedPart> Parts { get; init; }
}
public readonly struct ProcessedPart
{
public Part Part { get; init; }
public Program ProcessedProgram { get; init; }
public RapidPath RapidPath { get; init; }
}
}
-156
View File
@@ -1,156 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using OpenNest.CNC;
using OpenNest.CNC.CuttingStrategy;
using OpenNest.Engine.RapidPlanning;
using OpenNest.Engine.Sequencing;
using OpenNest.Geometry;
namespace OpenNest.Engine
{
public class PlateProcessor
{
public IPartSequencer Sequencer { get; set; }
public ContourCuttingStrategy CuttingStrategy { get; set; }
public IRapidPlanner RapidPlanner { get; set; }
public PlateProcessingResult Process(Plate plate)
{
var sequenced = Sequencer.Sequence(plate.Parts.ToList(), plate);
var exitPoint = PlateHelper.GetExitPoint(plate);
// Pass 1: process each part to collect pierce points
var piercePoints = new Vector[sequenced.Count];
var currentPoint = exitPoint;
for (var i = 0; i < sequenced.Count; i++)
{
var part = sequenced[i].Part;
if (!part.HasManualLeadIns && CuttingStrategy != null)
{
var localApproach = ToPartLocal(currentPoint, part);
var result = CuttingStrategy.Apply(part.Program, localApproach);
piercePoints[i] = ToPlateSpace(GetProgramStartPoint(result.Program), part);
currentPoint = ToPlateSpace(result.LastCutPoint, part);
}
else
{
piercePoints[i] = ToPlateSpace(GetProgramStartPoint(part.Program), part);
currentPoint = ToPlateSpace(GetProgramEndPoint(part.Program), part);
}
}
// Pass 2: re-process with next part's start point for perimeter lead-in refinement
var results = new List<ProcessedPart>(sequenced.Count);
var cutAreas = new List<Shape>();
currentPoint = exitPoint;
for (var i = 0; i < sequenced.Count; i++)
{
var part = sequenced[i].Part;
var localApproach = ToPartLocal(currentPoint, part);
Program processedProgram;
Vector lastCutLocal;
if (!part.HasManualLeadIns && CuttingStrategy != null)
{
CuttingResult cuttingResult;
if (i + 1 < sequenced.Count)
{
var nextStart = ToPartLocal(piercePoints[i + 1], part);
cuttingResult = CuttingStrategy.Apply(
part.Program,
localApproach,
nextStart
);
}
else
{
cuttingResult = CuttingStrategy.Apply(part.Program, localApproach);
}
processedProgram = cuttingResult.Program;
lastCutLocal = cuttingResult.LastCutPoint;
}
else
{
processedProgram = part.Program;
lastCutLocal = GetProgramEndPoint(part.Program);
}
var pierceLocal = GetProgramStartPoint(processedProgram);
var piercePoint = ToPlateSpace(pierceLocal, part);
var rapidPath = RapidPlanner.Plan(currentPoint, piercePoint, cutAreas);
results.Add(
new ProcessedPart
{
Part = part,
ProcessedProgram = processedProgram,
RapidPath = rapidPath,
}
);
var perimeter = GetPartPerimeter(part);
if (perimeter != null)
cutAreas.Add(perimeter);
currentPoint = ToPlateSpace(lastCutLocal, part);
}
return new PlateProcessingResult { Parts = results };
}
private static Vector ToPartLocal(Vector platePoint, Part part)
{
return platePoint - part.Location;
}
private static Vector ToPlateSpace(Vector localPoint, Part part)
{
return localPoint + part.Location;
}
private static Vector GetProgramStartPoint(Program program)
{
if (program.Codes.Count == 0)
return Vector.Zero;
var first = program.Codes[0];
if (first is Motion motion)
return motion.EndPoint;
return Vector.Zero;
}
private static Vector GetProgramEndPoint(Program program)
{
for (var i = program.Codes.Count - 1; i >= 0; i--)
{
if (program.Codes[i] is Motion motion)
return motion.EndPoint;
}
return Vector.Zero;
}
private static Shape GetPartPerimeter(Part part)
{
var entities = part.Program.ToGeometry();
if (entities == null || entities.Count == 0)
return null;
var profile = new ShapeProfile(entities);
var perimeter = profile.Perimeter;
if (perimeter == null || perimeter.Entities.Count == 0)
return null;
perimeter.Offset(part.Location);
return perimeter;
}
}
}
@@ -1,36 +0,0 @@
using System.Collections.Generic;
using OpenNest.Geometry;
namespace OpenNest.Engine.RapidPlanning
{
public class DirectRapidPlanner : IRapidPlanner
{
public RapidPath Plan(Vector from, Vector to, IReadOnlyList<Shape> cutAreas)
{
var travelLine = new Line(from, to);
foreach (var cutArea in cutAreas)
{
if (TravelLineIntersectsShape(travelLine, cutArea))
{
return new RapidPath { HeadUp = true, Waypoints = new List<Vector>() };
}
}
return new RapidPath { HeadUp = false, Waypoints = new List<Vector>() };
}
private static bool TravelLineIntersectsShape(Line travelLine, Shape shape)
{
foreach (var entity in shape.Entities)
{
if (entity is Line edge)
{
if (travelLine.Intersects(edge, out _))
return true;
}
}
return false;
}
}
}
@@ -1,10 +0,0 @@
using System.Collections.Generic;
using OpenNest.Geometry;
namespace OpenNest.Engine.RapidPlanning
{
public interface IRapidPlanner
{
RapidPath Plan(Vector from, Vector to, IReadOnlyList<Shape> cutAreas);
}
}
@@ -1,11 +0,0 @@
using System.Collections.Generic;
using OpenNest.Geometry;
namespace OpenNest.Engine.RapidPlanning
{
public readonly struct RapidPath
{
public bool HeadUp { get; init; }
public List<Vector> Waypoints { get; init; }
}
}
@@ -1,13 +0,0 @@
using System.Collections.Generic;
using OpenNest.Geometry;
namespace OpenNest.Engine.RapidPlanning
{
public class SafeHeightRapidPlanner : IRapidPlanner
{
public RapidPath Plan(Vector from, Vector to, IReadOnlyList<Shape> cutAreas)
{
return new RapidPath { HeadUp = true, Waypoints = new List<Vector>() };
}
}
}
@@ -1,94 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using OpenNest.CNC.CuttingStrategy;
using OpenNest.Math;
namespace OpenNest.Engine.Sequencing
{
public class AdvancedSequencer : IPartSequencer
{
private readonly SequenceParameters _parameters;
public AdvancedSequencer(SequenceParameters parameters)
{
_parameters = parameters;
}
public List<SequencedPart> Sequence(IReadOnlyList<Part> parts, Plate plate)
{
if (parts.Count == 0)
return new List<SequencedPart>();
var exit = PlateHelper.GetExitPoint(plate);
// Group parts into rows by Y proximity
var rows = GroupIntoRows(parts, _parameters.MinDistanceBetweenRowsColumns);
// Sort rows bottom-to-top (ascending Y)
rows.Sort((a, b) => a.RowY.CompareTo(b.RowY));
// Determine initial direction based on exit point
var leftToRight = exit.X > plate.Size.Length * 0.5;
var result = new List<SequencedPart>(parts.Count);
foreach (var row in rows)
{
var sorted = leftToRight
? row.Parts.OrderBy(p => p.BoundingBox.Center.X).ToList()
: row.Parts.OrderByDescending(p => p.BoundingBox.Center.X).ToList();
foreach (var p in sorted)
result.Add(new SequencedPart { Part = p });
if (_parameters.AlternateRowsColumns)
leftToRight = !leftToRight;
}
return result;
}
private static List<PartRow> GroupIntoRows(IReadOnlyList<Part> parts, double minDistance)
{
// Sort parts by Y center
var sorted = parts.OrderBy(p => p.BoundingBox.Center.Y).ToList();
var rows = new List<PartRow>();
foreach (var part in sorted)
{
var y = part.BoundingBox.Center.Y;
var placed = false;
foreach (var row in rows)
{
if (System.Math.Abs(y - row.RowY) <= minDistance + Tolerance.Epsilon)
{
row.Parts.Add(part);
placed = true;
break;
}
}
if (!placed)
{
var row = new PartRow(y);
row.Parts.Add(part);
rows.Add(row);
}
}
return rows;
}
private class PartRow
{
public double RowY { get; }
public List<Part> Parts { get; } = new List<Part>();
public PartRow(double rowY)
{
RowY = rowY;
}
}
}
}
@@ -1,17 +0,0 @@
using System.Collections.Generic;
using System.Linq;
namespace OpenNest.Engine.Sequencing
{
public class BottomSideSequencer : IPartSequencer
{
public List<SequencedPart> Sequence(IReadOnlyList<Part> parts, Plate plate)
{
return parts
.OrderBy(p => p.Location.Y)
.ThenBy(p => p.Location.X)
.Select(p => new SequencedPart { Part = p })
.ToList();
}
}
}
@@ -1,44 +0,0 @@
using System.Collections.Generic;
using System.Linq;
namespace OpenNest.Engine.Sequencing
{
public class EdgeStartSequencer : IPartSequencer
{
public List<SequencedPart> Sequence(IReadOnlyList<Part> parts, Plate plate)
{
// Plate(width, length) stores Size with Width/Length swapped internally.
// Reconstruct the logical plate box using the BoundingBox origin and the
// corrected extents: Size.Length = X-extent, Size.Width = Y-extent.
var origin = plate.BoundingBox(false);
var plateBox = new OpenNest.Geometry.Box(
origin.X,
origin.Y,
plate.Size.Length,
plate.Size.Width
);
return parts
.OrderBy(p => MinEdgeDistance(p.BoundingBox.Center, plateBox))
.ThenBy(p => p.Location.X)
.Select(p => new SequencedPart { Part = p })
.ToList();
}
private static double MinEdgeDistance(
OpenNest.Geometry.Vector center,
OpenNest.Geometry.Box plateBox
)
{
var distLeft = center.X - plateBox.Left;
var distRight = plateBox.Right - center.X;
var distBottom = center.Y - plateBox.Bottom;
var distTop = plateBox.Top - center.Y;
return System.Math.Min(
System.Math.Min(distLeft, distRight),
System.Math.Min(distBottom, distTop)
);
}
}
}
@@ -1,97 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using OpenNest.CNC.Thermal;
using OpenNest.Geometry;
namespace OpenNest.Engine.Sequencing
{
/// <summary>
/// What the heat-aware order needs of one part: where its cut starts and ends, its cut extent
/// (where its heat goes) and how long the torch is on.
/// </summary>
internal readonly record struct HeatAwareItem(Vector Entry, Vector Exit, Box Extent, double TorchSeconds)
{
internal Vector Center => Extent.Center;
/// <summary>The heat's initial spread: a quarter of the extent's squared diagonal.</summary>
internal double Spread2 => (Extent.Length * Extent.Length + Extent.Width * Extent.Width) / 4;
}
/// <summary>
/// Orders parts forward from a start point: each next part is the dependency-ready one with the
/// least travel seconds plus <c>weight</c> times the estimated heat (°C) at its center when the
/// tool gets there, from a <see cref="HeatSpreadEstimate"/> of the parts already cut. So the
/// route leaves a hot zone, but only as far as it must. Without a thickness, or with no weight,
/// it is a nearest-neighbor order by travel. It ignores whether a move passes over parts already
/// cut; see docs/plate-heat-map.md#sequencing.
/// </summary>
internal static class HeatAwareOrder
{
/// <param name="items">Every part's data, by ordinal.</param>
/// <param name="parts">The ordinals to order; prerequisites outside this set count as cut.</param>
/// <param name="start">The tool position before the first part.</param>
/// <param name="prerequisites">Ordinals that must come before each part; must be acyclic.</param>
/// <param name="done">Parts already cut, in order, from <paramref name="origin"/>: their heat
/// is laid down first. Null for none.</param>
/// <param name="origin">Where the tool was before <paramref name="done"/>.</param>
internal static int[] Plan(IReadOnlyList<HeatAwareItem> items, IReadOnlyList<int> parts, Vector start,
IReadOnlyList<IReadOnlyCollection<int>> prerequisites, ThermalParameters thermal, double weight,
CancellationToken token, IReadOnlyList<int> done = null, Vector? origin = null)
{
var estimate = new HeatSpreadEstimate(thermal ?? new ThermalParameters());
var heated = estimate.HasThickness && double.IsFinite(weight) && weight > 0;
var time = 0.0;
if (done is { Count: > 0 })
{
var position = origin ?? start;
foreach (var part in done)
{
var item = items[part];
time += estimate.TravelSeconds(position.DistanceTo(item.Entry)) + item.TorchSeconds;
estimate.Add(item.Center, item.Spread2, item.TorchSeconds, time);
position = item.Exit;
}
}
var pending = new HashSet<int>(parts);
var remaining = parts.ToList();
var order = new int[parts.Count];
var current = start;
for (var step = 0; step < order.Length; step++)
{
token.ThrowIfCancellationRequested();
var best = -1;
var bestCost = double.MaxValue;
foreach (var part in remaining)
{
if (prerequisites[part].Any(pending.Contains))
continue;
var item = items[part];
var travel = estimate.TravelSeconds(current.DistanceTo(item.Entry));
var cost = heated ? travel + weight * estimate.TemperatureAt(item.Center, time + travel) : travel;
// Strictly cheaper only, so ties keep the given order.
if (cost < bestCost)
{
best = part;
bestCost = cost;
}
}
if (best < 0)
throw new InvalidOperationException("Part prerequisites form a cycle.");
var chosen = items[best];
time += estimate.TravelSeconds(current.DistanceTo(chosen.Entry)) + chosen.TorchSeconds;
if (heated)
estimate.Add(chosen.Center, chosen.Spread2, chosen.TorchSeconds, time);
current = chosen.Exit;
order[step] = best;
pending.Remove(best);
remaining.Remove(best);
}
return order;
}
}
}
@@ -1,88 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using OpenNest.CNC;
using OpenNest.CNC.CuttingStrategy;
using OpenNest.CNC.Thermal;
using OpenNest.Converters;
using OpenNest.Geometry;
namespace OpenNest.Engine.Sequencing
{
/// <summary>
/// <see cref="SequenceMethod.HeatAware"/>: cuts forward from the plate's origin corner, each next
/// part the one with the least travel seconds plus <see cref="SequenceParameters.HeatWeight"/>
/// times the estimated heat where it is cut (<see cref="HeatAwareOrder"/>). Each part's cut
/// length, pierces, entry and exit come from its program as it stands. Cut-offs carry no heat
/// here and go last; <see cref="PlateSequencing.Apply(Plate, SequenceParameters, ThermalParameters)"/>
/// then moves each before the parts it crosses. Without a thickness the order is nearest neighbor.
/// Like every sequencer it returns the route exit-first, so the forward order comes back reversed.
/// </summary>
public class HeatAwareSequencer : IPartSequencer
{
private readonly SequenceParameters parameters;
private readonly ThermalParameters thermal;
/// <param name="thermal">The sheet's material and thickness; null orders by travel alone.</param>
public HeatAwareSequencer(SequenceParameters parameters, ThermalParameters thermal)
{
this.parameters = parameters;
this.thermal = thermal;
}
public List<SequencedPart> Sequence(IReadOnlyList<Part> parts, Plate plate)
{
if (parts.Count == 0)
return new List<SequencedPart>();
var heated = parts.Where(p => !p.BaseDrawing.IsCutOff).ToList();
var estimate = new HeatSpreadEstimate(thermal ?? new ThermalParameters());
var items = heated.Select(part => ItemOf(part, estimate)).ToArray();
var none = new IReadOnlyCollection<int>[items.Length];
System.Array.Fill(none, System.Array.Empty<int>());
var bounds = plate.BoundingBox(includeParts: false);
var order = HeatAwareOrder.Plan(items, Enumerable.Range(0, items.Length).ToArray(),
new Vector(bounds.X, bounds.Y), none, thermal, parameters.HeatWeight, CancellationToken.None);
var forward = order.Select(i => heated[i]).Concat(parts.Where(p => p.BaseDrawing.IsCutOff));
return forward.Reverse().Select(part => new SequencedPart { Part = part }).ToList();
}
private static HeatAwareItem ItemOf(Part part, HeatSpreadEstimate estimate)
{
var box = part.BoundingBox;
var entities = ConvertProgram.ToGeometry(DisplayPerimeterTail.WithoutTail(part.Program))
.Where(entity => entity is Line or Arc).ToList();
var length = 0.0;
var pierces = 0;
var torchOn = false;
Vector? entry = null;
var exit = box.Center;
foreach (var entity in entities)
{
var cuts = CutsMaterial(entity.Layer);
if (cuts)
{
length += entity.Length;
if (!torchOn)
pierces++;
entry ??= Start(entity) + part.Location;
exit = End(entity) + part.Location;
}
torchOn = cuts;
}
return entry is { } start
? new HeatAwareItem(start, exit, box, estimate.TorchSeconds(length, pierces))
: new HeatAwareItem(box.Center, box.Center, box, 0);
}
// Layers cut with the torch on (scribes etch, rapids and tabs travel head-up or uncut).
private static bool CutsMaterial(Layer layer) =>
layer == SpecialLayers.Cut || layer == SpecialLayers.Display || layer == SpecialLayers.Leadin
|| layer == SpecialLayers.Leadout || layer == SpecialLayers.Break;
private static Vector Start(Entity entity) => entity is Line line ? line.StartPoint : ((Arc)entity).StartPoint();
private static Vector End(Entity entity) => entity is Line line ? line.EndPoint : ((Arc)entity).EndPoint();
}
}
@@ -1,14 +0,0 @@
using System.Collections.Generic;
namespace OpenNest.Engine.Sequencing
{
public readonly struct SequencedPart
{
public Part Part { get; init; }
}
public interface IPartSequencer
{
List<SequencedPart> Sequence(IReadOnlyList<Part> parts, Plate plate);
}
}
@@ -1,142 +0,0 @@
using System.Collections.Generic;
using OpenNest.Math;
namespace OpenNest.Engine.Sequencing
{
public class LeastCodeSequencer : IPartSequencer
{
private readonly int _maxIterations;
public LeastCodeSequencer(int maxIterations = 100)
{
_maxIterations = maxIterations;
}
public List<SequencedPart> Sequence(IReadOnlyList<Part> parts, Plate plate)
{
if (parts.Count == 0)
return new List<SequencedPart>();
var exit = PlateHelper.GetExitPoint(plate);
var ordered = NearestNeighbor(parts, exit);
TwoOpt(ordered, exit);
var result = new List<SequencedPart>(ordered.Count);
foreach (var p in ordered)
result.Add(new SequencedPart { Part = p });
return result;
}
private static List<Part> NearestNeighbor(
IReadOnlyList<Part> parts,
OpenNest.Geometry.Vector exit
)
{
var remaining = new List<Part>(parts);
var ordered = new List<Part>(parts.Count);
var current = exit;
while (remaining.Count > 0)
{
var bestIdx = 0;
var bestDist = Distance(current, Center(remaining[0]));
for (var i = 1; i < remaining.Count; i++)
{
var d = Distance(current, Center(remaining[i]));
if (d < bestDist - Tolerance.Epsilon)
{
bestDist = d;
bestIdx = i;
}
}
var next = remaining[bestIdx];
ordered.Add(next);
remaining.RemoveAt(bestIdx);
current = Center(next);
}
return ordered;
}
private void TwoOpt(List<Part> ordered, OpenNest.Geometry.Vector exit)
{
var n = ordered.Count;
if (n < 3)
return;
for (var iter = 0; iter < _maxIterations; iter++)
{
var improved = false;
for (var i = 0; i < n - 1; i++)
{
for (var j = i + 1; j < n; j++)
{
var before = RouteDistance(ordered, exit);
Reverse(ordered, i, j);
var after = RouteDistance(ordered, exit);
if (after < before - Tolerance.Epsilon)
{
improved = true;
}
else
{
// Revert
Reverse(ordered, i, j);
}
}
}
if (!improved)
break;
}
}
/// <summary>
/// Computes the total distance of the route starting from exit through all parts.
/// </summary>
private static double RouteDistance(
List<Part> ordered,
OpenNest.Geometry.Vector exit
)
{
// Full route distance: exit -> ordered[0] -> ... -> ordered[n-1]
var total = 0.0;
var prev = exit;
foreach (var p in ordered)
{
var c = Center(p);
total += Distance(prev, c);
prev = c;
}
return total;
}
private static void Reverse(List<Part> list, int i, int j)
{
while (i < j)
{
var tmp = list[i];
list[i] = list[j];
list[j] = tmp;
i++;
j--;
}
}
private static OpenNest.Geometry.Vector Center(Part part)
{
return part.BoundingBox.Center;
}
private static double Distance(OpenNest.Geometry.Vector a, OpenNest.Geometry.Vector b)
{
var dx = b.X - a.X;
var dy = b.Y - a.Y;
return System.Math.Sqrt(dx * dx + dy * dy);
}
}
}
@@ -1,17 +0,0 @@
using System.Collections.Generic;
using System.Linq;
namespace OpenNest.Engine.Sequencing
{
public class LeftSideSequencer : IPartSequencer
{
public List<SequencedPart> Sequence(IReadOnlyList<Part> parts, Plate plate)
{
return parts
.OrderBy(p => p.Location.X)
.ThenBy(p => p.Location.Y)
.Select(p => new SequencedPart { Part = p })
.ToList();
}
}
}
@@ -1,30 +0,0 @@
using System;
using OpenNest.CNC.CuttingStrategy;
using OpenNest.CNC.Thermal;
namespace OpenNest.Engine.Sequencing
{
public static class PartSequencerFactory
{
/// <param name="thermal">
/// The sheet's material and thickness, which only <see cref="SequenceMethod.HeatAware"/>
/// reads; without them it orders by travel alone.
/// </param>
public static IPartSequencer Create(SequenceParameters parameters, ThermalParameters thermal = null)
{
return parameters.Method switch
{
SequenceMethod.RightSide => new RightSideSequencer(),
SequenceMethod.LeftSide => new LeftSideSequencer(),
SequenceMethod.BottomSide => new BottomSideSequencer(),
SequenceMethod.EdgeStart => new EdgeStartSequencer(),
SequenceMethod.LeastCode => new LeastCodeSequencer(),
SequenceMethod.Advanced => new AdvancedSequencer(parameters),
SequenceMethod.HeatAware => new HeatAwareSequencer(parameters, thermal),
_ => throw new NotSupportedException(
$"Sequence method '{parameters.Method}' is not supported."
),
};
}
}
}
-22
View File
@@ -1,22 +0,0 @@
using OpenNest.Geometry;
namespace OpenNest.Engine.Sequencing
{
internal static class PlateHelper
{
public static Vector GetExitPoint(Plate plate)
{
var xExtent = plate.Size.Length;
var yExtent = plate.Size.Width;
return plate.Quadrant switch
{
1 => new Vector(xExtent, yExtent),
2 => new Vector(0, yExtent),
3 => new Vector(0, 0),
4 => new Vector(xExtent, 0),
_ => new Vector(xExtent, yExtent),
};
}
}
}
+5 -42
View File
@@ -1,47 +1,17 @@
using System.Collections.Generic;
using System.Linq;
using OpenNest.CNC.CuttingStrategy;
using OpenNest.CNC.Thermal;
using OpenNest.CutOffs;
using OpenNest.Engine.CuttingPlanning;
namespace OpenNest.Engine.Sequencing
{
/// <summary>Applies a sequencer's exit-first route as the plate's cutting order.</summary>
/// <summary>
/// The cutoff rules every cutting order keeps: each cutoff segment before the parts its line
/// passes through, and sheet separators last. The order itself comes from Plan Cutting or
/// the user (Set Sequence, Sequence by Path).
/// </summary>
public static class PlateSequencing
{
/// <summary>Sequences the plates present when the operation starts.</summary>
/// <param name="thermal">The sheets' material and thickness, for
/// <see cref="SequenceMethod.HeatAware"/>; see <see cref="PartSequencerFactory.Create"/>.</param>
public static void ApplyAll(IEnumerable<Plate> plates, SequenceParameters parameters, ThermalParameters thermal = null)
{
// Reordering parts can make PlateManager replace the trailing empty
// plate. Snapshot before applying so those events cannot invalidate
// enumeration of the nest's live plate collection.
foreach (var plate in plates.ToArray())
Apply(plate, parameters, thermal);
}
/// <param name="thermal">The sheet's material and thickness, for
/// <see cref="SequenceMethod.HeatAware"/>; see <see cref="PartSequencerFactory.Create"/>.</param>
public static void Apply(Plate plate, SequenceParameters parameters, ThermalParameters thermal = null)
{
var sequencer = PartSequencerFactory.Create(parameters, thermal);
// Cut-first parts (test coupons) get their own route ahead of the rest,
// so they stay grouped instead of interleaving with the main route.
var first = plate.Parts.Where(p => p.BaseDrawing.CutFirst).ToList();
var rest = plate.Parts.Where(p => !p.BaseDrawing.CutFirst).ToList();
var ordered = CutOrder(sequencer, first, plate).Concat(CutOrder(sequencer, rest, plate)).ToList();
// Enforce dependencies AFTER reversing the exit-first route. Checking
// the sequencer's output itself would invert the safety rule on apply.
var cutOrder = OrderCutOffsFirst(ordered, plate);
plate.Parts.Clear();
foreach (var part in cutOrder)
plate.Parts.Add(part);
}
/// <summary>
/// Moves the given cutoffs' segment parts to where the cutoff rules need them while every
/// other part and cutoff keeps its position: each segment just before the first part in
@@ -101,13 +71,6 @@ namespace OpenNest.Engine.Sequencing
}
}
private static IEnumerable<Part> CutOrder(IPartSequencer sequencer, List<Part> parts, Plate plate)
{
if (parts.Count == 0)
return Enumerable.Empty<Part>();
return sequencer.Sequence(parts, plate).Select(p => p.Part).Reverse();
}
internal static List<Part> OrderCutOffsFirst(List<Part> ordered, Plate plate)
{
var definitions = new Dictionary<Drawing, CutOff>(ReferenceEqualityComparer.Instance);
@@ -1,17 +0,0 @@
using System.Collections.Generic;
using System.Linq;
namespace OpenNest.Engine.Sequencing
{
public class RightSideSequencer : IPartSequencer
{
public List<SequencedPart> Sequence(IReadOnlyList<Part> parts, Plate plate)
{
return parts
.OrderByDescending(p => p.Location.X)
.ThenBy(p => p.Location.Y)
.Select(p => new SequencedPart { Part = p })
.ToList();
}
}
}