mirror of
https://github.com/ajisaacs/OpenNest.git
synced 2026-11-17 15:27:40 -05:00
feat(engine): pack mixed jobs in full-height strips in Irregular
Irregular decodes the job once more in full-height strips along X when like parts group and every part shares one priority. A sheet that can take all the remaining parts is packed two ways and the better kept: - Bands: each type of three or more copies as its Lattice pattern in the narrowest strip that holds all its copies, bands side by side, the held-back copies and one-offs filling the gaps. - Strips: each strip holds the largest remaining part, as its band or a column one to three copies wide, every other part filling its gaps; a beam of the four densest partial sheets carries strip to strip. Band patterns are filled one grid unit wider than the spacing so a stack of rings passes the strict certification, members on a clamp go to the gap fill, and a short band moves flush to the far edge when that keeps it off the clamps. The plan replaces the result only by beating it. On seven sample parts (130 copies, 60 x 120) the layout ends at 102.9" instead of 107.7", and at 104.6" instead of 108.6" with the desktop's edge spacing and bottom clamp rail; at about twice the quantities the second sheet ends at 104.7" instead of 106.2". Every other benchmark job is unchanged. Solves of these jobs take about twice as long. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
163a9c83d9
commit
81e70af5b6
15 files changed
+23807
-19
No files matched your search
@@ -0,0 +1,398 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using Clipper2Lib;
|
||||
using OpenNest.Engine.Jobs;
|
||||
using OpenNest.Geometry;
|
||||
|
||||
namespace OpenNest.Engine.NestingEngines.Irregular;
|
||||
|
||||
/// <summary>
|
||||
/// Fills one sheet in full-height strips along its length, two ways.
|
||||
///
|
||||
/// <see cref="Fill"/> lays each like-part group out as a band: the group's Lattice pattern (the one
|
||||
/// interactive Fill gives that part alone, so a round part stacks, a hexagon tiles and an L
|
||||
/// interlocks with its pair) in the narrowest strip that holds all its copies. Bands stand side
|
||||
/// by side, then the copies held back from them and the types too few to band fill the gaps.
|
||||
///
|
||||
/// <see cref="FillStrips"/> builds each strip as densely as it can from any parts: the strip holds
|
||||
/// the largest remaining part, as its band or as a column of it, and every other part fills the
|
||||
/// strip's gaps, so big parts go first and small ones fill around them.
|
||||
///
|
||||
/// A person nesting many copies of a few parts lays them out in tidy columns; a frontier packer
|
||||
/// placing one part at a time instead leaves every group's last column ragged and scatters the
|
||||
/// smallest parts into the gaps between groups.
|
||||
/// </summary>
|
||||
internal sealed class BandedFill(
|
||||
IReadOnlyList<PartType> types,
|
||||
BlockCatalog blocks,
|
||||
NestPlateStock stock,
|
||||
ClampObstacles? clamps,
|
||||
Func<FrontierPacker> packer,
|
||||
Comparison<SheetFill> compare,
|
||||
WorkCounter counter,
|
||||
long budget)
|
||||
{
|
||||
/// <summary>Fewest copies a band may hold back to be narrower; a third of them when more.</summary>
|
||||
private const int MaxHeldBack = 4;
|
||||
|
||||
private sealed record Band(int Type, int Copies, double Length, IReadOnlyList<Placed> Members);
|
||||
|
||||
/// <summary>The fill, or null when nothing bands on this sheet.</summary>
|
||||
public SheetFill? Fill(IReadOnlyList<int> remaining, CancellationToken token)
|
||||
{
|
||||
if (stock.Outline != null)
|
||||
return null;
|
||||
var region = stock.WorkArea;
|
||||
var grouped = types.Where(t => remaining[t.Index] >= GroupedFill.MinGroup && t.Orientations.Count > 0)
|
||||
.Select(t => t.Index).ToArray();
|
||||
if (grouped.Length == 0)
|
||||
return null;
|
||||
// Per type, its narrowest full band first, then narrower bands holding fewer copies.
|
||||
var options = new Dictionary<int, List<Band>>();
|
||||
foreach (var (t, list) in grouped.Zip(BandsInParallel(grouped, remaining, region, token)))
|
||||
if (list.Count > 0)
|
||||
options[t] = list;
|
||||
if (options.Count == 0)
|
||||
return null;
|
||||
var bands = options.ToDictionary(o => o.Key, o => o.Value[0]);
|
||||
|
||||
// Both orders with every band full; then, on the better one, hold back copies band by
|
||||
// band while that improves the sheet.
|
||||
var orders = new[]
|
||||
{
|
||||
bands.Values.OrderByDescending(b => b.Length).ThenBy(b => b.Type).Select(b => b.Type).ToArray(),
|
||||
bands.Values.OrderBy(b => b.Length).ThenBy(b => b.Type).Select(b => b.Type).ToArray(),
|
||||
};
|
||||
int[]? bestOrder = null;
|
||||
SheetFill? best = null;
|
||||
foreach (var order in orders)
|
||||
{
|
||||
var fill = Run(order, order.ToDictionary(t => t, _ => 0), options, remaining, region, token);
|
||||
if (best == null || compare(fill, best) < 0)
|
||||
{
|
||||
best = fill;
|
||||
bestOrder = order;
|
||||
}
|
||||
}
|
||||
var choice = bestOrder!.ToDictionary(t => t, _ => 0);
|
||||
foreach (var t in bestOrder!)
|
||||
for (var k = 1; k < options[t].Count && counter.Value < budget; k++)
|
||||
{
|
||||
var trial = new Dictionary<int, int>(choice) { [t] = k };
|
||||
var candidate = Run(bestOrder, trial, options, remaining, region, token);
|
||||
if (compare(candidate, best!) < 0)
|
||||
{
|
||||
best = candidate;
|
||||
choice = trial;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Strip by strip: each strip holds the largest remaining part, either as its Lattice band
|
||||
/// (full or holding fewer copies) or packed largest part first in a strip one to three copies
|
||||
/// wide, and every other part fills the strip's gaps, largest piece first. A beam of the
|
||||
/// <see cref="Beam"/> partial sheets densest so far (part area per unit of length used) is
|
||||
/// carried strip to strip, so a strip is judged by what it leaves for the rest of the sheet,
|
||||
/// not by its own density alone; the best finished sheet wins.
|
||||
/// </summary>
|
||||
public SheetFill? FillStrips(IReadOnlyList<int> remaining, Func<Box, FrontierPacker> within, CancellationToken token)
|
||||
{
|
||||
if (stock.Outline != null)
|
||||
return null;
|
||||
var region = stock.WorkArea;
|
||||
var spacing = System.Math.Max(0, stock.PartSpacing);
|
||||
var bandCache = new Dictionary<(int, int), List<Band>>();
|
||||
var lookBack = types.Where(t => remaining[t.Index] > 0).SelectMany(t => t.Orientations)
|
||||
.Select(o => System.Math.Max(o.Width, o.Height)).DefaultIfEmpty(0).Max();
|
||||
var beam = new List<StripState> { new(new List<Placed>(), remaining.ToArray(), 0, region.Left) };
|
||||
var finished = new List<StripState>();
|
||||
while (beam.Count > 0)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var children = new List<StripState>();
|
||||
foreach (var state in beam)
|
||||
{
|
||||
var largest = types.Where(t => state.Rest[t.Index] > 0 && t.Orientations.Count > 0)
|
||||
.OrderByDescending(t => t.Area).ThenBy(t => t.Index).FirstOrDefault();
|
||||
if (largest == null || state.Front >= region.Right || counter.Value >= budget)
|
||||
{
|
||||
finished.Add(state);
|
||||
continue;
|
||||
}
|
||||
var t = largest.Index;
|
||||
var start = state.Placed.Count == 0 ? state.Front : state.Front + spacing;
|
||||
var offered = 0;
|
||||
void Offer(List<Placed> seatedNow, double end)
|
||||
{
|
||||
var reach = System.Math.Min(region.Right, end + 1e-6);
|
||||
if (reach <= state.Front)
|
||||
return;
|
||||
var counts = state.Rest.ToArray();
|
||||
foreach (var p in seatedNow)
|
||||
counts[p.Orientation.TypeIndex]--;
|
||||
var all = state.Placed.Concat(seatedNow).ToList();
|
||||
// The gap fill looks back one part length behind the strip: gaps further back
|
||||
// were filled with earlier strips, and parts there cost nothing to skip.
|
||||
var left = System.Math.Max(region.Left, start - lookBack);
|
||||
var fill = counts.Any(c => c > 0)
|
||||
? within(new Box(left, region.Bottom, reach - left, region.Width)).Fill(counts, token, all, region.Top)
|
||||
: new SheetFill(stock, Array.Empty<Placed>(), 0);
|
||||
var parts = seatedNow.Concat(fill.Parts).ToList();
|
||||
if (parts.Count == 0 || !parts.Any(p => p.Orientation.TypeIndex == t))
|
||||
return;
|
||||
var rest = state.Rest.ToArray();
|
||||
foreach (var p in parts)
|
||||
rest[p.Orientation.TypeIndex]--;
|
||||
children.Add(new StripState(all.Concat(fill.Parts).ToList(), rest,
|
||||
state.Area + parts.Sum(p => types[p.Orientation.TypeIndex].Area),
|
||||
System.Math.Max(state.Front, parts.Max(p => p.Right))));
|
||||
offered++;
|
||||
}
|
||||
if (state.Rest[t] >= GroupedFill.MinGroup)
|
||||
{
|
||||
if (!bandCache.TryGetValue((t, state.Rest[t]), out var bands))
|
||||
bandCache[(t, state.Rest[t])] = bands = Bands(t, state.Rest[t], region, token);
|
||||
foreach (var band in bands)
|
||||
{
|
||||
if (band.Length > region.Right - start + 1e-9)
|
||||
continue;
|
||||
var members = Seat(band, start, region);
|
||||
if (members.Count > 0)
|
||||
Offer(members, members.Max(p => p.Right));
|
||||
}
|
||||
}
|
||||
// Strip widths of one to three copies across, each distinct width once.
|
||||
var widths = new List<double>();
|
||||
foreach (var o in largest.Orientations)
|
||||
for (var k = 1; k <= 3; k++)
|
||||
{
|
||||
var width = k * o.Width + (k - 1) * spacing;
|
||||
if (!widths.Any(w => System.Math.Abs(w - width) < 0.05))
|
||||
widths.Add(width);
|
||||
}
|
||||
foreach (var width in widths.OrderBy(w => w))
|
||||
Offer(new List<Placed>(), start + width);
|
||||
if (offered == 0)
|
||||
finished.Add(state);
|
||||
}
|
||||
double Rank(StripState c) => -c.Area / System.Math.Max(c.Front - region.Left, 1e-9);
|
||||
beam = new List<StripState>();
|
||||
foreach (var child in children.OrderBy(Rank).ThenBy(c => c.Front))
|
||||
{
|
||||
if (beam.Count >= Beam)
|
||||
break;
|
||||
if (beam.Any(b => System.Math.Abs(b.Front - child.Front) < 1e-6 && System.Math.Abs(b.Area - child.Area) < 1e-6
|
||||
&& b.Rest.SequenceEqual(child.Rest)))
|
||||
continue;
|
||||
beam.Add(child);
|
||||
}
|
||||
}
|
||||
SheetFill? best = null;
|
||||
foreach (var state in finished)
|
||||
{
|
||||
var placed = state.Placed.ToList();
|
||||
var partArea = state.Area;
|
||||
if (state.Rest.Any(r => r > 0))
|
||||
{
|
||||
var tail = packer().Fill(state.Rest, token, placed);
|
||||
placed.AddRange(tail.Parts);
|
||||
partArea += tail.PartArea;
|
||||
}
|
||||
var sheet = new SheetFill(stock, placed, partArea);
|
||||
if (best == null || compare(sheet, best) < 0)
|
||||
best = sheet;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>Partial sheets carried strip to strip.</summary>
|
||||
private const int Beam = 4;
|
||||
|
||||
private sealed record StripState(List<Placed> Placed, int[] Rest, double Area, double Front);
|
||||
|
||||
/// <summary>A band's members starting at <paramref name="front"/>, flush to the bottom, or to
|
||||
/// the top when that keeps more of them off the clamps; members on a clamp are left out.</summary>
|
||||
private List<Placed> Seat(Band band, double front, Box region)
|
||||
{
|
||||
var minX = band.Members.Min(p => p.Left);
|
||||
var minY = band.Members.Min(p => p.Bottom);
|
||||
var maxY = band.Members.Max(p => p.Top);
|
||||
List<Placed> Shifted(double dy) => band.Members
|
||||
.Select(m => new Placed(m.Orientation, m.X + front - minX, m.Y + dy)).Where(p => !OnClamp(p)).ToList();
|
||||
var members = Shifted(region.Bottom - minY);
|
||||
if (members.Count < band.Members.Count && region.Top - maxY > region.Bottom - minY + 1e-9)
|
||||
{
|
||||
var top = Shifted(region.Top - maxY);
|
||||
if (top.Count > members.Count)
|
||||
members = top;
|
||||
}
|
||||
return members;
|
||||
}
|
||||
|
||||
/// <summary>The bands placed left to right in <paramref name="order"/>, then everything
|
||||
/// else filling around them.</summary>
|
||||
private SheetFill Run(int[] order, Dictionary<int, int> choice, Dictionary<int, List<Band>> options,
|
||||
IReadOnlyList<int> remaining, Box region, CancellationToken token)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var seated = new List<Placed>();
|
||||
var rest = remaining.ToArray();
|
||||
var front = region.Left;
|
||||
var spacing = System.Math.Max(0, stock.PartSpacing);
|
||||
foreach (var t in order)
|
||||
{
|
||||
var band = options[t][choice[t]];
|
||||
var room = region.Right - front;
|
||||
if (room <= 0)
|
||||
break;
|
||||
if (band.Length > room + 1e-9)
|
||||
{
|
||||
// The sheet ends inside this band: as many copies as the room left holds.
|
||||
var partial = Pattern(t, band.Copies, room, region.Width, token);
|
||||
if (partial == null)
|
||||
continue;
|
||||
band = partial;
|
||||
}
|
||||
var minX = band.Members.Min(p => p.Left);
|
||||
var minY = band.Members.Min(p => p.Bottom);
|
||||
var maxY = band.Members.Max(p => p.Top);
|
||||
// Flush to the bottom, or to the top when that keeps more copies off the clamps.
|
||||
List<Placed> Shifted(double dy) => band.Members
|
||||
.Select(m => new Placed(m.Orientation, m.X + front - minX, m.Y + dy)).Where(p => !OnClamp(p)).ToList();
|
||||
var members = Shifted(region.Bottom - minY);
|
||||
if (members.Count < band.Members.Count && region.Top - maxY > region.Bottom - minY + 1e-9)
|
||||
{
|
||||
var top = Shifted(region.Top - maxY);
|
||||
if (top.Count > members.Count)
|
||||
members = top;
|
||||
}
|
||||
var maxX = front;
|
||||
foreach (var placed in members)
|
||||
{
|
||||
seated.Add(placed);
|
||||
rest[t]--;
|
||||
maxX = System.Math.Max(maxX, placed.Right);
|
||||
}
|
||||
front = maxX + spacing;
|
||||
}
|
||||
var parts = seated.ToList();
|
||||
var partArea = seated.Sum(p => types[p.Orientation.TypeIndex].Area);
|
||||
if (rest.Any(r => r > 0))
|
||||
{
|
||||
var leftovers = packer().Fill(rest, token, seated);
|
||||
parts.AddRange(leftovers.Parts);
|
||||
partArea += leftovers.PartArea;
|
||||
}
|
||||
return new SheetFill(stock, parts, partArea);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The type's bands of full region height, narrowest full one first, then each narrower one
|
||||
/// holding at most <see cref="HeldBack"/> fewer copies. Lattice patterns grow in whole rows or
|
||||
/// columns, so each next band is asked for just short of the last one's length, and a few
|
||||
/// halvings toward the area bound catch patterns the steps skip.
|
||||
/// </summary>
|
||||
private List<Band> Bands(int t, int copies, Box region, CancellationToken token)
|
||||
{
|
||||
var type = types[t];
|
||||
var fewest = copies - HeldBack(copies);
|
||||
var found = new List<Band>();
|
||||
void Keep(Band band)
|
||||
{
|
||||
if (band.Copies >= fewest && !found.Any(b => b.Copies >= band.Copies && b.Length <= band.Length + 1e-6))
|
||||
{
|
||||
found.RemoveAll(b => b.Copies <= band.Copies && b.Length >= band.Length - 1e-6);
|
||||
found.Add(band);
|
||||
}
|
||||
}
|
||||
var length = region.Length;
|
||||
for (var step = 0; step < MaxSteps; step++)
|
||||
{
|
||||
var band = Pattern(t, copies, length, region.Width, token);
|
||||
if (band == null || band.Copies < fewest)
|
||||
break;
|
||||
Keep(band);
|
||||
length = band.Length - StepShort;
|
||||
}
|
||||
var full = found.Where(b => b.Copies >= copies).OrderBy(b => b.Length).FirstOrDefault();
|
||||
if (full == null)
|
||||
return new List<Band>();
|
||||
var lo = System.Math.Max(type.Orientations.Min(o => System.Math.Min(o.Width, o.Height)),
|
||||
copies * type.Area / region.Width);
|
||||
var hi = full.Length;
|
||||
for (var probe = 0; probe < Probes && hi - lo > StepShort; probe++)
|
||||
{
|
||||
var mid = (lo + hi) / 2;
|
||||
var band = Pattern(t, copies, mid, region.Width, token);
|
||||
if (band != null)
|
||||
Keep(band);
|
||||
if (band != null && band.Copies >= copies)
|
||||
hi = band.Length;
|
||||
else
|
||||
lo = mid;
|
||||
}
|
||||
full = found.Where(b => b.Copies >= copies).OrderBy(b => b.Length).First();
|
||||
return found.Where(b => b.Copies < copies && b.Length < full.Length - 1e-6).OrderBy(b => -b.Copies)
|
||||
.Take(MaxNarrower).Prepend(full).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="Bands"/> for each type at once. Each type's search depends only on its own
|
||||
/// patterns (fixed step counts, no shared budget), so the result is the same in any order.
|
||||
/// </summary>
|
||||
private List<Band>[] BandsInParallel(int[] typeIndexes, IReadOnlyList<int> remaining, Box region, CancellationToken token)
|
||||
{
|
||||
var result = new List<Band>[typeIndexes.Length];
|
||||
System.Threading.Tasks.Parallel.For(0, typeIndexes.Length,
|
||||
new System.Threading.Tasks.ParallelOptions { CancellationToken = token },
|
||||
i => result[i] = Bands(typeIndexes[i], remaining[typeIndexes[i]], region, token));
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Most copies a narrower band may leave to the gap fill.</summary>
|
||||
private static int HeldBack(int copies) => System.Math.Max(MaxHeldBack, copies / 3);
|
||||
|
||||
private const int MaxSteps = 6;
|
||||
|
||||
/// <summary>Narrower bands offered per type, those holding the most copies first.</summary>
|
||||
private const int MaxNarrower = 2;
|
||||
private const int Probes = 3;
|
||||
private const double StepShort = 0.01;
|
||||
|
||||
/// <summary>The type's Lattice pattern in a length x width box, up to the copies wanted.</summary>
|
||||
private Band? Pattern(int t, int copies, double length, double width, CancellationToken token)
|
||||
{
|
||||
var members = blocks.Band(types[t], copies, new Box(0, 0, length, width), token);
|
||||
// Bounds carry the arc flattening padding; a pattern they push past the box is no band.
|
||||
if (members.Count == 0 || members.Max(p => p.Top) - members.Min(p => p.Bottom) > width + 1e-9)
|
||||
return null;
|
||||
return new Band(t, members.Count, members.Max(p => p.Right) - members.Min(p => p.Left), members);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a band member at its pose enters a clamp keep-out (its clearance included); such
|
||||
/// members are left to the gap fill, which packs around the clamps.
|
||||
/// </summary>
|
||||
private bool OnClamp(Placed member)
|
||||
{
|
||||
if (clamps == null)
|
||||
return false;
|
||||
var point = new PointD(member.X, member.Y);
|
||||
for (var i = 0; i < clamps.Count; i++)
|
||||
{
|
||||
var nfp = clamps.Get(i, member.Orientation);
|
||||
var b = nfp.Bounds;
|
||||
if (point.x < b.left || point.x > b.right || point.y < b.top || point.y > b.bottom)
|
||||
continue;
|
||||
foreach (var path in nfp.Region)
|
||||
if (Clipper.IsPositive(path) && Clipper.PointInPolygon(point, path) != PointInPolygonResult.IsOutside)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ internal sealed class BlockCatalog : IDisposable
|
||||
private readonly Dictionary<int, int> attempts = new();
|
||||
internal int PreparationCount => attempts.Values.Sum();
|
||||
private readonly Dictionary<(int Type, int Quantity, double Length, double Width), IReadOnlyList<Placed>> cache = new();
|
||||
private readonly Dictionary<(int Type, int Quantity, double Length, double Width), IReadOnlyList<Placed>> bands = new();
|
||||
|
||||
/// <param name="drawingFor">Shared private drawings whose best-fit entries the caller owns;
|
||||
/// null makes the catalog own one per type and release it on dispose.</param>
|
||||
@@ -82,7 +83,31 @@ internal sealed class BlockCatalog : IDisposable
|
||||
return result;
|
||||
}
|
||||
|
||||
private IReadOnlyList<Placed> Build(PartType type, int quantity, Box rectangle, CancellationToken token)
|
||||
/// <summary>
|
||||
/// The type's Lattice pattern in a box of the given size, up to <paramref name="quantity"/>
|
||||
/// copies, for a band; unlike <see cref="Get"/> it is not limited in attempts per type. The
|
||||
/// pattern is filled one grid unit wider than the spacing: Fill sets parts exactly the spacing
|
||||
/// apart, which the stricter certification below can reject for curved parts (a stack of
|
||||
/// circles), and losing the band then loses its densest pattern.
|
||||
/// </summary>
|
||||
public IReadOnlyList<Placed> Band(PartType type, int quantity, Box rectangle, CancellationToken token)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (quantity <= 2 || type.Orientations.Count == 0 || rectangle.Length <= 0 || rectangle.Width <= 0)
|
||||
return Array.Empty<Placed>();
|
||||
var key = (type.Index, quantity, rectangle.Length, rectangle.Width);
|
||||
lock (bands)
|
||||
if (bands.TryGetValue(key, out var cached))
|
||||
return cached;
|
||||
// Types may build bands in parallel: each type's drawing and orientation list are its own.
|
||||
var result = Build(type, quantity, rectangle, token, spacing + System.Math.Pow(10, -NoFitCache.Precision));
|
||||
lock (bands)
|
||||
bands[key] = result;
|
||||
return result;
|
||||
}
|
||||
|
||||
private IReadOnlyList<Placed> Build(PartType type, int quantity, Box rectangle, CancellationToken token,
|
||||
double? fillSpacing = null)
|
||||
{
|
||||
// PrivatePlateFill.Run below is a full independent NFP-based pack whose own operations
|
||||
// never touch this solve's effort meter; charge it here using the same factors - demand
|
||||
@@ -92,7 +117,7 @@ internal sealed class BlockCatalog : IDisposable
|
||||
var drawing = drawingFor?.Invoke(type.Part) ?? OwnDrawing(type);
|
||||
try
|
||||
{
|
||||
var members = PrivatePlateFill.Run(drawing, type.Part.Rotation, spacing,
|
||||
var members = PrivatePlateFill.Run(drawing, type.Part.Rotation, fillSpacing ?? spacing,
|
||||
rectangle.Length, rectangle.Width, quantity, token);
|
||||
token.ThrowIfCancellationRequested();
|
||||
return Resolve(type, members.Take(quantity).ToArray(), orientations[type.Index], spacing, token);
|
||||
@@ -106,9 +131,12 @@ internal sealed class BlockCatalog : IDisposable
|
||||
|
||||
private Drawing OwnDrawing(PartType type)
|
||||
{
|
||||
if (!drawings.TryGetValue(type.Index, out var drawing))
|
||||
drawings[type.Index] = drawing = DrawingJobMapper.CreateDrawing(type.Part);
|
||||
return drawing;
|
||||
lock (drawings)
|
||||
{
|
||||
if (!drawings.TryGetValue(type.Index, out var drawing))
|
||||
drawings[type.Index] = drawing = DrawingJobMapper.CreateDrawing(type.Part);
|
||||
return drawing;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
|
||||
@@ -85,6 +85,7 @@ internal sealed class FrontierPacker
|
||||
/// fitted to <paramref name="nfps"/>.</param>
|
||||
/// <param name="groupRanks">Per type, a rank served after priority: a type is placed only when
|
||||
/// no type of the same priority and lower rank can be, so each type packs as one group.</param>
|
||||
/// <param name="within">Part of a rectangular stock's work area to fill instead of all of it.</param>
|
||||
/// <param name="reach">Farthest the packing front may go: the work area ends there along the
|
||||
/// front axis, so the fill must fit a shorter strip of the sheet.</param>
|
||||
public FrontierPacker(
|
||||
@@ -100,7 +101,8 @@ internal sealed class FrontierPacker
|
||||
PackBoundary? boundary = null,
|
||||
IReadOnlyList<double>? typeWeights = null,
|
||||
IReadOnlyList<int>? groupRanks = null,
|
||||
double? reach = null
|
||||
double? reach = null,
|
||||
Box? within = null
|
||||
)
|
||||
{
|
||||
if (boundary != null && !ReferenceEquals(boundary.Nfps, nfps))
|
||||
@@ -122,7 +124,9 @@ internal sealed class FrontierPacker
|
||||
work = axis == PackAxis.X
|
||||
? new Box(work.Left, work.Bottom, System.Math.Clamp(end - work.Left, 0, work.Length), work.Width)
|
||||
: new Box(work.Left, work.Bottom, work.Length, System.Math.Clamp(end - work.Bottom, 0, work.Width));
|
||||
limited = reach != null;
|
||||
if (within != null)
|
||||
work = within;
|
||||
limited = reach != null || within != null;
|
||||
}
|
||||
|
||||
private readonly bool limited;
|
||||
@@ -133,7 +137,10 @@ internal sealed class FrontierPacker
|
||||
|
||||
/// <param name="seated">Parts already on the sheet: they block space and hold the packing
|
||||
/// front where they reached, so the fill starts as gap fill. They are not returned.</param>
|
||||
public SheetFill Fill(IReadOnlyList<int> remaining, CancellationToken token, IReadOnlyList<Placed>? seated = null)
|
||||
/// <param name="front">Packing front to start from instead of the work area's leading edge: at
|
||||
/// the far edge, every placement is a gap fill, the largest part that fits at its lowest point.</param>
|
||||
public SheetFill Fill(IReadOnlyList<int> remaining, CancellationToken token, IReadOnlyList<Placed>? seated = null,
|
||||
double? front = null)
|
||||
{
|
||||
var left = remaining.ToArray();
|
||||
var states = new List<Region>();
|
||||
@@ -198,11 +205,11 @@ internal sealed class FrontierPacker
|
||||
i => snapshot[i].Subtract(nfps.Get(part.Orientation, snapshot[i].Orientation), part.X, part.Y)
|
||||
);
|
||||
}
|
||||
var front = axis == PackAxis.X ? work.Left : work.Bottom;
|
||||
var frontAt = System.Math.Max(axis == PackAxis.X ? work.Left : work.Bottom, front ?? double.NegativeInfinity);
|
||||
foreach (var part in seated ?? Array.Empty<Placed>())
|
||||
{
|
||||
placed.Add(part);
|
||||
front = System.Math.Max(front, axis == PackAxis.X ? part.Right : part.Top);
|
||||
frontAt = System.Math.Max(frontAt, axis == PackAxis.X ? part.Right : part.Top);
|
||||
Block(part);
|
||||
}
|
||||
var firstNew = placed.Count;
|
||||
@@ -246,7 +253,7 @@ internal sealed class FrontierPacker
|
||||
while (states.Count > 0)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var choice = Choose(states, offered, blockStates, front);
|
||||
var choice = Choose(states, offered, blockStates, frontAt);
|
||||
if (choice == null)
|
||||
break;
|
||||
|
||||
@@ -255,7 +262,7 @@ internal sealed class FrontierPacker
|
||||
{
|
||||
placed.Add(part);
|
||||
partArea += types[typeIndex].Area;
|
||||
front = System.Math.Max(front, axis == PackAxis.X ? part.Right : part.Top);
|
||||
frontAt = System.Math.Max(frontAt, axis == PackAxis.X ? part.Right : part.Top);
|
||||
}
|
||||
|
||||
left[typeIndex] -= choice.Count;
|
||||
|
||||
@@ -56,6 +56,12 @@ public sealed class IrregularNestingEngine : INestingEngine
|
||||
/// <summary>Whether the grouped variants run; off only in tests of the ungrouped search.</summary>
|
||||
internal bool GroupLikeParts { get; init; } = true;
|
||||
|
||||
/// <summary>Whether the banded variant runs; off only in tests of the search before it.</summary>
|
||||
internal bool BandLikeParts { get; init; } = true;
|
||||
|
||||
/// <summary>Work budgets after which the banded variant does not start.</summary>
|
||||
internal const int BandedWorkLimit = 3;
|
||||
|
||||
/// <summary>Whether the sheet-reduction pass runs; off only in tests of the search before it.</summary>
|
||||
internal bool ReduceSheets { get; init; } = true;
|
||||
|
||||
@@ -151,6 +157,23 @@ public sealed class IrregularNestingEngine : INestingEngine
|
||||
if (!ReferenceEquals(improved, plan))
|
||||
ReportPlan(job, types, improved, progress, token);
|
||||
}
|
||||
// Then full-height strips: each like-part group as a band of its Lattice pattern, or strip by
|
||||
// strip with the largest part first and the rest in its gaps; per sheet the better wins.
|
||||
// Strips ignore priority, so only jobs of one priority band; it starts while the work
|
||||
// spent stays under the ungrouped and grouped budgets together.
|
||||
if (BandLikeParts && groups && job.Parts.Select(p => p.Priority).Distinct().Count() == 1
|
||||
&& solver.Work.Value < BandedWorkLimit * WorkBudget)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var plan = solver.Plan(demand, PackAxis.X, 1.0, banded: true);
|
||||
if (plan.IsBetterThan(improved))
|
||||
{
|
||||
ReportPlan(job, types, plan, progress, token);
|
||||
improved = solver.ImproveTail(plan, solver.Work.Value + WorkBudget * 2);
|
||||
if (!ReferenceEquals(improved, plan))
|
||||
ReportPlan(job, types, improved, progress, token);
|
||||
}
|
||||
}
|
||||
// Then try to drop a sheet: split the parts over one sheet fewer and pack each sheet edge
|
||||
// first, the key part turned by its contacts. Replaces the result only by beating it.
|
||||
if (ReduceSheets)
|
||||
@@ -319,11 +342,12 @@ public sealed class IrregularNestingEngine : INestingEngine
|
||||
return cost != 0 ? cost : Compare(Offcut(job.Options, b), Offcut(job.Options, a));
|
||||
}
|
||||
|
||||
public Plan Plan(int[] demand, PackAxis axis, double beta, IReadOnlyList<double>? weights = null, bool grouped = false)
|
||||
public Plan Plan(int[] demand, PackAxis axis, double beta, IReadOnlyList<double>? weights = null, bool grouped = false,
|
||||
bool banded = false)
|
||||
{
|
||||
groupedBudget = Work.Value + workBudget;
|
||||
var run = Decode(demand, axis, beta, new Dictionary<string, int>(StringComparer.Ordinal), job.Options.MaxPlates, null,
|
||||
weights, grouped);
|
||||
weights, grouped, banded);
|
||||
var unplaced = types.Sum(t => t.Part.Quantity) - run.Sheets.Sum(s => s.Parts.Count);
|
||||
var reason = run.Reason;
|
||||
if (unplaced > 0 && reason == NestJobStopReason.Completed)
|
||||
@@ -379,6 +403,30 @@ public sealed class IrregularNestingEngine : INestingEngine
|
||||
return plan;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One banded sheet: like parts as full-height bands side by side, or strip by strip with
|
||||
/// the largest part's band or column and the others in its gaps; the better sheet wins, a
|
||||
/// tie keeping the bands. Falls back to the ordinary fill when nothing bands.
|
||||
/// </summary>
|
||||
private SheetFill Banded(NestPlateStock stock, int[] remaining, IReadOnlyList<double>? weights,
|
||||
Func<IReadOnlyList<int>?, double?, FrontierPacker> packer)
|
||||
{
|
||||
// Bands shape where a sheet ends; a sheet that cannot take all the remaining parts
|
||||
// fills to its end anyway, so it keeps the ordinary fill.
|
||||
var work = stock.WorkArea;
|
||||
if (types.Sum(t => remaining[t.Index] * t.Area) > work.Length * work.Width)
|
||||
return packer(null, null).Fill(remaining, token);
|
||||
var bands = new BandedFill(types, BlocksFor(stock), stock, ClampsFor(stock), () => packer(null, null),
|
||||
CompareSheets, Work, groupedBudget).Fill(remaining, token);
|
||||
var strips = new BandedFill(types, BlocksFor(stock), stock, ClampsFor(stock), () => packer(null, null),
|
||||
CompareSheets, Work, Work.Value + workBudget).FillStrips(remaining, box => new FrontierPacker(types,
|
||||
CacheFor(stock), PairsFor(stock), stock, PackAxis.Y, 1.0, Work, null, ClampsFor(stock), null, weights,
|
||||
null, null, box), token);
|
||||
if (bands == null)
|
||||
return strips ?? packer(null, null).Fill(remaining, token);
|
||||
return strips != null && CompareSheets(strips, bands) < 0 ? strips : bands;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Drops sheets while it can: the parts of a complete plan on one stock are split over
|
||||
/// one sheet fewer (by area, largest first onto the lightest sheet, then dealt in a snake)
|
||||
@@ -531,7 +579,8 @@ public sealed class IrregularNestingEngine : INestingEngine
|
||||
int? sheetCap,
|
||||
NestPlateStock? first,
|
||||
IReadOnlyList<double>? weights = null,
|
||||
bool grouped = false
|
||||
bool grouped = false,
|
||||
bool banded = false
|
||||
)
|
||||
{
|
||||
var remaining = (int[])demand.Clone();
|
||||
@@ -564,11 +613,14 @@ public sealed class IrregularNestingEngine : INestingEngine
|
||||
continue;
|
||||
progress?.Report(new NestJobProgress(NestJobStage.EvaluatingCandidate, stock.Id, sheets.Count, 0, 0));
|
||||
// Grouped fills pack groups from singles and pairs: Fill blocks cost far more per
|
||||
// fill there and gave no denser groups.
|
||||
// fill there and gave no denser groups. A banded fill's bands are Fill patterns
|
||||
// already; its gap fill takes singles and pairs.
|
||||
FrontierPacker Packer(IReadOnlyList<int>? ranks, double? reach) => new(types, CacheFor(stock),
|
||||
PairsFor(stock), stock, axis, beta, Work, grouped ? null : BlocksFor(stock), ClampsFor(stock), BoundaryFor(stock),
|
||||
PairsFor(stock), stock, axis, beta, Work, grouped || banded ? null : BlocksFor(stock), ClampsFor(stock), BoundaryFor(stock),
|
||||
weights, ranks, reach);
|
||||
var fill = grouped && GroupedFill.Applies(types, remaining)
|
||||
var fill = banded
|
||||
? Banded(stock, remaining, weights, Packer)
|
||||
: grouped && GroupedFill.Applies(types, remaining)
|
||||
? new GroupedFill(types, Packer, axis, stock.Outline == null, CompareSheets, Work, groupedBudget)
|
||||
.Fill(remaining, token)
|
||||
: Packer(null, null).Fill(remaining, token);
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
using OpenNest.Benchmark;
|
||||
using OpenNest.Engine.Jobs;
|
||||
using OpenNest.Engine.Jobs.Adapters;
|
||||
using OpenNest.Engine.NestingEngines.Irregular;
|
||||
using OpenNest.Tests.CuttingPlanning;
|
||||
|
||||
namespace OpenNest.Tests.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// Seven unlike sample parts (130 copies: base plates, L brackets, gussets, flanges, links, clamp
|
||||
/// jaws, hex covers) on a 60 x 120 sheet. Before banding, Irregular ended the layout at 107.7":
|
||||
/// each group packed as ragged columns, the links scattered into the gaps between them. Banded,
|
||||
/// each group stands in its own full-height column and the layout ends at 102.9".
|
||||
/// </summary>
|
||||
public class BandedNestingTests
|
||||
{
|
||||
[Fact]
|
||||
public void MixedSamplePartsNestInTidyBands()
|
||||
{
|
||||
var manifest = Path.Combine(PlanningCharacterizationTests.RepositoryRoot(), "test-data", "readme-parts",
|
||||
"readme-mixed.manifest.json");
|
||||
var job = DxfManifestLoader.Load(manifest).BuildNestJob(1);
|
||||
|
||||
var result = new IrregularNestingEngine().Solve(job);
|
||||
|
||||
Assert.Empty(NestLayoutCheck.Violations(job, result));
|
||||
var plate = Assert.Single(NestResultMaterializer.Materialize(job, result).Nest.Plates);
|
||||
Assert.Equal(130, plate.Parts.Count);
|
||||
var right = plate.Parts.Max(p => p.BoundingBox.Right);
|
||||
Assert.True(right < 104.5, $"Layout ends at {right:F3}");
|
||||
}
|
||||
}
|
||||
+42
-1
@@ -14,7 +14,7 @@ in `OpenNest.Engine/NestingEngines/<Name>/`, its tests in `OpenNest.Engine.Tests
|
||||
| Default | Any job; used when no engine is named | Runs Irregular, Rectangles and Circles, checks each layout with the layout check and keeps the best: valid first, then fewest unplaced parts, then lowest salvage-credited cost, then the largest compactness offcut; remaining ties keep the engine listed first here |
|
||||
| Rectangles | Plain and near-rectangular plates | Each part packed as the box of its material at its minimum-area rotation, using a maximal-rectangles free list; the sheet that finishes the job is also squeezed into a shorter or narrower bin; stock chosen sheet by sheet by salvage-credited look-ahead cost |
|
||||
| Circles | Round parts: blanks, washers, flanges, gears by their tip circle | Each part packed as its minimum enclosing circle at centers tangent to two of walls, placed discs and clamp keep-outs, with hexagonal and square lattice seeds; bids only when every part is round; stock chosen as Rectangles does, plus whole-job runs preferring each stock and a tail re-plan |
|
||||
| Irregular | Irregular profiles | No-fit-polygon frontier packing with gap filling and best-fit pairs, six whole-job strategy variants and a tail re-plan, then grouped variants that pack like parts together, then a sheet-reduction pass that packs edge parts first and turns a key part by its contacts; under a time limit it keeps trying seeded variants until the limit |
|
||||
| Irregular | Irregular profiles | No-fit-polygon frontier packing with gap filling and best-fit pairs, six whole-job strategy variants and a tail re-plan, then grouped variants that pack like parts together, then a banded variant that packs each sheet in full-height strips, each group as its Lattice band or each strip from the largest parts down, then a sheet-reduction pass that packs edge parts first and turns a key part by its contacts; under a time limit it keeps trying seeded variants until the limit |
|
||||
| FlatBar | Flat bar: parts about as wide as the bar | Each stock read as a bar and cut in one row: the CutList cut-list packer and a best-fill search on part lengths less their self-nesting gain, then a slide-left pass that nests shaped ends and refills freed length; stock chosen bar by bar by whole-plan cost |
|
||||
| Lattice, Strip, Vertical Remnant, Horizontal Remnant | Many copies of a few parts | The fixed placement strategies behind interactive fill; Lattice is the multi-phase lattice fill (linear, pairs, rectangle best-fit, remainder; the pairs phase fills the strip its grid leaves with rows of pairs when they hold more than single parts, and also tiles herringbone pairs: the part turned so a hull edge lies along a sheet axis, nested into its own row, with every other row reversed), and the remnant strategies run it ranked to keep the largest drop. In whole jobs, all four place a plate with any fixed or bounded part rotation by the rotation-aware ordered placer instead |
|
||||
|
||||
@@ -275,6 +275,47 @@ re-plan. The search until cancelled takes grouped decodes in turn with the varia
|
||||
same seeded weights. On the help tutorial's parts (30 gussets, 20 ells, 10 plates, 12 flanges on
|
||||
60 x 120 at 0.3 spacing) the layout ends at 34.9 rather than 38.1.
|
||||
|
||||
### Banded variant
|
||||
|
||||
Last of the search variants, Irregular decodes the job once more in full-height strips along X
|
||||
(`BandedFill`), when the grouped variants apply and every part has the same priority. A sheet
|
||||
that cannot take all the remaining part area keeps the ordinary fill: it fills to its end anyway,
|
||||
and strips only shape where a sheet ends. Every other sheet is packed two ways and the better
|
||||
sheet kept (a tie keeps the bands). A person nesting many copies of a few parts lays them out in
|
||||
tidy columns; packing one part at a time instead leaves each group's last column ragged and
|
||||
scatters the smallest parts into the gaps between groups.
|
||||
|
||||
- Bands: each type of three or more copies as its Lattice pattern (the pattern interactive Fill
|
||||
gives that part alone: circles stacked or staggered, hexagons tiled, L brackets interlocked in
|
||||
pairs) in the narrowest strip of full work-area height that holds all its copies. Bands stand
|
||||
side by side a part spacing apart, longest first or shortest first, whichever packs better;
|
||||
then the copies held back from them and the types with one or two copies fill the gaps under
|
||||
the usual rule. On the better order each type's narrower bands holding fewer copies (at most
|
||||
four, or a third, fewer; at most two per type) are tried in turn, kept when they improve the
|
||||
sheet.
|
||||
- Strips: each strip holds the largest remaining part, as its band (full or narrower) or as a
|
||||
column one to three copies wide, and every other part fills the strip's gaps, the largest piece
|
||||
at its leftmost, lowest point first, looking back one part length behind the strip. A beam of
|
||||
the four partial sheets densest so far (part area per length used) is carried strip to strip,
|
||||
so a strip is judged by what it leaves for the rest of the sheet, not by its own density; the
|
||||
best finished sheet wins.
|
||||
- Patterns grow in whole rows or columns, so each type's band is found by asking for the pattern
|
||||
just short of the last one's length, at most six times, then halving three times toward the
|
||||
area bound; types search in parallel, each on its own patterns, so the result does not depend
|
||||
on the order. Patterns are filled one Clipper grid unit (0.0001) wider than the part spacing and
|
||||
certified at the spacing: Fill sets parts exactly the spacing apart, which the strict
|
||||
certification can reject for curved parts, and a stack of rings would lose its densest pattern.
|
||||
- A band member inside a clamp keep-out goes to the gap fill instead; a band shorter than the
|
||||
sheet moves flush to the far edge when that keeps more of it off the clamps. Outlined sheets do
|
||||
not band.
|
||||
|
||||
Neither way wins every sheet. On the README sample parts (18 L brackets, 14 base plates, 18 clamp
|
||||
jaws, 12 flanges, 24 gussets, 14 hex covers, 30 links on 60 x 120) bands end the layout at 102.9
|
||||
(104.6 with the desktop's edge spacing and a bottom clamp rail) rather than 107.7 (108.6); with
|
||||
about twice those quantities over two sheets, strips end the second sheet at 104.7 rather than 106.2. It
|
||||
starts while the work spent stays under three work budgets and replaces the result only by
|
||||
beating it, with its own tail re-plan.
|
||||
|
||||
### Sheet reduction
|
||||
|
||||
Last, Irregular tries to drop a sheet from a complete plan of at most 40 parts on one rectangular
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,151 @@
|
||||
"""Generate sample DXF parts (inches) for the README Auto Nest screenshot.
|
||||
|
||||
Run: python test-data/readme-parts/generate.py
|
||||
Writes one DXF per part next to this script. Outlines and holes are written
|
||||
as plain LINE/ARC/CIRCLE entities so every importer reads them the same way.
|
||||
"""
|
||||
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
import ezdxf
|
||||
|
||||
OUT = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def new_doc():
|
||||
doc = ezdxf.new("R2010")
|
||||
doc.header["$INSUNITS"] = 1 # inches
|
||||
doc.header["$MEASUREMENT"] = 0
|
||||
return doc
|
||||
|
||||
|
||||
def add_loop(msp, points):
|
||||
"""Closed loop from (x, y, bulge) vertices, exploded to LINE/ARC."""
|
||||
poly = msp.add_lwpolyline(points, format="xyb", close=True)
|
||||
for e in list(poly.virtual_entities()):
|
||||
if e.dxftype() == "LINE":
|
||||
msp.add_line(e.dxf.start, e.dxf.end)
|
||||
else:
|
||||
msp.add_arc(e.dxf.center, e.dxf.radius, e.dxf.start_angle, e.dxf.end_angle)
|
||||
msp.delete_entity(poly)
|
||||
|
||||
|
||||
def bulge(angle_deg):
|
||||
return math.tan(math.radians(angle_deg) / 4)
|
||||
|
||||
|
||||
def rounded_rect(x0, y0, w, h, r):
|
||||
b = bulge(90)
|
||||
return [
|
||||
(x0 + r, y0, 0), (x0 + w - r, y0, b),
|
||||
(x0 + w, y0 + r, 0), (x0 + w, y0 + h - r, b),
|
||||
(x0 + w - r, y0 + h, 0), (x0 + r, y0 + h, b),
|
||||
(x0, y0 + h - r, 0), (x0, y0 + r, b),
|
||||
]
|
||||
|
||||
|
||||
def slot(msp, cx, cy, length, width, vertical=False):
|
||||
r = width / 2
|
||||
half = length / 2 - r
|
||||
b = bulge(180)
|
||||
if vertical:
|
||||
pts = [(cx + r, cy - half, 0), (cx + r, cy + half, b),
|
||||
(cx - r, cy + half, 0), (cx - r, cy - half, b)]
|
||||
else:
|
||||
pts = [(cx - half, cy - r, 0), (cx + half, cy - r, b),
|
||||
(cx + half, cy + r, 0), (cx - half, cy + r, b)]
|
||||
add_loop(msp, pts)
|
||||
|
||||
|
||||
def save(doc, name):
|
||||
doc.saveas(OUT / f"{name}.dxf")
|
||||
print(f"wrote {name}.dxf")
|
||||
|
||||
|
||||
def base_plate():
|
||||
doc = new_doc(); msp = doc.modelspace()
|
||||
add_loop(msp, rounded_rect(0, 0, 10, 8, 0.75))
|
||||
for x, y in [(1, 1), (9, 1), (1, 7), (9, 7)]:
|
||||
msp.add_circle((x, y), 0.3125)
|
||||
slot(msp, 5, 4, 4, 1)
|
||||
save(doc, "Base Plate")
|
||||
|
||||
|
||||
def angle_bracket():
|
||||
doc = new_doc(); msp = doc.modelspace()
|
||||
r = 1.0 # inside fillet
|
||||
b = bulge(90)
|
||||
pts = [
|
||||
(0, 0, 0), (9, 0, 0), (9, 2.5, 0),
|
||||
(2.5 + r, 2.5, -b), (2.5, 2.5 + r, 0),
|
||||
(2.5, 9, 0), (0, 9, 0),
|
||||
]
|
||||
add_loop(msp, pts)
|
||||
for x in (5, 7.5):
|
||||
msp.add_circle((x, 1.25), 0.28125)
|
||||
for y in (5, 7.5):
|
||||
msp.add_circle((1.25, y), 0.28125)
|
||||
save(doc, "Angle Bracket")
|
||||
|
||||
|
||||
def gusset():
|
||||
doc = new_doc(); msp = doc.modelspace()
|
||||
pts = [(0, 0, 0), (8, 0, 0), (8, 1, 0), (1, 8, 0), (0, 8, 0)]
|
||||
add_loop(msp, pts)
|
||||
msp.add_circle((2.6, 2.6), 1.1)
|
||||
save(doc, "Gusset")
|
||||
|
||||
|
||||
def flange():
|
||||
doc = new_doc(); msp = doc.modelspace()
|
||||
msp.add_circle((0, 0), 4.0)
|
||||
msp.add_circle((0, 0), 2.0)
|
||||
for i in range(6):
|
||||
a = math.radians(i * 60 + 30)
|
||||
msp.add_circle((3.0 * math.cos(a), 3.0 * math.sin(a)), 0.25)
|
||||
save(doc, "Flange")
|
||||
|
||||
|
||||
def link():
|
||||
doc = new_doc(); msp = doc.modelspace()
|
||||
b = bulge(180)
|
||||
r = 1.0
|
||||
pts = [(0, -r, 0), (6, -r, b), (6, r, 0), (0, r, b)]
|
||||
add_loop(msp, pts)
|
||||
msp.add_circle((0, 0), 0.40625)
|
||||
msp.add_circle((6, 0), 0.40625)
|
||||
save(doc, "Link")
|
||||
|
||||
|
||||
def clamp_jaw():
|
||||
doc = new_doc(); msp = doc.modelspace()
|
||||
# 7 x 4.5 block with a semicircular notch on top and chamfered corners.
|
||||
b = bulge(180)
|
||||
pts = [
|
||||
(0.5, 0, 0), (6.5, 0, 0), (7, 0.5, 0), (7, 4.5, 0),
|
||||
(5, 4.5, -b), (2, 4.5, 0),
|
||||
(0, 4.5, 0), (0, 0.5, 0),
|
||||
]
|
||||
add_loop(msp, pts)
|
||||
msp.add_circle((1, 1.25), 0.25)
|
||||
msp.add_circle((6, 1.25), 0.25)
|
||||
save(doc, "Clamp Jaw")
|
||||
|
||||
|
||||
def hex_cover():
|
||||
doc = new_doc(); msp = doc.modelspace()
|
||||
r = 3.5
|
||||
pts = [(r * math.cos(math.radians(60 * i)), r * math.sin(math.radians(60 * i)), 0)
|
||||
for i in range(6)]
|
||||
add_loop(msp, pts)
|
||||
msp.add_circle((0, 0), 1.25)
|
||||
for i in range(6):
|
||||
a = math.radians(60 * i + 30)
|
||||
msp.add_circle((2.3 * math.cos(a), 2.3 * math.sin(a)), 0.1875)
|
||||
save(doc, "Hex Cover")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
for make in (base_plate, angle_bracket, gusset, flange, link, clamp_jaw, hex_cover):
|
||||
make()
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"sheetSizes": ["60x120"],
|
||||
"spacing": 0.3,
|
||||
"edgeSpacing": 0.3,
|
||||
"quadrant": 1,
|
||||
"parts": [
|
||||
{ "dxf": "Angle Bracket.dxf", "quantity": 18 },
|
||||
{ "dxf": "Base Plate.dxf", "quantity": 14 },
|
||||
{ "dxf": "Clamp Jaw.dxf", "quantity": 18 },
|
||||
{ "dxf": "Flange.dxf", "quantity": 12 },
|
||||
{ "dxf": "Gusset.dxf", "quantity": 24 },
|
||||
{ "dxf": "Hex Cover.dxf", "quantity": 14 },
|
||||
{ "dxf": "Link.dxf", "quantity": 30 }
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user