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

+2 -2
View File
@@ -40,7 +40,7 @@ Releases: follow [the release procedure](docs/releasing.md) and `scripts/Publish
## Project map and boundaries
- `OpenNest.Core`: domain (`Nest -> Plate -> Part -> Drawing -> CNC.Program`), geometry, cutting strategies and diagnostics. Angles are radians; use `Tolerance.Epsilon` for geometry comparisons. `OpenNest.Math` shadows `System.Math`, so qualify the latter, and call `PortableMath` (not `System.Math`) for trig in Core/Engine/IO/Data so layouts match across platforms. `OpenNest.Math` and `OpenNest.Geometry` are Core's bottom layers (Math uses nothing else in OpenNest; Geometry uses Math plus the root types `OffsetSide`, `RotationType`, `PushDirection`, `RelativePosition`, `PerfCounters`, `SpecialLayers`); `CoreLayeringTests` enforces it.
- `OpenNest.Engine`: whole-job API in `Jobs/`, interactive proposals via `PlateFillService`, fill strategies, best-fit pairs, packing, sequencing and rapid planning. `INestingEngine.Solve(NestJob)` returns stock IDs/poses; boundary adapters map drawings and materialize results. `NestJobRunner` validates its candidates before committing demand/stock accounting. Do not assume arbitrary plug-in output or interactive paths received that validation. Job identity is reference-based, not drawing-name-based.
- `OpenNest.Engine`: whole-job API in `Jobs/`, interactive proposals via `PlateFillService`, fill strategies, best-fit pairs, packing and cutting planning. `INestingEngine.Solve(NestJob)` returns stock IDs/poses; boundary adapters map drawings and materialize results. `NestJobRunner` validates its candidates before committing demand/stock accounting. Do not assume arbitrary plug-in output or interactive paths received that validation. Job identity is reference-based, not drawing-name-based.
- Built-in whole-job engines live in `OpenNest.Engine/NestingEngines/<Name>/`, named for the jobs they suit; see [nesting engines](docs/nesting-engines.md). A change must beat that engine's current benchmark result with every layout valid. External plug-ins implement `INestingEngine` with a public parameterless constructor and load from `Engines/` beside the host; keep their projects out of this solution.
- `OpenNest.IO`: ACadSharp and SVG import/export and ZIP-based `.nest` persistence; depends on Core only (an IO.Tests guard enforces it). Best fits persist only when callers pass `BestFitCacheStore.Shared` as `NestReader`/`NestWriter.BestFitStore`. All DXF-to-Drawing conversion goes through `CadImporter`: `Import` + `BuildDrawing` for editable/reporting flows, `ImportDrawing` for headless callers. Preserve source offsets, entity IDs, suppressed entities and bends. Bend repair is opt-in, requires explicit source units and may not alter cut geometry or unrelated marks.
- `OpenNest`: WinForms UI (`Forms/`, `Controls/PlateView`, `Actions/`). `OpenNest.Data` holds cross-platform persistence; new-nest defaults live in `%APPDATA%\OpenNest\defaults.json` (in Database mode, the server's shared copy once it holds one). WinForms `Properties.Settings` persist to `%APPDATA%\OpenNest\user-settings.json` through `AppDataSettingsProvider`, never inside the Velopack install folder; `OpenNest.WinForms.Tests` redirects them to a temp file, so a test run never writes the user's settings. Posts live in `Posts/OpenNest.Posts.<Name>/` and deploy to each desktop app's output `Posts/` directory (WinForms and Avalonia). Desktop nest edits go through `BeginChange`/`RecordChange`; see [undo and redo](docs/undo-redo.md).
@@ -56,7 +56,7 @@ Releases: follow [the release procedure](docs/releasing.md) and `scripts/Publish
- `FillScore` ranks count, utilization, compactness; exact ties keep the current layout. Custom comparers remain authoritative. Preserve extents' negative/nonfinite-input fallback, pair preparation and adjusted-column overlap checks. Do not remove bounds recomputations without threshold/rounding characterization.
- `ObservableList` events own drawing/plate quantity tracking; avoid double accounting. Cutoff parts are excluded from quantity, utilization and overlap checks.
- `Plate.Outline`/`NestPlateStock.Outline` (`SheetOutline`) make a sheet irregular; `Size` stays its bounding box. Only Irregular fills it (`PackBoundary` eroded by the largest edge spacing); every other engine and fill strategy must place nothing on it, validation must reject parts outside it or over its obstacles, plate pushes stop at its usable edge, and automatic cut-offs refuse it. See [irregular stock](docs/irregular-stock.md).
- 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.
- 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. Cut order comes from Plan Cutting or the user (no automatic part sequencers); use `PlateSequencing.OrderCutOffsFirst`/`PlaceCutOffs` for 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. The one designed raise is the rapid out of a cutout's slug after its lead-out, marked at emission (see the cutting planner doc); no lead-out or an overcut keeps the head down. Every post must raise before a marked rapid or refuse the nest.
@@ -1,7 +1,9 @@
namespace OpenNest.CNC.CuttingStrategy
{
// Values 1-8 match PEP Technology's numbering scheme (value 6 intentionally skipped);
// OpenNest's own methods start at 100, outside PEP's range.
// OpenNest's own methods start at 100, outside PEP's range. Saved cutting settings still
// carry these values, but nothing orders parts by them: the cut order comes from Plan Cutting
// or the user (see docs/plate-heat-map.md#sequencing).
public enum SequenceMethod
{
RightSide = 1,
@@ -14,8 +16,7 @@ namespace OpenNest.CNC.CuttingStrategy
/// <summary>
/// Travel time plus <see cref="SequenceParameters.HeatWeight"/> times the estimated heat
/// where each candidate part starts: it leaves the hot zone, but goes no further than that.
/// See docs/plate-heat-map.md.
/// where each candidate part starts. Its sequencer was removed; see docs/plate-heat-map.md.
/// </summary>
HeatAware = 100,
}
@@ -1,107 +0,0 @@
using System;
using System.Collections.Generic;
using OpenNest.Geometry;
namespace OpenNest.CNC.Thermal
{
/// <summary>
/// A cheap stand-in for <see cref="PlateHeatSimulation"/> for choosing a cut order: each finished
/// part leaves a Gaussian blob of the heat its cut put in (absorbed power times its torch-on
/// time), as wide as the part to begin with, widening as the heat conducts (4αΔt) and fading
/// with the loss from both faces. It ignores kerfs and dropped slugs. Like the grid model, its
/// temperatures are relative, for comparing orders. See docs/plate-heat-map.md.
/// </summary>
public sealed class HeatSpreadEstimate
{
/// <summary>
/// The most recent parts whose heat is summed; older blobs have spread into a near-uniform
/// background that hardly changes which part is next, and leaving them out keeps a large
/// plate's order from growing with the cube of its part count.
/// </summary>
public const int MaxDeposits = 200;
private readonly List<Deposit> deposits = new();
private readonly double diffusivity;
private readonly double heatCapacity;
private readonly double loss;
private readonly double squareMeters;
public HeatSpreadEstimate(ThermalParameters thermal)
{
Thermal = thermal ?? throw new ArgumentNullException(nameof(thermal));
var meters = thermal.MetersPerUnit;
var material = thermal.Material;
var thickness = thermal.Thickness * meters;
HasThickness = double.IsFinite(thermal.Thickness) && thermal.Thickness > 0;
diffusivity = material.Diffusivity / (meters * meters);
heatCapacity = material.Density * material.SpecificHeat * thickness;
loss = HasThickness ? 2 * thermal.SurfaceCoefficient / heatCapacity : 0;
squareMeters = meters * meters;
// Stand-in feeds until the controller's process tables are known; the same ones the
// order comparisons in docs/plate-heat-map.md were made with.
var inches = HasThickness ? thermal.Thickness * meters / 0.0254 : 0;
var inchesPerMinute = inches <= 0.135 ? 400 : inches <= 0.26 ? 150 : 80;
var unitsPerInch = 0.0254 / meters;
FeedRate = inchesPerMinute * unitsPerInch / 60;
RapidRate = 3000 * unitsPerInch / 60;
PierceSeconds = inches <= 0.26 ? 0.5 : 1.5;
}
public ThermalParameters Thermal { get; }
/// <summary>False when the thickness is missing: the estimate is then always zero.</summary>
public bool HasThickness { get; }
/// <summary>Stand-in cutting feed for the thickness, in units per second.</summary>
public double FeedRate { get; }
/// <summary>Stand-in head-up travel rate, in units per second.</summary>
public double RapidRate { get; }
/// <summary>Stand-in pierce dwell for the thickness, in seconds.</summary>
public double PierceSeconds { get; }
/// <summary>Torch-on seconds for a part with this much cut length and these pierces.</summary>
public double TorchSeconds(double cutLength, int pierces) =>
System.Math.Max(0, cutLength) / FeedRate + System.Math.Max(0, pierces) * PierceSeconds;
/// <summary>Seconds to travel <paramref name="distance"/> head-up.</summary>
public double TravelSeconds(double distance) => distance / RapidRate;
/// <summary>
/// Adds a finished part's heat: <paramref name="torchSeconds"/> of absorbed power centered
/// at <paramref name="center"/>, spread to begin with over <paramref name="spread2"/>
/// (square units; a quarter of the part's squared diagonal), as of <paramref name="time"/>
/// seconds into the cut.
/// </summary>
public void Add(Vector center, double spread2, double torchSeconds, double time)
{
if (!HasThickness || torchSeconds <= 0)
return;
if (deposits.Count == MaxDeposits)
deposits.RemoveAt(0);
deposits.Add(new(center, Thermal.AbsorbedPower * torchSeconds, time, System.Math.Max(spread2, 0)));
}
/// <summary>The estimated temperature rise, in °C, at <paramref name="at"/> and <paramref name="time"/>.</summary>
public double TemperatureAt(Vector at, double time)
{
var total = 0.0;
foreach (var deposit in deposits)
{
var elapsed = System.Math.Max(0, time - deposit.Time);
var spread2 = 4 * diffusivity * elapsed + deposit.Spread2;
if (spread2 <= 0)
continue;
var dx = at.X - deposit.Center.X;
var dy = at.Y - deposit.Center.Y;
total += deposit.Energy / (heatCapacity * System.Math.PI * spread2 * squareMeters)
* System.Math.Exp(-(dx * dx + dy * dy) / spread2 - loss * elapsed);
}
return total;
}
private readonly record struct Deposit(Vector Center, double Energy, double Time, double Spread2);
}
}
-75
View File
@@ -1,75 +0,0 @@
using System.Collections.Generic;
using OpenNest.Geometry;
namespace OpenNest
{
public interface ISequencer
{
List<Part> SequenceParts(IList<Part> parts);
List<Part> SequenceParts(IList<Part> parts, Vector origin);
}
public class SequenceByNearest : ISequencer
{
public List<Part> SequenceParts(IList<Part> parts)
{
return SequenceParts(parts, Vector.Zero);
}
public List<Part> SequenceParts(IList<Part> parts, Vector origin)
{
if (parts.Count == 0)
return new List<Part>();
var dupList = new List<Part>(parts);
var seqList = new List<Part>(parts.Count);
var lastPart = GetClosestPart(origin, dupList);
seqList.Add(lastPart);
dupList.Remove(lastPart);
for (
int i = 0;
i
< parts.Count
- 1 /*STOP BEFORE LAST PART*/
;
i++
)
{
var nextPart = GetClosestPart(lastPart.Location, dupList);
if (nextPart == null)
break;
seqList.Add(nextPart);
dupList.Remove(nextPart);
lastPart = nextPart;
}
return seqList;
}
private Part GetClosestPart(Vector pt, IList<Part> parts)
{
if (parts.Count == 0)
return null;
var closestPart = parts[0];
var closestDistance = parts[0].Location.DistanceTo(pt);
for (int i = 1; i < parts.Count; i++)
{
var distance = parts[i].Location.DistanceTo(pt);
if (distance < closestDistance)
{
closestPart = parts[i];
closestDistance = distance;
}
}
return closestPart;
}
}
}
-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();
}
}
}
@@ -1,124 +0,0 @@
using OpenNest.CNC.CuttingStrategy;
using OpenNest.Engine;
using OpenNest.Engine.RapidPlanning;
using OpenNest.Engine.Sequencing;
namespace OpenNest.Tests.Engine;
public class PlateProcessorTests
{
private static Part MakePartAt(double x, double y) => TestHelpers.MakePartAt(x, y, size: 2);
[Fact]
public void Process_ReturnsAllParts()
{
var plate = new Plate(60, 120);
plate.Parts.Add(MakePartAt(10, 10));
plate.Parts.Add(MakePartAt(30, 30));
plate.Parts.Add(MakePartAt(50, 50));
var processor = new PlateProcessor
{
Sequencer = new RightSideSequencer(),
RapidPlanner = new SafeHeightRapidPlanner(),
};
var result = processor.Process(plate);
Assert.Equal(3, result.Parts.Count);
}
[Fact]
public void Process_PreservesSequenceOrder()
{
var plate = new Plate(60, 120);
var left = MakePartAt(5, 10);
var right = MakePartAt(50, 10);
plate.Parts.Add(left);
plate.Parts.Add(right);
var processor = new PlateProcessor
{
Sequencer = new RightSideSequencer(),
RapidPlanner = new SafeHeightRapidPlanner(),
};
var result = processor.Process(plate);
Assert.Same(right, result.Parts[0].Part);
Assert.Same(left, result.Parts[1].Part);
}
[Fact]
public void Process_SkipsCuttingStrategy_WhenManualLeadIns()
{
var plate = new Plate(60, 120);
var part = MakePartAt(10, 10);
part.HasManualLeadIns = true;
plate.Parts.Add(part);
var processor = new PlateProcessor
{
Sequencer = new LeftSideSequencer(),
CuttingStrategy = new ContourCuttingStrategy { Parameters = new CuttingParameters() },
RapidPlanner = new SafeHeightRapidPlanner(),
};
var result = processor.Process(plate);
Assert.Same(part.Program, result.Parts[0].ProcessedProgram);
}
[Fact]
public void Process_DoesNotMutatePart()
{
var plate = new Plate(60, 120);
var part = MakePartAt(10, 10);
var originalProgram = part.Program;
plate.Parts.Add(part);
var processor = new PlateProcessor
{
Sequencer = new LeftSideSequencer(),
RapidPlanner = new SafeHeightRapidPlanner(),
};
var result = processor.Process(plate);
Assert.Same(originalProgram, part.Program);
}
[Fact]
public void Process_NoCuttingStrategy_PassesProgramThrough()
{
var plate = new Plate(60, 120);
var part = MakePartAt(10, 10);
plate.Parts.Add(part);
var processor = new PlateProcessor
{
Sequencer = new LeftSideSequencer(),
RapidPlanner = new SafeHeightRapidPlanner(),
};
var result = processor.Process(plate);
Assert.Same(part.Program, result.Parts[0].ProcessedProgram);
}
[Fact]
public void Process_EmptyPlate_ReturnsEmptyResult()
{
var plate = new Plate(60, 120);
var processor = new PlateProcessor
{
Sequencer = new LeftSideSequencer(),
RapidPlanner = new SafeHeightRapidPlanner(),
};
var result = processor.Process(plate);
Assert.Empty(result.Parts);
}
}
@@ -1,58 +0,0 @@
using OpenNest.Engine.RapidPlanning;
using OpenNest.Geometry;
namespace OpenNest.Tests.RapidPlanning;
public class DirectRapidPlannerTests
{
[Fact]
public void NoCutAreas_ReturnsHeadDown()
{
var planner = new DirectRapidPlanner();
var result = planner.Plan(new Vector(0, 0), new Vector(10, 10), new List<Shape>());
Assert.False(result.HeadUp);
Assert.Empty(result.Waypoints);
}
[Fact]
public void ClearPath_ReturnsHeadDown()
{
var planner = new DirectRapidPlanner();
var cutArea = new Shape();
cutArea.Entities.Add(new Line(new Vector(50, 0), new Vector(50, 10)));
cutArea.Entities.Add(new Line(new Vector(50, 10), new Vector(60, 10)));
cutArea.Entities.Add(new Line(new Vector(60, 10), new Vector(60, 0)));
cutArea.Entities.Add(new Line(new Vector(60, 0), new Vector(50, 0)));
var result = planner.Plan(
new Vector(0, 0),
new Vector(10, 10),
new List<Shape> { cutArea }
);
Assert.False(result.HeadUp);
}
[Fact]
public void BlockedPath_ReturnsHeadUp()
{
var planner = new DirectRapidPlanner();
var cutArea = new Shape();
cutArea.Entities.Add(new Line(new Vector(5, 0), new Vector(5, 20)));
cutArea.Entities.Add(new Line(new Vector(5, 20), new Vector(6, 20)));
cutArea.Entities.Add(new Line(new Vector(6, 20), new Vector(6, 0)));
cutArea.Entities.Add(new Line(new Vector(6, 0), new Vector(5, 0)));
var result = planner.Plan(
new Vector(0, 10),
new Vector(10, 10),
new List<Shape> { cutArea }
);
Assert.True(result.HeadUp);
Assert.Empty(result.Waypoints);
}
}
@@ -1,37 +0,0 @@
using OpenNest.Engine.RapidPlanning;
using OpenNest.Geometry;
namespace OpenNest.Tests.RapidPlanning;
public class SafeHeightRapidPlannerTests
{
[Fact]
public void AlwaysReturnsHeadUp()
{
var planner = new SafeHeightRapidPlanner();
var from = new Vector(10, 10);
var to = new Vector(50, 50);
var cutAreas = new List<Shape>();
var result = planner.Plan(from, to, cutAreas);
Assert.True(result.HeadUp);
Assert.Empty(result.Waypoints);
}
[Fact]
public void ReturnsHeadUp_EvenWithCutAreas()
{
var planner = new SafeHeightRapidPlanner();
var from = new Vector(0, 0);
var to = new Vector(10, 10);
var shape = new Shape();
shape.Entities.Add(new Line(new Vector(5, 0), new Vector(5, 20)));
var cutAreas = new List<Shape> { shape };
var result = planner.Plan(from, to, cutAreas);
Assert.True(result.HeadUp);
}
}
@@ -1,65 +0,0 @@
using OpenNest.CNC.CuttingStrategy;
using OpenNest.Engine.Sequencing;
namespace OpenNest.Tests.Sequencing;
public class AdvancedSequencerTests
{
private static Part MakePartAt(double x, double y) => TestHelpers.MakePartAt(x, y);
[Fact]
public void GroupsIntoRows_NoAlternate()
{
var plate = new Plate(100, 100);
var row1a = MakePartAt(10, 10);
var row1b = MakePartAt(30, 10);
var row2a = MakePartAt(10, 50);
var row2b = MakePartAt(30, 50);
plate.Parts.Add(row1a);
plate.Parts.Add(row1b);
plate.Parts.Add(row2a);
plate.Parts.Add(row2b);
var parameters = new SequenceParameters
{
Method = SequenceMethod.Advanced,
MinDistanceBetweenRowsColumns = 5.0,
AlternateRowsColumns = false,
};
var sequencer = new AdvancedSequencer(parameters);
var result = sequencer.Sequence(plate.Parts.ToList(), plate);
Assert.Same(row1a, result[0].Part);
Assert.Same(row1b, result[1].Part);
Assert.Same(row2a, result[2].Part);
Assert.Same(row2b, result[3].Part);
}
[Fact]
public void SerpentineAlternatesDirection()
{
var plate = new Plate(100, 100);
var r1Left = MakePartAt(10, 10);
var r1Right = MakePartAt(30, 10);
var r2Left = MakePartAt(10, 50);
var r2Right = MakePartAt(30, 50);
plate.Parts.Add(r1Left);
plate.Parts.Add(r1Right);
plate.Parts.Add(r2Left);
plate.Parts.Add(r2Right);
var parameters = new SequenceParameters
{
Method = SequenceMethod.Advanced,
MinDistanceBetweenRowsColumns = 5.0,
AlternateRowsColumns = true,
};
var sequencer = new AdvancedSequencer(parameters);
var result = sequencer.Sequence(plate.Parts.ToList(), plate);
Assert.Same(r1Left, result[0].Part);
Assert.Same(r1Right, result[1].Part);
Assert.Same(r2Right, result[2].Part);
Assert.Same(r2Left, result[3].Part);
}
}
@@ -1,72 +0,0 @@
using OpenNest.Engine.Sequencing;
namespace OpenNest.Tests.Sequencing;
public class DirectionalSequencerTests
{
private static Part MakePartAt(double x, double y) => TestHelpers.MakePartAt(x, y);
private static Plate MakePlate(params Part[] parts) => TestHelpers.MakePlate(60, 120, parts);
[Fact]
public void RightSide_SortsXDescending()
{
var a = MakePartAt(10, 5);
var b = MakePartAt(30, 5);
var c = MakePartAt(20, 5);
var plate = MakePlate(a, b, c);
var sequencer = new RightSideSequencer();
var result = sequencer.Sequence(plate.Parts.ToList(), plate);
Assert.Same(b, result[0].Part);
Assert.Same(c, result[1].Part);
Assert.Same(a, result[2].Part);
}
[Fact]
public void LeftSide_SortsXAscending()
{
var a = MakePartAt(10, 5);
var b = MakePartAt(30, 5);
var c = MakePartAt(20, 5);
var plate = MakePlate(a, b, c);
var sequencer = new LeftSideSequencer();
var result = sequencer.Sequence(plate.Parts.ToList(), plate);
Assert.Same(a, result[0].Part);
Assert.Same(c, result[1].Part);
Assert.Same(b, result[2].Part);
}
[Fact]
public void BottomSide_SortsYAscending()
{
var a = MakePartAt(5, 20);
var b = MakePartAt(5, 5);
var c = MakePartAt(5, 10);
var plate = MakePlate(a, b, c);
var sequencer = new BottomSideSequencer();
var result = sequencer.Sequence(plate.Parts.ToList(), plate);
Assert.Same(b, result[0].Part);
Assert.Same(c, result[1].Part);
Assert.Same(a, result[2].Part);
}
[Fact]
public void RightSide_TiesBrokenByPerpendicularAxis()
{
var a = MakePartAt(10, 20);
var b = MakePartAt(10, 5);
var plate = MakePlate(a, b);
var sequencer = new RightSideSequencer();
var result = sequencer.Sequence(plate.Parts.ToList(), plate);
Assert.Same(b, result[0].Part);
Assert.Same(a, result[1].Part);
}
}
@@ -1,27 +0,0 @@
using OpenNest.Engine.Sequencing;
namespace OpenNest.Tests.Sequencing;
public class EdgeStartSequencerTests
{
private static Part MakePartAt(double x, double y) => TestHelpers.MakePartAt(x, y);
[Fact]
public void SortsByDistanceFromNearestEdge()
{
var plate = new Plate(60, 120);
var edgePart = MakePartAt(1, 1);
var centerPart = MakePartAt(25, 25);
var midPart = MakePartAt(10, 10);
plate.Parts.Add(edgePart);
plate.Parts.Add(centerPart);
plate.Parts.Add(midPart);
var sequencer = new EdgeStartSequencer();
var result = sequencer.Sequence(plate.Parts.ToList(), plate);
Assert.Same(edgePart, result[0].Part);
Assert.Same(midPart, result[1].Part);
Assert.Same(centerPart, result[2].Part);
}
}
@@ -1,167 +0,0 @@
using OpenNest.CNC.CuttingStrategy;
using OpenNest.CNC.Thermal;
using OpenNest.CutOffs;
using OpenNest.Engine.Sequencing;
using OpenNest.Geometry;
namespace OpenNest.Tests.Sequencing;
public class HeatAwareSequencerTests
{
private static readonly ThermalParameters QuarterInchSteel = ThermalParameters.For("Mild steel", "A36", 0.25, Units.Inches);
private static readonly IReadOnlyCollection<int>[] NoPrerequisites = [[], [], []];
// A long hot part beside a short cool one, and another short one far along.
private static HeatAwareItem[] HotNeighbor() =>
[
Item(1, 0, 60),
Item(2, 0, 10),
Item(20, 0, 10),
];
private static HeatAwareItem Item(double x, double y, double seconds) =>
new(new Vector(x, y), new Vector(x, y), new Box(x - 0.5, y - 0.5, 1, 1), seconds);
[Fact]
public void WithoutWeight_ItIsNearestNeighbor()
{
var order = HeatAwareOrder.Plan(HotNeighbor(), [0, 1, 2], Vector.Zero, NoPrerequisites,
QuarterInchSteel, 0, default);
Assert.Equal([0, 1, 2], order);
}
[Fact]
public void WithoutThickness_ItIsNearestNeighbor()
{
var order = HeatAwareOrder.Plan(HotNeighbor(), [0, 1, 2], Vector.Zero, NoPrerequisites,
ThermalParameters.For("Mild steel", "A36", 0, Units.Inches), 0.15, default);
Assert.Equal([0, 1, 2], order);
}
[Fact]
public void AHotNeighbor_IsLeftUntilTheRouteComesBack()
{
var order = HeatAwareOrder.Plan(HotNeighbor(), [0, 1, 2], Vector.Zero, NoPrerequisites,
QuarterInchSteel, 0.15, default);
Assert.Equal([0, 2, 1], order);
}
[Fact]
public void ItGoesOnlyAsFarAsTheHotZone()
{
// Two cool parts beyond the hot neighbor: the nearer one clear of the heat comes next,
// not the farthest.
HeatAwareItem[] items = [Item(1, 0, 60), Item(2, 0, 10), Item(12, 0, 10), Item(40, 0, 10)];
var order = HeatAwareOrder.Plan(items, [0, 1, 2, 3], Vector.Zero, [[], [], [], []],
QuarterInchSteel, 0.15, default);
Assert.Equal(0, order[0]);
Assert.Equal(2, order[1]);
}
[Fact]
public void APrerequisite_StillComesFirst()
{
// The hot neighbor must follow the first part (as a nested part precedes its host).
IReadOnlyCollection<int>[] prerequisites = [[], [0], []];
var order = HeatAwareOrder.Plan(HotNeighbor(), [1, 0, 2], Vector.Zero, prerequisites,
QuarterInchSteel, 0.15, default);
Assert.True(Array.IndexOf(order, 0) < Array.IndexOf(order, 1));
Assert.Equal([0, 1, 2], order.Order());
}
[Fact]
public void PartsAlreadyCut_LeaveTheirHeat()
{
// Re-planning parts 1 and 2 after part 0 was cut: part 1 sits in part 0's heat.
var order = HeatAwareOrder.Plan(HotNeighbor(), [1, 2], new Vector(1, 0), NoPrerequisites,
QuarterInchSteel, 0.15, default, done: [0], origin: Vector.Zero);
Assert.Equal([2, 1], order);
}
[Fact]
public void Estimate_FadesAndSpreadsWithTime()
{
var estimate = new HeatSpreadEstimate(QuarterInchSteel);
estimate.Add(Vector.Zero, 0.5, 30, 0);
var atOnce = estimate.TemperatureAt(Vector.Zero, 0);
var later = estimate.TemperatureAt(Vector.Zero, 60);
var aside = estimate.TemperatureAt(new Vector(3, 0), 0);
var asideLater = estimate.TemperatureAt(new Vector(3, 0), 60);
Assert.True(atOnce > later);
Assert.True(aside < atOnce);
Assert.True(asideLater > aside, "Heat conducts outward.");
}
[Fact]
public void Sequencer_ReturnsTheForwardOrderExitFirst()
{
var plate = new Plate(60, 30);
var parts = Enumerable.Range(0, 3).Select(i => TestHelpers.MakePartAt(5 + i * 10, 5)).ToList();
foreach (var part in parts)
plate.Parts.Add(part);
// No thickness: nearest neighbor from the plate's origin corner.
var result = new HeatAwareSequencer(new SequenceParameters { Method = SequenceMethod.HeatAware }, null)
.Sequence(parts, plate);
Assert.Equal(new[] { parts[2], parts[1], parts[0] }, result.Select(r => r.Part));
}
[Fact]
public void Apply_CutsAHotNeighborLater()
{
// Ten small squares in a row; with a heavy weight the next part is never the one beside
// the part just cut.
var plate = new Plate(120, 20);
var parts = Enumerable.Range(0, 10).Select(i => TestHelpers.MakePartAt(1 + i * 1.5, 1)).ToList();
foreach (var part in parts)
plate.Parts.Add(part);
var parameters = new SequenceParameters { Method = SequenceMethod.HeatAware, HeatWeight = 5 };
PlateSequencing.Apply(plate, parameters, QuarterInchSteel);
var order = plate.Parts.Select(part => parts.IndexOf(part)).ToArray();
Assert.Equal(Enumerable.Range(0, 10), order.Order());
Assert.Equal(0, order[0]);
Assert.Contains(order.Zip(order.Skip(1)), pair => System.Math.Abs(pair.First - pair.Second) > 1);
}
[Fact]
public void Apply_KeepsCutOffsBeforeThePartsTheyCross()
{
var plate = new Plate(60, 30);
var left = TestHelpers.MakePartAt(5, 5);
var right = TestHelpers.MakePartAt(40, 5);
plate.Parts.Add(left);
plate.Parts.Add(right);
plate.CutOffs.Add(new CutOff(new Vector(20, 0), CutOffAxis.Vertical));
plate.RegenerateCutOffs(new CutOffSettings());
PlateSequencing.Apply(plate, new SequenceParameters { Method = SequenceMethod.HeatAware }, QuarterInchSteel);
var applied = plate.Parts.ToList();
Assert.Contains(applied, p => p.BaseDrawing.IsCutOff);
Assert.Equal(2, applied.Count(p => !p.BaseDrawing.IsCutOff));
// The cut-off rules already hold: applying them again changes nothing.
Assert.Equal(applied, PlateSequencing.OrderCutOffsFirst(applied, plate));
}
[Fact]
public void Factory_CreatesTheHeatAwareSequencer()
{
var sequencer = PartSequencerFactory.Create(new SequenceParameters { Method = SequenceMethod.HeatAware });
Assert.IsType<HeatAwareSequencer>(sequencer);
}
}
@@ -1,57 +0,0 @@
using OpenNest.Engine.Sequencing;
namespace OpenNest.Tests.Sequencing;
public class LeastCodeSequencerTests
{
private static Part MakePartAt(double x, double y) => TestHelpers.MakePartAt(x, y);
[Fact]
public void NearestNeighbor_FromExitPoint()
{
var plate = new Plate(60, 120);
var farPart = MakePartAt(5, 5);
var nearPart = MakePartAt(55, 115);
plate.Parts.Add(farPart);
plate.Parts.Add(nearPart);
var sequencer = new LeastCodeSequencer();
var result = sequencer.Sequence(plate.Parts.ToList(), plate);
// nearPart is closer to exit point, should come first
Assert.Same(nearPart, result[0].Part);
Assert.Same(farPart, result[1].Part);
}
[Fact]
public void PreservesAllParts()
{
var plate = new Plate(60, 120);
for (var i = 0; i < 10; i++)
plate.Parts.Add(MakePartAt(i * 5, i * 10));
var sequencer = new LeastCodeSequencer();
var result = sequencer.Sequence(plate.Parts.ToList(), plate);
Assert.Equal(10, result.Count);
}
[Fact]
public void TwoOpt_ImprovesSolution()
{
var plate = new Plate(100, 100);
var a = MakePartAt(90, 90);
var b = MakePartAt(10, 80);
var c = MakePartAt(80, 10);
var d = MakePartAt(5, 5);
plate.Parts.Add(a);
plate.Parts.Add(b);
plate.Parts.Add(c);
plate.Parts.Add(d);
var sequencer = new LeastCodeSequencer();
var result = sequencer.Sequence(plate.Parts.ToList(), plate);
Assert.Equal(4, result.Count);
}
}
@@ -1,28 +0,0 @@
using OpenNest.CNC.CuttingStrategy;
using OpenNest.Engine.Sequencing;
namespace OpenNest.Tests.Sequencing;
public class PartSequencerFactoryTests
{
[Theory]
[InlineData(SequenceMethod.RightSide, typeof(RightSideSequencer))]
[InlineData(SequenceMethod.LeftSide, typeof(LeftSideSequencer))]
[InlineData(SequenceMethod.BottomSide, typeof(BottomSideSequencer))]
[InlineData(SequenceMethod.EdgeStart, typeof(EdgeStartSequencer))]
[InlineData(SequenceMethod.LeastCode, typeof(LeastCodeSequencer))]
[InlineData(SequenceMethod.Advanced, typeof(AdvancedSequencer))]
public void Create_ReturnsCorrectType(SequenceMethod method, Type expectedType)
{
var parameters = new SequenceParameters { Method = method };
var sequencer = PartSequencerFactory.Create(parameters);
Assert.IsType(expectedType, sequencer);
}
[Fact]
public void Create_RightSideAlt_Throws()
{
var parameters = new SequenceParameters { Method = SequenceMethod.RightSideAlt };
Assert.Throws<NotSupportedException>(() => PartSequencerFactory.Create(parameters));
}
}
+60 -252
View File
@@ -1,4 +1,3 @@
using OpenNest.CNC.CuttingStrategy;
using OpenNest.CutOffs;
using OpenNest.Engine.CuttingPlanning;
using OpenNest.Engine.Sequencing;
@@ -7,146 +6,16 @@ using OpenNest.IO;
namespace OpenNest.Tests.Sequencing;
// The cutoff rules applied to a cutting order the user gives: each test hands OrderCutOffsFirst
// a route, as Sequence by Path does.
public class PlateSequencingTests
{
[Theory]
[InlineData(1)]
[InlineData(3)]
public void ApplyAll_WithManagedNest_SequencesEveryPlateAndPreservesParts(int plateCount)
{
var nest = new Nest("sequence-all");
var drawing = TestHelpers.MakeSquareDrawing();
nest.Drawings.Add(drawing);
for (var i = 0; i < plateCount; i++)
{
var plate = TestHelpers.MakePlate(60, 120,
new Part(drawing, new Vector(10, 5)),
new Part(drawing, new Vector(30, 20)),
new Part(drawing, new Vector(20, 10)));
plate.Quantity = i + 1;
nest.Plates.Add(plate);
}
using var manager = new PlateManager(nest);
manager.EnsureSentinel();
manager.LoadFirst();
var plates = nest.Plates.Take(plateCount).ToArray();
var parameters = new SequenceParameters { Method = SequenceMethod.LeastCode };
var expected = plates.Select(plate => Baseline(plate, parameters)).ToArray();
var parts = plates.SelectMany(plate => plate.Parts)
.Select(part => (Part: part, part.Program, part.Location, part.Rotation)).ToArray();
var nested = drawing.Quantity.Nested;
var added = new int[plateCount];
for (var i = 0; i < plateCount; i++)
{
var index = i;
plates[i].PartAdded += (_, _) => added[index]++;
}
PlateSequencing.ApplyAll(nest.Plates, parameters);
Assert.Equal(plateCount + 1, nest.Plates.Count);
Assert.Equal(plates, nest.Plates.Take(plateCount));
Assert.Empty(nest.Plates[^1].Parts);
Assert.Same(plates[0], manager.CurrentPlate);
for (var i = 0; i < plateCount; i++)
{
Assert.Equal(expected[i], plates[i].Parts);
Assert.Equal(expected[i].Length, added[i]);
Assert.Equal(i + 1, plates[i].Quantity);
}
Assert.Equal(nested, drawing.Quantity.Nested);
foreach (var item in parts)
{
Assert.Same(item.Program, item.Part.Program);
Assert.Equal(item.Location, item.Part.Location);
Assert.Equal(item.Rotation, item.Part.Rotation);
}
}
[Fact]
public void ApplyAll_EmptyNestAndSentinelOnly_AreUnchanged()
{
var nest = new Nest("empty");
var parameters = new SequenceParameters { Method = SequenceMethod.LeastCode };
PlateSequencing.ApplyAll(nest.Plates, parameters);
Assert.Empty(nest.Plates);
using var manager = new PlateManager(nest);
manager.EnsureSentinel();
var sentinel = Assert.Single(nest.Plates);
PlateSequencing.ApplyAll(nest.Plates, parameters);
Assert.Same(sentinel, Assert.Single(nest.Plates));
Assert.Empty(sentinel.Parts);
}
[Fact]
public void ApplyAll_InvalidSequenceMethod_LeavesAllPlatesUntouched()
{
var nest = new Nest("invalid-sequence");
nest.Plates.Add(TestHelpers.MakePlate(60, 120, TestHelpers.MakePartAt(10, 5)));
nest.Plates.Add(TestHelpers.MakePlate(60, 120, TestHelpers.MakePartAt(30, 20)));
using var manager = new PlateManager(nest);
manager.EnsureSentinel();
var plates = nest.Plates.ToArray();
var parts = plates.Select(plate => plate.Parts.ToArray()).ToArray();
Assert.Throws<NotSupportedException>(() => PlateSequencing.ApplyAll(nest.Plates,
new SequenceParameters { Method = (SequenceMethod)999 }));
Assert.Equal(plates, nest.Plates);
for (var i = 0; i < plates.Length; i++)
Assert.Equal(parts[i], plates[i].Parts);
}
[Fact]
public void ApplyAll_WithManagedNest_PreservesCutOffDependenciesOnEveryPlate()
{
var nest = new Nest("sequence-all-cutoffs");
var plates = new[]
{
TestHelpers.MakePlate(60, 120, TestHelpers.MakePartAt(10, 10, 10)),
TestHelpers.MakePlate(60, 120, TestHelpers.MakePartAt(10, 30, 10)),
};
var parts = plates.Select(plate => Assert.Single(plate.Parts)).ToArray();
foreach (var plate in plates)
{
plate.CutOffs.Add(new CutOff(new Vector(15, 0), CutOffAxis.Vertical));
plate.RegenerateCutOffs(new CutOffSettings());
nest.Plates.Add(plate);
}
using var manager = new PlateManager(nest);
manager.EnsureSentinel();
PlateSequencing.ApplyAll(nest.Plates,
new SequenceParameters { Method = SequenceMethod.LeastCode });
for (var i = 0; i < plates.Length; i++)
AssertPrecedes(plates[i], Assert.Single(plates[i].CutOffs), parts[i]);
}
[Fact]
public void Apply_WithoutCutOffs_PreservesExistingReversedSequencerOrder()
{
var plate = TestHelpers.MakePlate(60, 120,
TestHelpers.MakePartAt(10, 5), TestHelpers.MakePartAt(30, 20),
TestHelpers.MakePartAt(20, 10));
var parameters = new SequenceParameters { Method = SequenceMethod.LeastCode };
var expected = Baseline(plate, parameters);
PlateSequencing.Apply(plate, parameters);
Assert.Equal(expected, plate.Parts);
}
[Theory]
[InlineData(CutOffAxis.Vertical, CutDirection.AwayFromOrigin)]
[InlineData(CutOffAxis.Vertical, CutDirection.TowardOrigin)]
[InlineData(CutOffAxis.Horizontal, CutDirection.AwayFromOrigin)]
[InlineData(CutOffAxis.Horizontal, CutDirection.TowardOrigin)]
public void Apply_MovesEveryCrossingCutOffBeforeEveryCrossedPart(
public void OrderCutOffsFirst_MovesEveryCrossingCutOffBeforeEveryCrossedPart(
CutOffAxis axis, CutDirection direction)
{
var drawing = TestHelpers.MakeSquareDrawing();
@@ -162,16 +31,15 @@ public class PlateSequencingTests
plate.CutOffs.Add(cutB);
var settings = new CutOffSettings { CutDirection = direction };
plate.RegenerateCutOffs(settings);
var parameters = new SequenceParameters { Method = SequenceMethod.LeastCode };
var baseline = Baseline(plate, parameters);
var route = plate.Parts.Reverse().ToList();
var programs = plate.Parts.Select(p => (Part: p, p.Program, p.Location, p.Rotation)).ToArray();
var nested = drawing.Quantity.Nested;
PlateSequencing.Apply(plate, parameters);
Order(plate, route);
AssertPrecedes(plate, cutA, first, second);
AssertPrecedes(plate, cutB, first, second);
Assert.Equal(baseline.Where(p => !p.BaseDrawing.IsCutOff),
Assert.Equal(route.Where(p => !p.BaseDrawing.IsCutOff),
plate.Parts.Where(p => !p.BaseDrawing.IsCutOff));
Assert.Equal(programs.Length, plate.Parts.Count);
Assert.Equal(nested, drawing.Quantity.Nested);
@@ -192,10 +60,9 @@ public class PlateSequencingTests
// The remnant's lines go last: the strip line stopping on the separator, then the separator.
[Theory]
[InlineData(SequenceMethod.RightSide)]
[InlineData(SequenceMethod.LeftSide)]
[InlineData(SequenceMethod.LeastCode)]
public void Apply_RemnantLines_AreCutLastInnerFirst(SequenceMethod method)
[InlineData(false)]
[InlineData(true)]
public void OrderCutOffsFirst_RemnantLines_AreCutLastInnerFirst(bool reversed)
{
var plate = new Plate(60, 120);
plate.Parts.Add(TestHelpers.MakePartAt(10, 10, 10));
@@ -205,9 +72,11 @@ public class PlateSequencingTests
plate.CutOffs.Add(horizontal);
plate.CutOffs.Add(vertical);
plate.RegenerateCutOffs(new CutOffSettings());
plate.Parts.Reorder([.. plate.Parts.Where(p => p.BaseDrawing.IsCutOff), .. plate.Parts.Where(p => !p.BaseDrawing.IsCutOff)]);
List<Part> route = [.. plate.Parts.Where(p => p.BaseDrawing.IsCutOff), .. plate.Parts.Where(p => !p.BaseDrawing.IsCutOff)];
if (reversed)
route.Reverse();
PlateSequencing.Apply(plate, new SequenceParameters { Method = method });
Order(plate, route);
Assert.Same(vertical.Drawing, plate.Parts[^2].BaseDrawing);
Assert.Same(horizontal.Drawing, plate.Parts[^1].BaseDrawing);
@@ -220,13 +89,9 @@ public class PlateSequencingTests
}
[Theory]
[InlineData(SequenceMethod.RightSide)]
[InlineData(SequenceMethod.LeftSide)]
[InlineData(SequenceMethod.BottomSide)]
[InlineData(SequenceMethod.EdgeStart)]
[InlineData(SequenceMethod.LeastCode)]
[InlineData(SequenceMethod.Advanced)]
public void Apply_AllMethodsAndQuadrants_RespectCutOffDependencies(SequenceMethod method)
[InlineData(false)]
[InlineData(true)]
public void OrderCutOffsFirst_AllQuadrants_RespectCutOffDependencies(bool reversed)
{
foreach (var quadrant in new[] { 1, 2, 3, 4 })
{
@@ -242,8 +107,11 @@ public class PlateSequencingTests
plate.CutOffs.Add(vertical);
plate.CutOffs.Add(horizontal);
plate.RegenerateCutOffs(new CutOffSettings());
var route = plate.Parts.ToList();
if (reversed)
route.Reverse();
PlateSequencing.Apply(plate, new SequenceParameters { Method = method });
Order(plate, route);
AssertPrecedes(plate, vertical, part);
AssertPrecedes(plate, horizontal, part);
@@ -251,10 +119,9 @@ public class PlateSequencingTests
}
[Theory]
[InlineData(CutOffAxis.Vertical, SequenceMethod.LeftSide)]
[InlineData(CutOffAxis.Horizontal, SequenceMethod.BottomSide)]
public void Apply_LimitedSameNamedCutOffs_OnlyMoveBeforePartsWithinTheirSpans(
CutOffAxis axis, SequenceMethod method)
[InlineData(CutOffAxis.Vertical)]
[InlineData(CutOffAxis.Horizontal)]
public void OrderCutOffsFirst_LimitedSameNamedCutOffs_OnlyMoveBeforePartsWithinTheirSpans(CutOffAxis axis)
{
var first = TestHelpers.MakePartAt(10, 10, 10);
var second = axis == CutOffAxis.Vertical
@@ -272,85 +139,68 @@ public class PlateSequencingTests
Assert.Equal(2, lowerParts.Length);
Assert.Equal(2, upperParts.Length);
PlateSequencing.Apply(plate, new SequenceParameters { Method = method });
Order(plate, [second, first, .. lowerParts, .. upperParts]);
Assert.Equal(upperParts.Append(second).Concat(lowerParts).Append(first), plate.Parts);
Assert.Equal(new[] { lower, upper }, plate.CutOffs);
}
[Fact]
public void Apply_SheetSeparatingCutOff_GoesAfterEveryPartAndCrossingCutOff()
[Theory]
[InlineData(false)]
[InlineData(true)]
public void OrderCutOffsFirst_SheetSeparatingCutOff_GoesAfterEveryPartAndCrossingCutOff(bool reversed)
{
var hazards = 0;
foreach (var method in Enum.GetValues<SequenceMethod>())
{
var left = TestHelpers.MakePartAt(10, 10, 10);
var right = TestHelpers.MakePartAt(80, 10, 10);
var plate = TestHelpers.MakePlate(60, 120, left, right);
var separator = new CutOff(new Vector(40, 0), CutOffAxis.Vertical);
var crossing = new CutOff(new Vector(85, 0), CutOffAxis.Vertical);
plate.CutOffs.Add(separator);
plate.CutOffs.Add(crossing);
plate.RegenerateCutOffs(new CutOffSettings());
var parameters = new SequenceParameters { Method = method };
var separatorPart = plate.Parts.Single(p => ReferenceEquals(p.BaseDrawing, separator.Drawing));
List<Part> baseline;
try
{
baseline = Baseline(plate, parameters).ToList();
}
catch (NotSupportedException)
{
continue;
}
if (baseline.IndexOf(separatorPart) < baseline.IndexOf(right)
|| baseline.IndexOf(separatorPart) < baseline.IndexOf(left))
hazards++;
var left = TestHelpers.MakePartAt(10, 10, 10);
var right = TestHelpers.MakePartAt(80, 10, 10);
var plate = TestHelpers.MakePlate(60, 120, left, right);
var separator = new CutOff(new Vector(40, 0), CutOffAxis.Vertical);
var crossing = new CutOff(new Vector(85, 0), CutOffAxis.Vertical);
plate.CutOffs.Add(separator);
plate.CutOffs.Add(crossing);
plate.RegenerateCutOffs(new CutOffSettings());
var separatorPart = plate.Parts.Single(p => ReferenceEquals(p.BaseDrawing, separator.Drawing));
// Without the rule, this route cuts the separator before the parts.
var cuts = plate.Parts.Where(p => p.BaseDrawing.IsCutOff).ToList();
if (reversed)
cuts.Reverse();
List<Part> route = [.. cuts, .. reversed ? new[] { right, left } : new[] { left, right }];
PlateSequencing.Apply(plate, parameters);
Order(plate, route);
Assert.Same(separatorPart, plate.Parts[^1]);
AssertPrecedes(plate, crossing, right);
Assert.Equal(5, plate.Parts.Count); // The crossing line is two segment parts.
}
// Without the rule, at least one route cuts the separator before a part.
Assert.True(hazards > 0);
Assert.Same(separatorPart, plate.Parts[^1]);
AssertPrecedes(plate, crossing, right);
Assert.Equal(5, plate.Parts.Count); // The crossing line is two segment parts.
}
[Fact]
public void Apply_OrphanedCutOff_ConservativelyPrecedesAllParts()
public void OrderCutOffsFirst_OrphanedCutOff_ConservativelyPrecedesAllParts()
{
var part = TestHelpers.MakePartAt(10, 10, 10);
var orphan = TestHelpers.MakePartAt(0, 0);
orphan.BaseDrawing.IsCutOff = true;
var plate = TestHelpers.MakePlate(60, 120, part, orphan);
PlateSequencing.Apply(plate,
new SequenceParameters { Method = SequenceMethod.LeftSide });
Order(plate, [part, orphan]);
Assert.Equal(new[] { orphan, part }, plate.Parts);
}
[Fact]
public void Apply_EmptyAndCutOffOnlyPlates_PreserveAllEntries()
public void OrderCutOffsFirst_EmptyAndCutOffOnlyRoutes_KeepTheirOrder()
{
var plate = new Plate(60, 120);
var parameters = new SequenceParameters { Method = SequenceMethod.LeastCode };
PlateSequencing.Apply(plate, parameters);
Assert.Empty(plate.Parts);
Assert.Empty(PlateSequencing.OrderCutOffsFirst([], plate));
plate.CutOffs.Add(new CutOff(new Vector(10, 0), CutOffAxis.Vertical));
plate.CutOffs.Add(new CutOff(new Vector(20, 0), CutOffAxis.Vertical));
plate.CutOffs.Add(new CutOff(new Vector(10, 0), CutOffAxis.Vertical) { EndLimit = 30 });
plate.CutOffs.Add(new CutOff(new Vector(20, 0), CutOffAxis.Vertical) { EndLimit = 30 });
plate.RegenerateCutOffs(new CutOffSettings());
var expected = Baseline(plate, parameters);
var route = plate.Parts.Reverse().ToList();
PlateSequencing.Apply(plate, parameters);
Assert.Equal(expected, plate.Parts);
Assert.Equal(route, PlateSequencing.OrderCutOffsFirst(route, plate));
}
[Fact]
public void Apply_SaveAndReload_PreservesCorrectedMixedSequence()
public void OrderCutOffsFirst_SaveAndReload_PreservesCorrectedMixedSequence()
{
var nest = new Nest("sequenced-cutoffs");
var drawing = TestHelpers.MakeSquareDrawing();
@@ -363,8 +213,7 @@ public class PlateSequencingTests
plate.CutOffs.Add(crossing);
plate.CutOffs.Add(tail);
plate.RegenerateCutOffs(new CutOffSettings());
PlateSequencing.Apply(plate,
new SequenceParameters { Method = SequenceMethod.LeftSide });
Order(plate, plate.Parts.Reverse().ToList());
AssertPrecedes(plate, crossing, part);
Assert.Equal(2, TestHelpers.CutOffParts(plate, crossing).Length); // Trimmed around the part.
Assert.Same(part, plate.Parts[2]);
@@ -379,47 +228,7 @@ public class PlateSequencingTests
}
[Fact]
public void Apply_InvalidSequenceMethod_LeavesPlateUntouched()
{
var plate = TestHelpers.MakePlate(60, 120, TestHelpers.MakePartAt(10, 5));
var before = plate.Parts.ToArray();
Assert.Throws<NotSupportedException>(() => PlateSequencing.Apply(plate,
new SequenceParameters { Method = (SequenceMethod)999 }));
Assert.Equal(before, plate.Parts);
}
[Theory]
[InlineData(SequenceMethod.RightSide)]
[InlineData(SequenceMethod.LeftSide)]
[InlineData(SequenceMethod.BottomSide)]
[InlineData(SequenceMethod.EdgeStart)]
[InlineData(SequenceMethod.LeastCode)]
[InlineData(SequenceMethod.Advanced)]
public void Apply_CutFirstDrawing_SequencesItsPartsBeforeEveryOtherPart(SequenceMethod method)
{
var squares = TestHelpers.MakeSquareDrawing(1.5);
squares.CutFirst = true;
var parts = TestHelpers.MakeSquareDrawing();
var plate = new Plate(60, 120);
for (var i = 0; i < 10; i++)
plate.Parts.Add(new Part(squares, new Vector(2 + i * 5, 50 + (i % 2) * 4)));
for (var i = 0; i < 6; i++)
plate.Parts.Add(new Part(parts, new Vector(5 + (i % 3) * 15, 5 + (i / 3) * 15)));
var parameters = new SequenceParameters { Method = method };
var others = plate.Parts.Where(p => !p.BaseDrawing.CutFirst).ToList();
var expectedRest = PartSequencerFactory.Create(parameters).Sequence(others, plate)
.Select(p => p.Part).Reverse().ToArray();
PlateSequencing.Apply(plate, parameters);
Assert.All(plate.Parts.Take(10), p => Assert.Same(squares, p.BaseDrawing));
Assert.Equal(expectedRest, plate.Parts.Skip(10));
}
[Fact]
public void Apply_CutFirstDrawing_StillFollowsCutOffsThatCrossIt()
public void OrderCutOffsFirst_CutFirstPart_StillFollowsCutOffsThatCrossIt()
{
var square = TestHelpers.MakePartAt(10, 10, 1.5);
square.BaseDrawing.CutFirst = true;
@@ -430,7 +239,7 @@ public class PlateSequencingTests
plate.CutOffs.Add(crossing);
plate.RegenerateCutOffs(new CutOffSettings());
PlateSequencing.Apply(plate, new SequenceParameters { Method = SequenceMethod.LeftSide });
Order(plate, [square, other, .. plate.Parts.Where(p => p.BaseDrawing.IsCutOff)]);
AssertPrecedes(plate, crossing, square);
Assert.Same(square, plate.Parts.First(p => !p.BaseDrawing.IsCutOff));
@@ -486,9 +295,8 @@ public class PlateSequencingTests
Assert.Equal(4, removed);
}
private static Part[] Baseline(Plate plate, SequenceParameters parameters) =>
PartSequencerFactory.Create(parameters).Sequence(plate.Parts.ToList(), plate)
.Select(p => p.Part).Reverse().ToArray();
private static void Order(Plate plate, List<Part> route) =>
plate.Parts.Reorder(PlateSequencing.OrderCutOffsFirst(route, plate));
// Each of the cut-off's segment parts precedes the crossed parts in its span of the line,
// and every crossed part follows at least one segment.
+17 -4
View File
@@ -1,5 +1,4 @@
using OpenNest.CNC;
using OpenNest.Engine.Sequencing;
using OpenNest.Geometry;
namespace OpenNest.Tests;
@@ -17,8 +16,9 @@ internal static class TestLeadIns
if (parameters == null)
return;
var sequenced = new LeftSideSequencer().Sequence(plate.Parts.ToList(), plate);
var exitPoint = PlateHelper.GetExitPoint(plate);
// Left to right, then bottom to top, starting from the plate's exit corner.
var sequenced = plate.Parts.OrderBy(p => p.Location.X).ThenBy(p => p.Location.Y).ToList();
var exitPoint = ExitPoint(plate);
// The first pass fixes each part's pierce; the second faces each part toward the next pierce.
var piercePoints = Pass(null);
Pass(piercePoints);
@@ -29,7 +29,7 @@ internal static class TestLeadIns
var current = exitPoint;
for (var i = 0; i < sequenced.Count; i++)
{
var part = sequenced[i].Part;
var part = sequenced[i];
if (!part.LeadInsLocked)
{
if (part.HasManualLeadIns)
@@ -47,6 +47,19 @@ internal static class TestLeadIns
}
}
private static Vector ExitPoint(Plate plate)
{
var xExtent = plate.Size.Length;
var yExtent = plate.Size.Width;
return plate.Quadrant switch
{
2 => new Vector(0, yExtent),
3 => new Vector(0, 0),
4 => new Vector(xExtent, 0),
_ => new Vector(xExtent, yExtent),
};
}
private static Vector Pierce(Part part)
{
foreach (var code in part.Program.Codes)
@@ -277,14 +277,6 @@ public class UndoRecordingTests
env.AssertOneUndoableEdit("Automatic Scrap Cutoffs", () => UndoTestEnv.Invoke(form, "ApplyButton_Click", null, EventArgs.Empty));
});
[Fact]
public void AutoSequencingRecordsOneEntry() => UndoTestEnv.Run(env =>
{
env.Editor.PlateManager.LoadAt(0);
env.AssertOneUndoableEdit("Auto Sequence", env.Editor.AutoSequenceCurrentPlate);
env.AssertOneUndoableEdit("Auto Sequence All Plates", env.Editor.AutoSequenceAllPlates);
}, NestOutOfOrder);
[Fact]
public void SetSequenceRecordsOneEntryPerClick() => UndoTestEnv.Run(env =>
{
@@ -682,20 +674,6 @@ public class UndoRecordingTests
return nest;
}
// Three squares in a row, cut middle, far, near: any sequencer reorders them.
private static Nest NestOutOfOrder()
{
var nest = UndoTestEnv.BuildNest();
var square = nest.Drawings.Single();
foreach (var plate in nest.Plates.Take(2))
{
plate.Parts.Clear();
foreach (var x in new[] { 35.0, 65.0, 5.0 })
plate.Parts.Add(new Part(square, new Vector(x, 5)));
}
return nest;
}
private static Nest NestWithLeadIns()
{
var nest = UndoTestEnv.BuildNest();
-35
View File
@@ -17,7 +17,6 @@ using OpenNest.Data.MaterialLedger;
using OpenNest.Desktop;
using OpenNest.Diagnostics;
using OpenNest.Engine;
using OpenNest.Engine.Sequencing;
using OpenNest.IO;
using OpenNest.Math;
using OpenNest.Properties;
@@ -1161,40 +1160,6 @@ namespace OpenNest.Forms
// The trailing empty plate comes back as the new-plate sentinel.
public void RemoveEmptyPlates() => PlateCommands.RemoveEmptyPlates(Nest, label => BeginChange(label));
public void AutoSequenceCurrentPlate()
{
var plate = PlateView.Plate;
using var change = BeginChange("Auto Sequence");
var before = CutOrder(plate).ToList();
SequencePlate(plate);
if (!CutOrder(plate).SequenceEqual(before))
change.MarkChanged();
change.Complete();
PlateView.Invalidate();
}
public void AutoSequenceAllPlates()
{
using var change = BeginChange("Auto Sequence All Plates");
var before = Nest.Plates.SelectMany(CutOrder).ToList();
var parameters = new SequenceParameters { Method = SequenceMethod.LeastCode };
PlateSequencing.ApplyAll(Nest.Plates, parameters);
if (!Nest.Plates.SelectMany(CutOrder).SequenceEqual(before))
change.MarkChanged();
change.Complete();
PlateView.Invalidate();
}
// Sequencing reorders parts and cut-offs; a plate already in order is left as it was.
private static IEnumerable<object> CutOrder(Plate plate) =>
plate.Parts.Cast<object>().Concat(plate.CutOffs);
private static void SequencePlate(Plate plate)
{
var parameters = new SequenceParameters { Method = SequenceMethod.LeastCode };
PlateSequencing.Apply(plate, parameters);
}
public void CalculateCurrentPlateCutTime() =>
ShowCutTime(cutparams => CutTimeReport.ForPlate(PlateView.Plate, cutparams, Nest.Units));
+2 -20
View File
@@ -114,7 +114,6 @@ namespace OpenNest.Forms
toolStripMenuItem12 = new System.Windows.Forms.ToolStripSeparator();
runAutoNestToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
mnuNestServerJobs = new System.Windows.Forms.ToolStripMenuItem();
autoSequenceAllPlatesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
mnuNestRemoveEmptyPlates = new System.Windows.Forms.ToolStripMenuItem();
mnuNestClear = new System.Windows.Forms.ToolStripMenuItem();
mnuNestValidate = new System.Windows.Forms.ToolStripMenuItem();
@@ -158,7 +157,6 @@ namespace OpenNest.Forms
mnuPlateRemoveCommonLine = new System.Windows.Forms.ToolStripMenuItem();
mnuPlateCutCommonLinesTwice = new System.Windows.Forms.ToolStripMenuItem();
mnuSequenceParts = new System.Windows.Forms.ToolStripMenuItem();
autoSequenceCurrentPlateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
manualSequenceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
sequenceByPathToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
calculateCutTimeToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
@@ -660,7 +658,7 @@ namespace OpenNest.Forms
//
// mnuNest
//
mnuNest.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { mnuNestEdit, mnuNestMachine, mnuNestClamps, mnuNestSupportGrid, mnuNestImportDrawing, mnuNestShapeLibrary, mnuNestDrawingLibrary, toolStripMenuItem7, mnuNestFirstPlate, mnuNestLastPlate, toolStripMenuItem6, mnuNestNextPlate, mnuNestPreviousPlate, toolStripMenuItem12, runAutoNestToolStripMenuItem, mnuNestServerJobs, autoSequenceAllPlatesToolStripMenuItem, mnuNestRemoveEmptyPlates, mnuNestClear, mnuNestValidate, mnuNestPost, toolStripMenuItem19, calculateCutTimeToolStripMenuItem, toolStripMenuItem22, mnuNestAutomaticCutOff, mnuNestPlanCutting, mnuNestRemoveLeadIns });
mnuNest.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { mnuNestEdit, mnuNestMachine, mnuNestClamps, mnuNestSupportGrid, mnuNestImportDrawing, mnuNestShapeLibrary, mnuNestDrawingLibrary, toolStripMenuItem7, mnuNestFirstPlate, mnuNestLastPlate, toolStripMenuItem6, mnuNestNextPlate, mnuNestPreviousPlate, toolStripMenuItem12, runAutoNestToolStripMenuItem, mnuNestServerJobs, mnuNestRemoveEmptyPlates, mnuNestClear, mnuNestValidate, mnuNestPost, toolStripMenuItem19, calculateCutTimeToolStripMenuItem, toolStripMenuItem22, mnuNestAutomaticCutOff, mnuNestPlanCutting, mnuNestRemoveLeadIns });
mnuNest.Name = "mnuNest";
mnuNest.Size = new System.Drawing.Size(43, 20);
mnuNest.Text = "&Nest";
@@ -778,13 +776,6 @@ namespace OpenNest.Forms
mnuNestServerJobs.Text = "My Server Jobs...";
mnuNestServerJobs.Click += ServerJobs_Click;
//
// autoSequenceAllPlatesToolStripMenuItem
//
autoSequenceAllPlatesToolStripMenuItem.Name = "autoSequenceAllPlatesToolStripMenuItem";
autoSequenceAllPlatesToolStripMenuItem.Size = new System.Drawing.Size(205, 22);
autoSequenceAllPlatesToolStripMenuItem.Text = "Auto Sequence All Plates";
autoSequenceAllPlatesToolStripMenuItem.Click += SequenceAllPlates_Click;
//
// mnuNestRemoveEmptyPlates
//
mnuNestRemoveEmptyPlates.Name = "mnuNestRemoveEmptyPlates";
@@ -1095,18 +1086,11 @@ namespace OpenNest.Forms
//
// mnuSequenceParts
//
mnuSequenceParts.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { autoSequenceCurrentPlateToolStripMenuItem, manualSequenceToolStripMenuItem, sequenceByPathToolStripMenuItem });
mnuSequenceParts.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { manualSequenceToolStripMenuItem, sequenceByPathToolStripMenuItem });
mnuSequenceParts.Name = "mnuSequenceParts";
mnuSequenceParts.Size = new System.Drawing.Size(177, 22);
mnuSequenceParts.Text = "Sequence Parts";
//
// autoSequenceCurrentPlateToolStripMenuItem
//
autoSequenceCurrentPlateToolStripMenuItem.Name = "autoSequenceCurrentPlateToolStripMenuItem";
autoSequenceCurrentPlateToolStripMenuItem.Size = new System.Drawing.Size(168, 22);
autoSequenceCurrentPlateToolStripMenuItem.Text = "Auto Sequence";
autoSequenceCurrentPlateToolStripMenuItem.Click += AutoSequenceCurrentPlate_Click;
//
// manualSequenceToolStripMenuItem
//
manualSequenceToolStripMenuItem.Name = "manualSequenceToolStripMenuItem";
@@ -1583,10 +1567,8 @@ namespace OpenNest.Forms
private System.Windows.Forms.ToolStripMenuItem closeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem runAutoNestToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem mnuNestServerJobs;
private System.Windows.Forms.ToolStripMenuItem autoSequenceCurrentPlateToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem manualSequenceToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem sequenceByPathToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem autoSequenceAllPlatesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem mnuToolsMeasureArea;
private System.Windows.Forms.ToolStripMenuItem mnuToolsBestFitViewer;
private System.Windows.Forms.ToolStripMenuItem mnuPlatePatternTile;
-1
View File
@@ -253,7 +253,6 @@ namespace OpenNest.Forms
}
}
private void SequenceAllPlates_Click(object sender, EventArgs e) => WithActive(f => f.AutoSequenceAllPlates());
private void ValidateNest_Click(object sender, EventArgs e)
{
-1
View File
@@ -38,7 +38,6 @@ namespace OpenNest.Forms
private void SimulateCutting_Click(object sender, EventArgs e) => WithActive(f => f.SimulateCutting());
private void AutoSequenceCurrentPlate_Click(object sender, EventArgs e) => WithActive(f => f.AutoSequenceCurrentPlate());
private void ManualSequenceParts_Click(object sender, EventArgs e)
{
+4 -6
View File
@@ -90,17 +90,15 @@ The program marks the locked stretch with `HEAD HEIGHT LOCK` and `HEAD HEIGHT UN
For **Plate > Sequence Parts > Manual Sequence**, choose the one-based sequence number and hover a part on the sheet; only the part under the pointer is outlined. Click it to place it at that exact position, then the number advances up to the last part. Clicking empty sheet space changes nothing. Use **Done**, the window close button, right-click on the sheet, or Escape to leave the tool. Manual reordering changes neither geometry nor quantities.
For **Plate > Sequence Parts > Sequence by Path**, drag lines over the sheet with the left button in the order you want the parts cut; clicking a part adds it as a one-point line that claims the parts whose bounding boxes hold the click. Lifting the button between lines is a rapid: the dashed jump to the next line's numbered start claims no parts. Each part belongs to the line crossing its bounding box that passes closest to its bounding-box center, and lines are cut in drawing order, each in the order its nearest points fall along it; where a line passes a part more than once, the closest pass decides. Parts no line crosses are cut after all the others, in the order they would follow their nearest line, and are drawn muted until a line or click reaches them. The numbers update as you drag, and the plate is reordered when you release. **Undo Line**, Backspace or Ctrl+Z removes the last line; **Clear** or right-click removes them all and restores the order the tool started with. Cut-first parts stay ahead of the rest, and cutoffs follow the same dependency rules as Part Sequencing below. Escape mid-drag drops only that line; otherwise Escape, **Done** or closing the window leaves the tool.
For **Plate > Sequence Parts > Sequence by Path**, drag lines over the sheet with the left button in the order you want the parts cut; clicking a part adds it as a one-point line that claims the parts whose bounding boxes hold the click. Lifting the button between lines is a rapid: the dashed jump to the next line's numbered start claims no parts. Each part belongs to the line crossing its bounding box that passes closest to its bounding-box center, and lines are cut in drawing order, each in the order its nearest points fall along it; where a line passes a part more than once, the closest pass decides. Parts no line crosses are cut after all the others, in the order they would follow their nearest line, and are drawn muted until a line or click reaches them. The numbers update as you drag, and the plate is reordered when you release. **Undo Line**, Backspace or Ctrl+Z removes the last line; **Clear** or right-click removes them all and restores the order the tool started with. Cut-first parts stay ahead of the rest, and cutoffs follow the cutoff ordering rules below. Escape mid-drag drops only that line; otherwise Escape, **Done** or closing the window leaves the tool.
After adding cutoffs, apply **Part Sequencing** to the current plate or all plates. Each trimmed segment of a cutoff is a part of its own in the sequence, and each is moved earlier as needed so it is cut before every part its nominal line passes through within the segment's span: the stretch of the line from the end of the segment before it to the start of the one after it (or the line's start or end). The parts a line passes through lie in the gaps between its segments, so each is cut after the segment on either side of it and no other; the segment below a row of parts is cut with that row, not before a row the line passes through farther on. Segments due before the same part keep the order they were regenerated in. Ordinary parts retain their relative order from the chosen sequencing route. A cutoff that splits the whole sheet — one continuous cut from sheet edge to sheet edge, such as a tail separator — goes after every part and every other cutoff, so the head never travels back across the separated edge. So does one continuous cut from a sheet edge or such a separator to another, such as the last strip line stopping at a horizontal remnant separator: it frees a remnant with the lines it stops on, and goes just before them, so the remnants' mass stays on the sheet to absorb heat until the parts are cut. Cutoffs that cross no part but leave gaps keep their normal route position. Cutoff geometry, clearance, part programs, placements, and quantities are unchanged.
The cut order comes from Plan Cutting or from the user (Manual Sequence, Sequence by Path); OpenNest has no automatic part sequencer of its own. Sequence by Path (`PlateSequencing.OrderCutOffsFirst`) and placing new or moved cutoffs (`PlateSequencing.PlaceCutOffs`) apply these ordering rules. Each trimmed segment of a cutoff is a part of its own in the sequence, and each is moved earlier as needed so it is cut before every part its nominal line passes through within the segment's span: the stretch of the line from the end of the segment before it to the start of the one after it (or the line's start or end). The parts a line passes through lie in the gaps between its segments, so each is cut after the segment on either side of it and no other; the segment below a row of parts is cut with that row, not before a row the line passes through farther on. Segments due before the same part keep the order they were regenerated in. Ordinary parts retain their relative order from the route. A cutoff that splits the whole sheet — one continuous cut from sheet edge to sheet edge, such as a tail separator — goes after every part and every other cutoff, so the head never travels back across the separated edge. So does one continuous cut from a sheet edge or such a separator to another, such as the last strip line stopping at a horizontal remnant separator: it frees a remnant with the lines it stops on, and goes just before them, so the remnants' mass stays on the sheet to absorb heat until the parts are cut. Cutoffs that cross no part but leave gaps keep their normal route position. Cutoff geometry, clearance, part programs, placements, and quantities are unchanged.
The dependency check uses the nominal horizontal/vertical line within the segment's span, not the trimmed cutting segment itself, which intentionally skips the parts (`CutOffSegments` measures the spans from the segment parts). It conservatively checks placed part bounds (including edge contacts), so a cutoff through a concave recess can also move ahead of that part. Definitions are matched by drawing identity, not their displayed names. A cutoff part with no matching definition is conservatively ordered before all ordinary parts, and a segment part whose cut cannot be measured stands for the whole line.
Drawings marked **Cut first** in the drawing editor (for example test squares) are sequenced ahead of every other part: their parts get their own route with the chosen method, then the remaining parts follow on theirs. A cutoff that crosses a cut-first part is still cut before it.
Drawings marked **Cut first** in the drawing editor (for example test squares) are sequenced ahead of every other part: Sequence by Path orders their parts first, then the remaining parts. A cutoff that crosses a cut-first part is still cut before it.
This rule runs when applying automatic sequencing, after reversing the exit-first sequencer route into cutting order. Manual sequence edits are still manual; adding or moving cutoffs does not automatically reapply this rule. Reapply Part Sequencing after layout changes and review the resulting rapids before posting. Regeneration and saving/reloading retain the applied mixed sequence.
The all-plates command uses `PlateSequencing.ApplyAll`, which snapshots the target plate references before sequencing. Reordering parts raises collection events that can replace the nest's trailing empty plate; those events must not invalidate the batch's iteration or skip any original plate. This snapshot is not a transaction or a concurrency guard: sequencing still runs synchronously on the owning thread, using the same per-plate cutoff rules.
Manual Sequence edits are still manual and are not corrected. Review the resulting rapids before posting. Regeneration and saving/reloading retain the applied mixed sequence.
## Rerunning, editing, and saving
+1 -1
View File
@@ -40,7 +40,7 @@ uses the Cincinnati machine-sample convention, not a generic TF5200 laser API:
- Motion endpoints are sheet-absolute XY. Arc `I`/`J` are offsets from the arc
start, matching the G162 convention; the post does not explicitly emit G162.
- Parts and sheet cut-offs post in the plate's cut sequence (`Plate.Parts`
order, as set by Set Sequence or a sequencer). A cut-off is not moved after
order, as set by Plan Cutting or Set Sequence). A cut-off is not moved after
the parts. Each segment is an open
line with no lead-in: rapid to its start, `/L "L4"`, `/L "L6"`, the `G1`,
and `/L "ZHSOFF"`. No `G41`/`G42` is selected, because the line is the beam
+1 -1
View File
@@ -906,7 +906,7 @@ one, exactly as before. Expanded sheets list each frame's inserts immediately be
at every level (innermost first), so the committed part order cuts every insert before the cutout
that would release its slug.
Leads are not changed: pre-post verification still warns when a host's hole lead or an insert's
lead meets the other part, or when a later reorder (by hand or Auto Sequence) puts the host
lead meets the other part, or when a later reorder (by hand) puts the host
first (see [pre-post verification](post-verification.md)); Plan Cutting cuts each insert before
its frame and refuses a kept order that does not. Engine benchmarks call engines directly and do
not run this pre-pass; internal `NestPipeline.RunWithoutCutouts` is the ordinary-solve baseline
+14 -14
View File
@@ -3,7 +3,7 @@
`OpenNest.Core/CNC/Thermal/PlateHeatSimulation.cs` estimates how heat builds up in the sheet
while a [cut simulation](cut-time-estimates.md) plays. The Cut Simulator shows it under the cut
trail (Heat: Now or Peak so far). It is a display and analysis aid and never changes the plate;
a parked [heat-aware sequencer](#sequencing) uses a cheaper estimate of the same physics.
a removed heat-aware sequencer used a cheaper estimate of the same physics ([Sequencing](#sequencing)).
## Model
@@ -77,26 +77,26 @@ bed, and its heat label says whether the sheet is cooled by air only or by air a
## Sequencing
`SequenceMethod.HeatAware` is a heat-aware part sequencer,
parked until FLIR thermal-camera readings calibrate the model. It is available to
`PlateSequencing.Apply(plate, parameters, thermal)` only: Plan Cutting does not use it, and no UI
offers it. The method and `SequenceParameters.HeatWeight` (seconds per °C, 0.15 by default) are
saved with the cutting settings.
A heat-aware part sequencer was tried and removed: the cut order comes from Plan Cutting or the
user, and OpenNest keeps no automatic part sequencers (the code is in git history before the
commit that removed them). A heat-aware order belongs in Plan Cutting's search once FLIR
thermal-camera readings calibrate the model. `SequenceMethod.HeatAware` and
`SequenceParameters.HeatWeight` are still read and written with the cutting settings, but nothing
orders parts by them. What was tried:
- Order (`OpenNest.Engine/Sequencing/HeatAwareOrder.cs`): a forward greedy from the plate's origin
corner. The next part is the one with the least travel seconds plus `HeatWeight` times the
estimated temperature at its center when the tool gets there. Cut-offs go last in its route, and
`OrderCutOffsFirst` places them as for every method. Without a thickness it is nearest neighbor.
- Estimate (`HeatSpreadEstimate`): each finished part leaves a Gaussian blob of its energy
- Order: a forward greedy from the plate's origin corner. The next part was the one with the least
travel seconds plus `HeatWeight` (seconds per °C, 0.15 by default) times the estimated
temperature at its center when the tool got there. Without a thickness it was nearest neighbor.
- Estimate: each finished part left a Gaussian blob of its energy
(`AbsorbedPower` times its torch-on time), as wide as the part to begin with (a quarter of its
squared diagonal), widening by 4αΔt and fading with the surface loss; only the latest 200 parts
count. Torch-on time comes from each part's cut length and pierces at stand-in feeds by
thickness: 400 in/min up to 0.135 in, 150 up to 0.26 in, 80 above, a 0.5 s pierce up to 0.26 in
and 1.5 s above, and 3000 in/min travel.
Why it is parked: Plan Cutting does not follow `SequenceMethod`. It plans its own shortest tour
(nearest neighbor, 2-opt, Or-opt), which already travels a fraction of the row-based `Advanced`
sequencer's distance, so the heat order's travel savings over `Advanced` do not carry over. And its
Why it did not help: Plan Cutting plans its own shortest tour (nearest neighbor, 2-opt, Or-opt),
which already traveled a fraction of the removed row-based `Advanced` sequencer's distance, so the
heat order's travel savings over `Advanced` did not carry over. And its
strict search refuses head-down rapids over parts already cut free. A heat-spreading order skips
neighbors and comes back to them across cut parts, so the search stalls, learns rules, and ends on
its shortest tour or the safest-route fallback; a heat order used only where it does not stall
+1 -1
View File
@@ -28,7 +28,7 @@ Everything stored in the nest:
list or its right-click menu), Move Plate (dragging a row in the Plates list or
Alt+Up/Alt+Down), Edit Plate (its sheet outline included), rotate,
resize, cutting parameters, clamps and clamp rail, the support grid, the nest's default plate;
- cutting: manual and automatic cut-offs and their drags, Auto Sequence, Set Sequence,
- cutting: manual and automatic cut-offs and their drags, Set Sequence,
Sequence by Path, placing and removing lead-ins, Plan Cutting's Apply, clearing lead-ins and
cut-offs;
- drawings: import, Shape Library, edit in the converter, drawing properties and quantities, delete, clean