using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using OpenNest.Geometry;
using OpenNest.Math;
namespace OpenNest.Engine.Fill
{
public static partial class Expander
{
///
/// Opens a tightly packed selection one axis at a time, for the layouts
/// the pair search cannot move: every pair there must reach one spacing,
/// so a single pinned direction (or a long stack it fails to ripple
/// through) leaves the other direction's room unused. Each axis takes the
/// widest gap its longest chain of parts fits, keeping their order.
/// Returns null when the selection has cut-offs or parts whose boxes
/// overlap, or when neither axis has room.
///
private static Result SweepAxes(
SeparationContext context,
List entry,
List selected,
Options opt,
CancellationToken token
)
{
if (selected.Any(p => p.BaseDrawing.IsCutOff))
return null;
var boxes = selected.Select(p => p.BoundingBox).ToArray();
for (var i = 0; i < boxes.Length; i++)
for (var j = i + 1; j < boxes.Length; j++)
if (AxisGap(boxes[i], boxes[j], horizontal: true) < -Tolerance.Epsilon
&& AxisGap(boxes[i], boxes[j], horizontal: false) < -Tolerance.Epsilon)
return null;
// As for a pattern, no selected gap closes below the tightest one.
var floor = double.MaxValue;
foreach (var pair in context.Pairs)
if (context.IsMover(pair.IndexB))
floor = System.Math.Min(floor, pair.EntryFloor);
if (!(floor > 0) || floor == double.MaxValue)
return null;
var positions = new List(entry);
var x = SweepAxis(context, entry, positions, boxes, horizontal: true, floor, opt, token);
var y = SweepAxis(context, entry, positions, boxes, horizontal: false, floor, opt, token);
if (token.IsCancellationRequested)
return new Result { Canceled = true };
if (x == null && y == null)
return null;
if (!context.MeetsEntryFloors(positions, entry, floor))
throw new InvalidOperationException("Axis sweep violates an entry clearance floor.");
double measured;
try
{
measured = MinimumPairClearance(context, positions, token);
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
return new Result { Canceled = true };
}
if (token.IsCancellationRequested)
return new Result { Canceled = true };
Apply(selected, entry, positions);
return new Result
{
AchievedSpacing = System.Math.Max(0, measured),
SpacingX = x,
SpacingY = y,
};
}
/// True when the tightest gap is still near the plate's own
/// spacings, as in a nest; parts placed far apart are not opened up.
private static bool IsPacked(Plate plate, double spacing)
{
var edge = plate.EdgeSpacing;
var widest = System.Math.Max(plate.PartSpacing, System.Math.Max(
System.Math.Max(edge.Left, edge.Right), System.Math.Max(edge.Bottom, edge.Top)));
return spacing <= 2 * widest;
}
/// The gap from the lower box to the higher one along an axis;
/// negative when their extents on that axis overlap.
private static double AxisGap(Box a, Box b, bool horizontal) => horizontal
? System.Math.Max(b.Left - a.Right, a.Left - b.Right)
: System.Math.Max(b.Bottom - a.Top, a.Bottom - b.Top);
///
/// Moves parts toward the high side of one axis to the widest spacing that
/// fits, updating . Returns that spacing, or
/// null when the axis cannot open (or the run was canceled).
///
private static double? SweepAxis(
SeparationContext context,
List entry,
List positions,
Box[] entryBoxes,
bool horizontal,
double floor,
Options opt,
CancellationToken token
)
{
var count = entryBoxes.Length;
var boxes = new Box[count];
for (var i = 0; i < count; i++)
boxes[i] = entryBoxes[i].Translate(positions[i] - entry[i]);
double LowOf(Box box) => horizontal ? box.Left : box.Bottom;
double HighOf(Box box) => horizontal ? box.Right : box.Top;
var order = Enumerable.Range(0, count).OrderBy(i => LowOf(boxes[i])).ToArray();
// The positions at a target spacing, each part pushed only as far as
// its edge strip and its lower neighbors need; null when they do not
// fit or break a floor.
(List Positions, bool Widens)? At(double spacing)
{
var limits = context.EdgeLimits(spacing);
var (lowLimit, highLimit) = horizontal
? (limits.Left, limits.Right)
: (limits.Bottom, limits.Top);
var move = new double[count];
var widens = false;
for (var n = 0; n < count; n++)
{
var j = order[n];
move[j] = System.Math.Max(0, lowLimit - LowOf(boxes[j]));
for (var m = 0; m < n; m++)
{
var i = order[m];
var gap = LowOf(boxes[j]) - HighOf(boxes[i]);
if (gap < -Tolerance.Epsilon)
continue; // side by side on this axis, not in a chain
var cross = System.Math.Max(0, AxisGap(boxes[i], boxes[j], !horizontal));
if (cross >= spacing)
continue;
// The lower part's own push carries over, less any gap
// to spare.
var need = System.Math.Sqrt(spacing * spacing - cross * cross) - gap;
widens |= need > Tolerance.Epsilon;
move[j] = System.Math.Max(move[j], move[i] + need);
}
if (move[j] > 0 && HighOf(boxes[j]) + move[j] > highLimit + 1e-9)
return null;
if (move[j] == 0 && HighOf(boxes[j]) > highLimit + 1e-9)
return null;
}
var trial = new List(positions);
for (var i = 0; i < count; i++)
{
if (move[i] <= 0)
continue;
var delta = horizontal ? new Vector(move[i], 0) : new Vector(0, move[i]);
trial[i] = positions[i] + delta;
if (context.HasWalls
&& context.ClipToMaterial(i, positions, delta / move[i], move[i], wallsOnly: true)
< move[i] - 1e-6)
return null;
}
return context.MeetsEntryFloors(trial, entry, floor) ? (trial, widens) : null;
}
var good = floor;
var bad = horizontal ? context.WorkArea.Length : context.WorkArea.Width;
List best = null;
while (bad - good > opt.Tolerance)
{
if (token.IsCancellationRequested)
return null;
var mid = (good + bad) / 2;
var probe = At(mid);
if (probe == null)
{
bad = mid;
continue;
}
good = mid;
// A probe that only pushes parts off an edge opens no gap.
best = probe.Value.Widens ? probe.Value.Positions : null;
}
if (best == null || good <= floor + opt.Tolerance)
return null;
for (var i = 0; i < count; i++)
positions[i] = best[i];
return good;
}
}
}