using System;
using System.Collections.Generic;
using OpenNest.Engine;
using OpenNest.Engine.Fill;
using OpenNest.Math;
namespace OpenNest.Engine.Jobs.Placement.Fillers;
///
/// Filler-only settings that distinguish Fill from the remnant fills: how candidates are ranked,
/// the preferred direction, the axis surplus parts are trimmed from, and how angles are chosen.
/// Strategies see only the the filler builds from it.
///
internal sealed class PlateFillPolicy
{
private readonly Func comparerFactory;
private readonly Func angleExtent;
private PlateFillPolicy(
Func comparerFactory,
NestDirection? preferredDirection,
ShrinkAxis trimAxis,
Func angleExtent
)
{
this.comparerFactory = comparerFactory;
PreferredDirection = preferredDirection;
TrimAxis = trimAxis;
this.angleExtent = angleExtent;
}
/// Plain fill: default ranking and the filler's learned angle candidates.
internal static PlateFillPolicy Fill { get; } = new(
() => new DefaultFillComparer(),
null,
ShrinkAxis.Width,
null
);
/// Vertical remnant: minimize X-extent, prefer horizontal placement.
internal static PlateFillPolicy VerticalRemnant { get; } = new(
() => new VerticalRemnantComparer(),
NestDirection.Horizontal,
ShrinkAxis.Width,
RotatedWidth
);
/// Horizontal remnant: minimize Y-extent, prefer vertical placement.
internal static PlateFillPolicy HorizontalRemnant { get; } = new(
() => new HorizontalRemnantComparer(),
NestDirection.Vertical,
ShrinkAxis.Length,
RotatedHeight
);
internal NestDirection? PreferredDirection { get; }
internal ShrinkAxis TrimAxis { get; }
///
/// True when the filler's chooses the angles; false when
/// replaces it entirely.
///
internal bool UsesAngleBuilder => angleExtent == null;
internal IFillComparer CreateComparer() => comparerFactory();
///
/// The remnant angles: the primary angle and its quarter turn, narrowest extent first. No
/// circle case, sweep or learned angles, and the item's rotation range is ignored.
///
internal List BuildFixedAngles(NestItem item, ClassificationResult classification)
{
var baseAngles = new List
{
classification.PrimaryAngle,
classification.PrimaryAngle + Angle.HalfPI,
};
baseAngles.Sort((left, right) => angleExtent(item, left).CompareTo(angleExtent(item, right)));
return baseAngles;
}
private static double RotatedWidth(NestItem item, double angle)
{
var boundingBox = item.Drawing.Program.BoundingBox();
var cos = System.Math.Abs(PortableMath.Cos(angle));
var sin = System.Math.Abs(PortableMath.Sin(angle));
return boundingBox.Length * cos + boundingBox.Width * sin;
}
private static double RotatedHeight(NestItem item, double angle)
{
var boundingBox = item.Drawing.Program.BoundingBox();
var cos = System.Math.Abs(PortableMath.Cos(angle));
var sin = System.Math.Abs(PortableMath.Sin(angle));
return boundingBox.Width * cos + boundingBox.Length * sin;
}
}