using OpenNest.Geometry;
using OpenNest.Math;
namespace OpenNest.Labels
{
///
/// Where a part's number label would be etched: a rectangle on the flat face, in the drawing's
/// source frame. Only the placement is stored. It is an annotation, like a dimension: it never
/// affects the program, nesting geometry or posts.
///
public sealed class LabelBox
{
public LabelBox()
{
}
public LabelBox(Vector center, double width, double height, double rotation)
{
Center = center;
Width = width;
Height = height;
Rotation = rotation;
}
public Vector Center { get; set; }
/// The side along the text, before .
public double Width { get; set; }
/// The side across the text, before .
public double Height { get; set; }
/// Counterclockwise turn about , in radians.
public double Rotation { get; set; }
/// True when the center, both sides and the rotation are finite and both sides are positive.
public bool IsValid =>
double.IsFinite(Center.X) && double.IsFinite(Center.Y)
&& double.IsFinite(Width) && Width > 0
&& double.IsFinite(Height) && Height > 0
&& double.IsFinite(Rotation);
public LabelBox Clone() => new(Center, Width, Height, Rotation);
/// The corners counterclockwise from the text's lower left.
public Vector[] Corners()
{
var cos = PortableMath.Cos(Rotation);
var sin = PortableMath.Sin(Rotation);
var hw = Width / 2;
var hh = Height / 2;
Vector Corner(double x, double y) => new(Center.X + x * cos - y * sin, Center.Y + x * sin + y * cos);
return new[] { Corner(-hw, -hh), Corner(hw, -hh), Corner(hw, hh), Corner(-hw, hh) };
}
/// A point in the box's own frame (x along the text, y across it), origin at the center.
public Vector ToLocal(Vector point)
{
var cos = PortableMath.Cos(Rotation);
var sin = PortableMath.Sin(Rotation);
var dx = point.X - Center.X;
var dy = point.Y - Center.Y;
return new Vector(dx * cos + dy * sin, -dx * sin + dy * cos);
}
/// The point at in the box's own frame.
public Vector ToWorld(Vector local)
{
var cos = PortableMath.Cos(Rotation);
var sin = PortableMath.Sin(Rotation);
return new Vector(
Center.X + local.X * cos - local.Y * sin,
Center.Y + local.X * sin + local.Y * cos);
}
public bool Contains(Vector point)
{
var local = ToLocal(point);
return System.Math.Abs(local.X) <= Width / 2 && System.Math.Abs(local.Y) <= Height / 2;
}
}
}