feat(shapes): add angle, channel and rolled plate to the Shape Library

Each makes the flat blank of a part bent or rolled along its length,
sized with the bend allowance at the K-factor. Angle and channel bends
are saved on the drawing as 90 degree up bends and etched as an
imported DXF's up bends are. The preview draws each part's section
beside the blank, dimensioned with the formed sizes; a long part's
section is enlarged so it stays readable. K-factor is a plain number,
not a length, in the form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-11-17 17:28:58 -05:00
1 parent d7f550dda4
commit 587613ff89
14 files changed
+800 -28

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
namespace OpenNest.Bending
{
public static class BendMath
{
/// <summary>
/// The length of the neutral axis through a bend: the arc at the inside radius plus
/// <paramref name="kFactor"/> of the thickness.
/// </summary>
/// <param name="angle">The bend angle in radians.</param>
public static double Allowance(double angle, double insideRadius, double thickness, double kFactor) =>
angle * (insideRadius + kFactor * thickness);
}
}
+73
View File
@@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using OpenNest.Geometry;
namespace OpenNest.Shapes
{
/// <summary>
/// The flat blank of a formed angle: two legs and one 90° bend, sized from the outside
/// dimensions with the bend allowance at <see cref="KFactor"/>.
/// </summary>
public class AngleShape : ShapeDefinition
{
public double OutsideWidth { get; set; }
public double OutsideHeight { get; set; }
public double Thickness { get; set; }
public double InsideRadius { get; set; }
[Unitless]
[DisplayName("K-Factor")]
public double KFactor { get; set; }
public double Length { get; set; }
public double InsideWidth => OutsideWidth - Thickness;
public double InsideHeight => OutsideHeight - Thickness;
public double BendAllowance => SheetMetal.BendAllowance(InsideRadius, Thickness, KFactor);
/// <summary>The developed width of the blank: both legs' flats plus the bend.</summary>
public double FlatLength => InsideHeight - InsideRadius + InsideWidth - InsideRadius + BendAllowance;
/// <summary>The bend line's distance from the edge of the shorter leg.</summary>
public double BendLineDim => System.Math.Min(InsideWidth, InsideHeight) - InsideRadius + BendAllowance / 2;
public override string GenerateName() =>
$"Angle {Dim(OutsideWidth)}x{Dim(OutsideHeight)}x{Dim(Thickness)} x {Dim(Length)}";
public override void SetPreviewDefaults()
{
OutsideWidth = 4;
OutsideHeight = 2;
Thickness = 0.125;
InsideRadius = 0.3125;
KFactor = 0.42;
Length = 12;
}
public override IReadOnlyList<ShapeDimension> GetDimensions() =>
new[]
{
ShapeDimension.Linear(nameof(Length), new Vector(0, 0), new Vector(Length, 0), ShapeDimension.Down),
};
public override ShapeSideView GetSideView() =>
SheetMetal.Section(false, OutsideWidth, OutsideHeight, Thickness, InsideRadius,
nameof(OutsideWidth), nameof(OutsideHeight), nameof(Thickness), nameof(InsideRadius));
public override Drawing GetDrawing()
{
SheetMetal.Validate(Thickness, Length, KFactor);
if (!(InsideHeight - InsideRadius > 0) || !(InsideWidth - InsideRadius > 0))
throw new InvalidOperationException("Each leg must be longer than the thickness plus the inside radius.");
// The shorter leg runs along the bottom edge, so the bend line sits BendLineDim up.
var entities = SheetMetal.Entities(Length, FlatLength, new[] { BendLineDim }, InsideRadius, out var bends);
var drawing = CreateDrawing(entities);
drawing.Bends.AddRange(bends);
return drawing;
}
}
}
+77
View File
@@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using OpenNest.Geometry;
namespace OpenNest.Shapes
{
/// <summary>
/// The flat blank of a formed channel: two equal sides, a bottom and two 90° bends, sized
/// from the outside dimensions with the bend allowance at <see cref="KFactor"/>.
/// </summary>
public class ChannelShape : ShapeDefinition
{
public double OutsideWidth { get; set; }
public double OutsideHeight { get; set; }
public double Thickness { get; set; }
public double InsideRadius { get; set; }
[Unitless]
[DisplayName("K-Factor")]
public double KFactor { get; set; }
public double Length { get; set; }
public double InsideWidth => OutsideWidth - Thickness * 2;
public double InsideHeight => OutsideHeight - Thickness;
public double BendAllowance => SheetMetal.BendAllowance(InsideRadius, Thickness, KFactor);
/// <summary>The developed width of the blank: both sides' and the bottom's flats plus the bends.</summary>
public double FlatLength =>
(InsideHeight - InsideRadius) * 2 + InsideWidth - InsideRadius * 2 + BendAllowance * 2;
/// <summary>Each bend line's distance from its side's edge.</summary>
public double BendLineDim => InsideHeight - InsideRadius + BendAllowance / 2;
public override string GenerateName() =>
$"Channel {Dim(OutsideWidth)}x{Dim(OutsideHeight)}x{Dim(Thickness)} x {Dim(Length)}";
public override void SetPreviewDefaults()
{
OutsideWidth = 4;
OutsideHeight = 2;
Thickness = 0.125;
InsideRadius = 0.3125;
KFactor = 0.42;
Length = 12;
}
public override IReadOnlyList<ShapeDimension> GetDimensions() =>
new[]
{
ShapeDimension.Linear(nameof(Length), new Vector(0, 0), new Vector(Length, 0), ShapeDimension.Down),
};
public override ShapeSideView GetSideView() =>
SheetMetal.Section(true, OutsideWidth, OutsideHeight, Thickness, InsideRadius,
nameof(OutsideWidth), nameof(OutsideHeight), nameof(Thickness), nameof(InsideRadius));
public override Drawing GetDrawing()
{
SheetMetal.Validate(Thickness, Length, KFactor);
if (!(InsideHeight - InsideRadius > 0))
throw new InvalidOperationException("The sides must be longer than the thickness plus the inside radius.");
if (InsideWidth - InsideRadius * 2 < 0)
throw new InvalidOperationException("The width must fit both sides' thickness and inside radius.");
var flat = FlatLength;
var bendLine = BendLineDim;
var entities = SheetMetal.Entities(Length, flat, new[] { bendLine, flat - bendLine }, InsideRadius, out var bends);
var drawing = CreateDrawing(entities);
drawing.Bends.AddRange(bends);
return drawing;
}
}
}
+72
View File
@@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using OpenNest.Geometry;
namespace OpenNest.Shapes
{
/// <summary>
/// The flat blank of a plate rolled into a cylinder: <see cref="Length"/> by the
/// circumference of the neutral axis, <see cref="KFactor"/> of the thickness out from the
/// inside diameter.
/// </summary>
public class RolledPlateShape : ShapeDefinition
{
public double InsideDiameter { get; set; }
public double Thickness { get; set; }
[Unitless]
[DisplayName("K-Factor")]
public double KFactor { get; set; }
public double Length { get; set; }
public double InsideRadius => InsideDiameter / 2;
public double OutsideDiameter => InsideDiameter + Thickness * 2;
/// <summary>The developed width of the blank: the neutral axis's circumference.</summary>
public double FlatLength => System.Math.PI * 2 * (InsideRadius + Thickness * KFactor);
public override string GenerateName() =>
$"Rolled Plate {Dim(InsideDiameter)} ID x {Dim(Thickness)} x {Dim(Length)}";
public override void SetPreviewDefaults()
{
InsideDiameter = 10;
Thickness = 0.1875;
KFactor = 0.42;
Length = 12;
}
public override IReadOnlyList<ShapeDimension> GetDimensions() =>
new[]
{
ShapeDimension.Linear(nameof(Length), new Vector(0, 0), new Vector(Length, 0), ShapeDimension.Down),
};
/// <summary>The rolled ring, with its inside diameter across the middle and a leader from its wall to the thickness.</summary>
public override ShapeSideView GetSideView()
{
var inside = InsideRadius;
var outside = InsideRadius + Thickness;
return new ShapeSideView(
new Entity[] { new Circle(0, 0, outside), new Circle(0, 0, inside) },
new[]
{
ShapeDimension.Inline(nameof(InsideDiameter), new Vector(-inside, 0), new Vector(inside, 0), "Ø"),
ShapeDimension.Leader(nameof(Thickness), new Vector(outside * System.Math.Sqrt(0.5), outside * System.Math.Sqrt(0.5)), new Vector(1, 1)),
});
}
public override Drawing GetDrawing()
{
SheetMetal.Validate(Thickness, Length, KFactor);
if (!(InsideDiameter > 0))
throw new InvalidOperationException("The inside diameter must be more than zero.");
var entities = SheetMetal.Entities(Length, FlatLength, Array.Empty<double>(), 0, out _);
return CreateDrawing(entities);
}
}
}
+6
View File
@@ -42,6 +42,12 @@ namespace OpenNest.Shapes
/// </summary>
public virtual IReadOnlyList<ShapeDimension> GetDimensions() => Array.Empty<ShapeDimension>();
/// <summary>
/// A sheet metal part's cross-section that the Shape Library draws beside the flat blank,
/// with the dimensions of parameters the blank cannot show; null for a flat shape.
/// </summary>
public virtual ShapeSideView GetSideView() => null;
public static List<T> LoadFromJson<T>(string path)
where T : ShapeDefinition
{
+24
View File
@@ -0,0 +1,24 @@
using System.Collections.Generic;
using OpenNest.Geometry;
namespace OpenNest.Shapes
{
/// <summary>
/// A sheet metal part's cross-section, which the Shape Library draws beside the flat blank with
/// its own dimensions. Annotation only: it never affects the drawing.
/// </summary>
public sealed class ShapeSideView
{
public ShapeSideView(IReadOnlyList<Entity> entities, IReadOnlyList<ShapeDimension> dimensions)
{
Entities = entities;
Dimensions = dimensions;
}
/// <summary>The section's closed outlines, in the view's own coordinates.</summary>
public IReadOnlyList<Entity> Entities { get; }
/// <summary>The section's dimensions, in the same coordinates as <see cref="Entities"/>.</summary>
public IReadOnlyList<ShapeDimension> Dimensions { get; }
}
}
+119
View File
@@ -0,0 +1,119 @@
using System;
using System.Collections.Generic;
using System.Linq;
using OpenNest.Bending;
using OpenNest.Geometry;
namespace OpenNest.Shapes
{
/// <summary>
/// Flat blanks and sections for the sheet metal shapes: parts bent or rolled along their
/// length, cut as a rectangle <c>length</c> along X by the developed width along Y.
/// </summary>
internal static class SheetMetal
{
public const double BendAngle = 90;
public static void Validate(double thickness, double length, double kFactor)
{
if (!(thickness > 0))
throw new InvalidOperationException("The thickness must be more than zero.");
if (!(length > 0))
throw new InvalidOperationException("The length must be more than zero.");
if (!(kFactor >= 0 && kFactor <= 1))
throw new InvalidOperationException("The K-factor must be from 0 to 1.");
}
public static double BendAllowance(double insideRadius, double thickness, double kFactor) =>
BendMath.Allowance(Math.Angle.ToRadians(BendAngle), insideRadius, thickness, kFactor);
/// <summary>The blank's outline, with a 90° up bend across it, etched, at each bend line.</summary>
/// <param name="bendLines">Each bend line's distance from the blank's bottom edge.</param>
public static List<Entity> Entities(double length, double width, IReadOnlyList<double> bendLines, double insideRadius, out List<Bend> bends)
{
var entities = new List<Entity>
{
new Line(0, 0, length, 0),
new Line(length, 0, length, width),
new Line(length, width, 0, width),
new Line(0, width, 0, 0),
};
bends = bendLines
.Select(y => new Bend
{
StartPoint = new Vector(0, y),
EndPoint = new Vector(length, y),
Direction = BendDirection.Up,
Angle = BendAngle,
Radius = insideRadius,
})
.ToList();
foreach (var bend in bends)
entities.AddRange(bend.GetEtchEntities());
return entities;
}
/// <summary>
/// The section of a part bent up 90° at its right end (an angle, "_|") or at both ends
/// (a channel, "U"): the bottom on Y = 0 from X = 0 to <paramref name="outsideWidth"/>,
/// the sides up to <paramref name="outsideHeight"/>, every bend at
/// <paramref name="insideRadius"/>. Dimensioned with the outside sizes, the thickness
/// across the right side's top and the inside radius of its bend.
/// </summary>
public static ShapeSideView Section(
bool bothSides, double outsideWidth, double outsideHeight, double thickness, double insideRadius,
string widthProperty, string heightProperty, string thicknessProperty, string radiusProperty)
{
const double quarter = System.Math.PI / 2;
var outsideRadius = insideRadius + thickness;
var right = new Vector(outsideWidth - outsideRadius, outsideRadius);
var left = new Vector(outsideRadius, outsideRadius);
var w = outsideWidth;
var h = outsideHeight;
var t = thickness;
// Round the outside, counterclockwise from the bottom's left end, then back inside
// (a reversed arc runs clockwise from its start angle to its end angle).
var entities = new List<Entity>();
if (bothSides)
{
entities.Add(new Line(0, h, 0, outsideRadius));
entities.Add(new Arc(left, outsideRadius, 2 * quarter, 3 * quarter));
entities.Add(new Line(outsideRadius, 0, right.X, 0));
}
else
{
entities.Add(new Line(0, 0, right.X, 0));
}
entities.Add(new Arc(right, outsideRadius, 3 * quarter, 4 * quarter));
entities.Add(new Line(w, outsideRadius, w, h));
entities.Add(new Line(w, h, w - t, h));
entities.Add(new Line(w - t, h, w - t, outsideRadius));
entities.Add(new Arc(right, insideRadius, 0, 3 * quarter, true));
if (bothSides)
{
entities.Add(new Line(right.X, t, outsideRadius, t));
entities.Add(new Arc(left, insideRadius, 3 * quarter, 2 * quarter, true));
entities.Add(new Line(t, outsideRadius, t, h));
entities.Add(new Line(t, h, 0, h));
}
else
{
entities.Add(new Line(right.X, t, 0, t));
entities.Add(new Line(0, t, 0, 0));
}
var dimensions = new[]
{
ShapeDimension.Linear(widthProperty, new Vector(0, 0), new Vector(w, 0), ShapeDimension.Down),
ShapeDimension.Linear(heightProperty, new Vector(w, 0), new Vector(w, h), ShapeDimension.Right),
ShapeDimension.Linear(thicknessProperty, new Vector(w - t, h), new Vector(w, h), ShapeDimension.Up),
ShapeDimension.ArcLeader(radiusProperty, right, insideRadius, 3 * quarter, 4 * quarter, "R"),
};
return new ShapeSideView(entities, dimensions);
}
}
}
+13
View File
@@ -0,0 +1,13 @@
using System;
namespace OpenNest.Shapes
{
/// <summary>
/// Marks a <see cref="double"/> shape parameter that is a plain number, such as a K-factor,
/// rather than a length: the Shape Library shows it without fractions or an inch mark.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public sealed class UnitlessAttribute : Attribute
{
}
}
@@ -17,6 +17,8 @@ public class ShapeCutDirectionTests
{
var shapes = new ShapeDefinition[]
{
new AngleShape(),
new ChannelShape(),
new CircleShape(),
new IsoscelesTriangleShape(),
new LShape(),
@@ -26,6 +28,7 @@ public class ShapeCutDirectionTests
new RectangleShape(),
new RightTriangleShape(),
new RingShape(),
new RolledPlateShape(),
new RoundedRectangleShape(),
new TShape(),
new TrapezoidShape(),
@@ -75,6 +78,9 @@ public class ShapeCutDirectionTests
Assert.True(perimeter >= 0, $"{name}: no perimeter");
for (var i = 0; i < contours.Count; i++)
{
// Marks such as etched bend lines are open: they have no winding.
if (contours[i].IsMark)
continue;
var area = ContourWinding.SignedArea(contours[i]);
if (i == perimeter)
Assert.True(area < 0, $"{name}: outside is not clockwise");
@@ -86,6 +92,7 @@ public class ShapeCutDirectionTests
/// <summary>Each contour's winding sign, in a stable order so reordering does not matter.</summary>
private static List<int> Directions(Program program) =>
PostContours.Extract(program, Vector.Zero)
.Where(c => !c.IsMark)
.Select(c => System.Math.Sign(ContourWinding.SignedArea(c)))
.OrderBy(s => s)
.ToList();
+4 -1
View File
@@ -20,7 +20,10 @@ public class ShapeDimensionTests
{
var shape = (ShapeDefinition)Activator.CreateInstance(shapeType)!;
shape.SetPreviewDefaults();
var dimensions = shape.GetDimensions();
// A side view's dimensions show parameters too, each once across both views.
var dimensions = shape.GetDimensions()
.Concat(shape.GetSideView()?.Dimensions ?? Array.Empty<ShapeDimension>())
.ToList();
Assert.NotEmpty(dimensions);
Assert.Equal(dimensions.Count, dimensions.Select(d => d.Property).Distinct().Count());
@@ -0,0 +1,182 @@
using OpenNest.Bending;
using OpenNest.CNC;
using OpenNest.Geometry;
using OpenNest.Shapes;
namespace OpenNest.Tests.Shapes;
public class SheetMetalShapeTests
{
// 90° bend at 5/16 inside radius, 1/8 thick, K 0.42.
private static readonly double Allowance = System.Math.PI / 2 * (0.3125 + 0.42 * 0.125);
[Fact]
public void Angle_BlankIsTheDevelopedWidthByTheLength()
{
var shape = new AngleShape();
shape.SetPreviewDefaults();
var box = shape.GetDrawing().Program.BoundingBox();
// Legs' flats: 2 - 1/8 - 5/16 and 4 - 1/8 - 5/16.
var expected = 1.5625 + 3.5625 + Allowance;
Assert.Equal(expected, shape.FlatLength, 9);
Assert.Equal(12, box.Length, 6);
Assert.Equal(expected, box.Width, 6);
}
[Fact]
public void Angle_BendsUpAcrossTheBlankFromTheShorterLeg()
{
var shape = new AngleShape();
shape.SetPreviewDefaults();
var bend = Assert.Single(shape.GetDrawing().Bends);
var y = 1.5625 + Allowance / 2;
Assert.Equal(y, shape.BendLineDim, 9);
Assert.Equal(new Vector(0, y), bend.StartPoint);
Assert.Equal(new Vector(12, y), bend.EndPoint);
Assert.Equal(BendDirection.Up, bend.Direction);
Assert.Equal(90, bend.Angle);
Assert.Equal(0.3125, bend.Radius);
}
[Fact]
public void Channel_BlankHasTwoBendsInFromEachSide()
{
var shape = new ChannelShape();
shape.SetPreviewDefaults();
var drawing = shape.GetDrawing();
var box = drawing.Program.BoundingBox();
// Sides' flats: 2 - 1/8 - 5/16 each; bottom: 4 - 2(1/8) - 2(5/16).
var expected = 1.5625 * 2 + 3.125 + Allowance * 2;
Assert.Equal(expected, shape.FlatLength, 9);
Assert.Equal(expected, box.Width, 6);
var lines = drawing.Bends.Select(b => b.StartPoint.Y).OrderBy(y => y).ToList();
var inset = 1.5625 + Allowance / 2;
Assert.Equal(2, lines.Count);
Assert.Equal(inset, lines[0], 9);
Assert.Equal(expected - inset, lines[1], 9);
}
[Fact]
public void RolledPlate_BlankIsTheNeutralCircumference()
{
var shape = new RolledPlateShape { InsideDiameter = 10, Thickness = 0.25, KFactor = 0.5, Length = 24 };
var drawing = shape.GetDrawing();
var box = drawing.Program.BoundingBox();
var expected = System.Math.PI * 2 * (5 + 0.125);
Assert.Equal(expected, shape.FlatLength, 9);
Assert.Equal(24, box.Length, 6);
Assert.Equal(expected, box.Width, 6);
Assert.Empty(drawing.Bends);
Assert.Equal(10.5, shape.OutsideDiameter, 9);
}
[Fact]
public void BendLines_AreEtchedOnTheBlank()
{
var shape = new ChannelShape();
shape.SetPreviewDefaults();
var etches = shape.GetDrawing().Program.Codes
.OfType<LinearMove>()
.Count(m => m.Layer == LayerType.Scribe);
// Each 12" bend line gets a 1" dash at either end.
Assert.Equal(4, etches);
}
[Fact]
public void Angle_LegNoLongerThanThicknessPlusRadius_DoesNotMakeAShape()
{
var shape = new AngleShape { OutsideWidth = 4, OutsideHeight = 0.4, Thickness = 0.125, InsideRadius = 0.3125, KFactor = 0.42, Length = 12 };
Assert.Throws<InvalidOperationException>(() => shape.GetDrawing());
}
[Fact]
public void KFactorAboveOne_DoesNotMakeAShape()
{
var shape = new ChannelShape();
shape.SetPreviewDefaults();
shape.KFactor = 1.5;
Assert.Throws<InvalidOperationException>(() => shape.GetDrawing());
}
[Fact]
public void AngleSideView_IsOneClosedSectionOfTheFormedAngle()
{
var shape = new AngleShape();
shape.SetPreviewDefaults();
var section = Assert.Single(ShapeBuilder.GetShapes(shape.GetSideView().Entities));
// Two legs' flats and a quarter annulus at the bend.
const double t = 0.125, ir = 0.3125, or = ir + t;
var expected = t * (4 - or) + t * (2 - or) + System.Math.PI / 4 * (or * or - ir * ir);
Assert.True(section.IsClosed());
Assert.Equal(expected, section.Area(), 1e-4);
var box = section.BoundingBox;
Assert.Equal(4, box.Length, 6);
Assert.Equal(2, box.Width, 6);
}
[Fact]
public void ChannelSideView_IsOneClosedSectionOfTheFormedChannel()
{
var shape = new ChannelShape();
shape.SetPreviewDefaults();
var section = Assert.Single(ShapeBuilder.GetShapes(shape.GetSideView().Entities));
// Two sides' and the bottom's flats and two quarter annuli at the bends.
const double t = 0.125, ir = 0.3125, or = ir + t;
var expected = t * (2 - or) * 2 + t * (4 - 2 * or) + System.Math.PI / 2 * (or * or - ir * ir);
Assert.True(section.IsClosed());
Assert.Equal(expected, section.Area(), 1e-4);
}
[Fact]
public void SideViews_DimensionTheSizesTheBlankCannotShow()
{
var angle = new AngleShape();
angle.SetPreviewDefaults();
var rolled = new RolledPlateShape();
rolled.SetPreviewDefaults();
Assert.Equal(
new[] { nameof(AngleShape.OutsideWidth), nameof(AngleShape.OutsideHeight), nameof(AngleShape.Thickness), nameof(AngleShape.InsideRadius) },
angle.GetSideView().Dimensions.Select(d => d.Property));
var radius = angle.GetSideView().Dimensions.Single(d => d.Property == nameof(AngleShape.InsideRadius));
Assert.Equal(0.3125, radius.ArcRadius, 9);
Assert.Equal("R", radius.Prefix);
Assert.Equal(
new[] { nameof(RolledPlateShape.InsideDiameter), nameof(RolledPlateShape.Thickness) },
rolled.GetSideView().Dimensions.Select(d => d.Property));
}
[Fact]
public void FlatShapes_HaveNoSideView()
{
Assert.Null(new RectangleShape { Length = 10, Width = 5 }.GetSideView());
}
[Fact]
public void GeneratedNames_DescribeThePart()
{
var angle = new AngleShape();
angle.SetPreviewDefaults();
var rolled = new RolledPlateShape();
rolled.SetPreviewDefaults();
Assert.Equal("Angle 4x2x0.125 x 12", angle.GenerateName());
Assert.Equal("Rolled Plate 10 ID x 0.188 x 12", rolled.GenerateName());
}
}
@@ -101,6 +101,52 @@ public class ShapeLibraryFormTests
Assert.True(Find<Button>(form, "addButton").Enabled);
});
[Fact]
public void KFactorIsAPlainNumberNotALength() => ArchUnitsTests.RunSta(() =>
{
using var form = new ShapeLibraryForm();
SelectShape(form, typeof(ChannelShape));
var preview = Find<ShapePreviewControl>(form, "previewBox");
var width = preview.Plate.Parts.Single().BoundingBox.Width;
Assert.Equal("K-Factor: 0.42", preview.LabelText("KFactor"));
var box = OpenEditor(form, "KFactor");
box.Text = "1.5";
Press(box, Keys.Enter);
Assert.Same(box, form.ActiveEditor);
box.Text = "0.5";
Press(box, Keys.Enter);
Assert.Null(form.ActiveEditor);
Assert.Equal("K-Factor: 0.5", preview.LabelText("KFactor"));
// Two bends' allowance grows by 90° x 0.08 of the 1/8" thickness each.
Assert.Equal(width + System.Math.PI * 0.08 * 0.125, preview.Plate.Parts.Single().BoundingBox.Width, 6);
});
[Fact]
public void ASheetMetalPartsSideViewDimensionsItsSection() => ArchUnitsTests.RunSta(() =>
{
using var form = new ShapeLibraryForm();
SelectShape(form, typeof(AngleShape));
var preview = Find<ShapePreviewControl>(form, "previewBox");
var blank = preview.Plate.Parts.Single().BoundingBox;
Assert.Equal(new[] { "Length", "OutsideWidth", "OutsideHeight", "Thickness", "InsideRadius", "KFactor" }, preview.LabelKeys);
Assert.Equal("4\"", preview.LabelText("OutsideWidth"));
Assert.Equal("R5/16\"", preview.LabelText("InsideRadius"));
// The section sits to the right of the blank, its dimensions with it.
Assert.True(preview.LabelBounds("OutsideWidth")!.Value.Left > preview.LabelBounds("Length")!.Value.Right);
var box = OpenEditor(form, "OutsideWidth");
box.Text = "6";
Press(box, Keys.Enter);
Assert.Null(form.ActiveEditor);
Assert.Equal("6\"", preview.LabelText("OutsideWidth"));
Assert.Equal(blank.Width + 2, preview.Plate.Parts.Single().BoundingBox.Width, 6);
});
[Fact]
public void TabCommitsAndMovesToTheNextDimension() => ArchUnitsTests.RunSta(() =>
{
+131 -16
View File
@@ -58,6 +58,16 @@ namespace OpenNest.Controls
// The shown drawing's cut geometry, in its own coordinates (as dimension points are).
private List<Entity> profile = new();
// A sheet metal part's section beside the blank, in its own coordinates, and where it is
// shown: view = offset + point * scale. Empty when the shape has none.
private List<Entity> sideProfile = new();
private List<Polygon> sideOutlines = new();
private Vector sideOffset;
private double sideScale = 1;
// The view the dimension being laid out belongs to.
private Frame frame;
private IReadOnlyList<Annotation> annotations = Array.Empty<Annotation>();
private IReadOnlyList<Note> notes = Array.Empty<Note>();
private AnnotationLayout layout;
@@ -97,7 +107,7 @@ namespace OpenNest.Controls
internal bool IsUserView => userView;
/// <summary>A dimension to draw: its text, and the count text after it when it has one.</summary>
public sealed record Annotation(ShapeDimension Dimension, string Text, string CountText = null);
public sealed record Annotation(ShapeDimension Dimension, string Text, string CountText = null, bool OnSideView = false);
/// <summary>A parameter with no place on the drawing, shown as a chip along the bottom.</summary>
public sealed record Note(string Key, string Text, bool Enabled = true);
@@ -134,6 +144,9 @@ namespace OpenNest.Controls
/// <summary>The keys of the labels on screen, in drawing order (dimensions, then notes).</summary>
internal IReadOnlyList<string> LabelKeys => CurrentLayout().Labels.Select(l => l.Key).ToList();
/// <summary>The text of the label for <paramref name="key"/>, or null when none is shown.</summary>
internal string LabelText(string key) => CurrentLayout().Labels.FirstOrDefault(l => l.Key == key)?.Text;
/// <summary>Where the label for <paramref name="key"/> is on the control, or null when none is shown.</summary>
public Rectangle? LabelBounds(string key)
{
@@ -142,11 +155,17 @@ namespace OpenNest.Controls
}
/// <summary>
/// Shows <paramref name="drawing"/>. A new shape (<paramref name="newShape"/>) fits the
/// view and puts dragged dimensions back; a changed parameter keeps a hand-set view.
/// Shows <paramref name="drawing"/>, and to its right <paramref name="sideView"/>, a sheet metal
/// part's section, enlarged when it would be too small to read beside the blank. A new
/// shape (<paramref name="newShape"/>) fits the view and puts dragged dimensions back; a
/// changed parameter keeps a hand-set view.
/// </summary>
public void ShowDrawing(Drawing drawing, bool newShape = true)
public void ShowDrawing(Drawing drawing, bool newShape = true, IReadOnlyList<Entity> sideView = null)
{
sideProfile = drawing?.Program != null && sideView != null ? sideView.ToList() : new List<Entity>();
sideOutlines = sideProfile.Count == 0
? new List<Polygon>()
: ShapeBuilder.GetShapes(sideProfile).Select(s => s.ToPolygon()).ToList();
if (newShape)
{
userView = false;
@@ -167,6 +186,7 @@ namespace OpenNest.Controls
var shown = Plate.Parts[0].BoundingBox;
var source = drawing.Program.BoundingBox();
shapeOffset = new Vector(shown.X - source.X, shown.Y - source.Y);
PlaceSideView(shown);
FitUnlessUserView();
}
else
@@ -176,6 +196,54 @@ namespace OpenNest.Controls
}
}
/// <summary>
/// Puts the side view to the right of the blank, centered on it, a quarter of the blank's
/// larger size away. A section under 35% of that size is enlarged to it, so a long part's
/// section stays readable; its dimensions show the true sizes.
/// </summary>
private void PlaceSideView(Box blank)
{
sideScale = 1;
sideOffset = Vector.Zero;
var section = SideBounds();
if (section == null)
return;
var blankSize = System.Math.Max(blank.Length, blank.Width);
var sectionSize = System.Math.Max(section.Length, section.Width);
if (sectionSize > 0)
sideScale = System.Math.Max(1, 0.35 * blankSize / sectionSize);
var gap = 0.25 * blankSize;
sideOffset = new Vector(
blank.Right + gap - section.X * sideScale,
blank.Center.Y - (section.Y + section.Width / 2) * sideScale);
}
/// <summary>The side view's bounds in its own coordinates; null when there is none.</summary>
private Box SideBounds()
{
if (sideProfile.Count == 0)
return null;
var boxes = sideProfile.Select(e => e.BoundingBox).ToList();
var left = boxes.Min(b => b.Left);
var bottom = boxes.Min(b => b.Bottom);
return new Box(left, bottom, boxes.Max(b => b.Right) - left, boxes.Max(b => b.Top) - bottom);
}
/// <summary>The blank's and the side view's bounds together, in view coordinates.</summary>
private Box ViewBounds()
{
var blank = Plate.Parts[0].BoundingBox;
var section = SideBounds();
if (section == null)
return blank;
var left = System.Math.Min(blank.Left, sideOffset.X + section.Left * sideScale);
var bottom = System.Math.Min(blank.Bottom, sideOffset.Y + section.Bottom * sideScale);
var right = System.Math.Max(blank.Right, sideOffset.X + section.Right * sideScale);
var top = System.Math.Max(blank.Top, sideOffset.Y + section.Top * sideScale);
return new Box(left, bottom, right - left, top - bottom);
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
@@ -217,7 +285,7 @@ namespace OpenNest.Controls
return;
}
var box = Plate.Parts[0].BoundingBox;
var box = ViewBounds();
if (box.Length <= 0 || box.Width <= 0)
{
base.ZoomToFit(redraw);
@@ -251,7 +319,7 @@ namespace OpenNest.Controls
UpdateMatrix();
layout = BuildLayout();
var shape = ShapeRect();
var shape = GuiRect(box);
var reach = layout.DimensionBounds;
if (reach.IsEmpty)
break;
@@ -438,12 +506,34 @@ namespace OpenNest.Controls
Renderer.DrawPlate(e.Graphics);
Renderer.DrawLibraryParts(e.Graphics, ColorScheme.Default);
e.Graphics.ResetTransform();
PaintSideView(e.Graphics);
layout = BuildLayout();
PaintAnnotations(e.Graphics, layout);
PaintInfo(e.Graphics);
}
/// <summary>Fills and outlines the side view's section as the blank is drawn.</summary>
private void PaintSideView(Graphics g)
{
if (sideOutlines.Count == 0 || Plate.Parts.Count == 0)
return;
frame = SideFrame();
using var path = new GraphicsPath(FillMode.Alternate);
foreach (var outline in sideOutlines)
{
var points = outline.Vertices.Select(ToScreen).ToArray();
if (points.Length > 2)
path.AddPolygon(points);
}
var scheme = ColorScheme.Default;
using var fill = new SolidBrush(scheme.LibraryFillColor);
using var pen = new Pen(scheme.LibraryOutlineColor);
g.FillPath(fill, path);
g.DrawPath(pen, path);
}
private void PaintInfo(Graphics g)
{
if (infoLines == null)
@@ -534,15 +624,34 @@ namespace OpenNest.Controls
new(TextRenderer.MeasureText(text, Font, System.Drawing.Size.Empty, TextFormatFlags.NoPadding).Width + 2 * LabelPadding,
LabelHeight);
/// <summary>
/// One view's place on the control, the blank's or the side view's: its points are
/// shown at <see cref="Offset"/> + point x <see cref="Scale"/>.
/// </summary>
private readonly record struct Frame(Vector Offset, double Scale, List<Entity> Profile, RectangleF Rect);
private Frame BlankFrame() =>
new(shapeOffset, 1, profile, GuiRect(Plate.Parts[0].BoundingBox));
private Frame SideFrame()
{
var section = SideBounds();
var shown = new Box(sideOffset.X + section.X * sideScale, sideOffset.Y + section.Y * sideScale,
section.Length * sideScale, section.Width * sideScale);
return new(sideOffset, sideScale, sideProfile, GuiRect(shown));
}
private PointF ToScreen(Vector shapePoint)
{
var graph = PointWorldToGraph(shapePoint.X + shapeOffset.X, shapePoint.Y + shapeOffset.Y);
var graph = PointWorldToGraph(shapePoint.X * frame.Scale + frame.Offset.X, shapePoint.Y * frame.Scale + frame.Offset.Y);
return new PointF(graph.X + origin.X, graph.Y + origin.Y);
}
private RectangleF ShapeRect()
/// <summary>A length in the current frame's coordinates, in pixels.</summary>
private float FrameToGui(double length) => LengthWorldToGui(length * frame.Scale);
private RectangleF GuiRect(Box box)
{
var box = Plate.Parts[0].BoundingBox;
var graphTopLeft = PointWorldToGraph(box.X, box.Y + box.Width);
return new RectangleF(graphTopLeft.X + origin.X, graphTopLeft.Y + origin.Y,
LengthWorldToGui(box.Length), LengthWorldToGui(box.Width));
@@ -554,9 +663,14 @@ namespace OpenNest.Controls
if (Plate.Parts.Count == 0)
return result;
var shape = ShapeRect();
var blank = BlankFrame();
var side = sideProfile.Count > 0 ? SideFrame() : (Frame?)null;
foreach (var annotation in annotations)
{
if (annotation.OnSideView && side == null)
continue;
frame = annotation.OnSideView ? side.Value : blank;
var shape = frame.Rect;
var d = annotation.Dimension;
switch (d.Kind)
{
@@ -572,6 +686,7 @@ namespace OpenNest.Controls
}
}
frame = blank;
result.Labels.AddRange(LayoutChips());
return result;
}
@@ -621,15 +736,15 @@ namespace OpenNest.Controls
/// </summary>
private float ExtensionStart(Vector point, Vector side, float reach, RectangleF shape)
{
if (profile.Count == 0 || !(reach > 0))
if (frame.Profile == null || frame.Profile.Count == 0 || !(reach > 0))
return 0;
var limit = reach + (System.Math.Abs(side.X) > System.Math.Abs(side.Y) ? shape.Width : shape.Height);
var travelled = 0f;
for (var i = 0; i < MaxExtensionSteps && travelled < limit; i++)
{
var at = point + side * LengthGuiToWorld(reach - travelled);
var free = LengthWorldToGui(DistanceToProfile(at)) - ExtensionClearance;
var at = point + side * (LengthGuiToWorld(reach - travelled) / frame.Scale);
var free = FrameToGui(DistanceToProfile(at)) - ExtensionClearance;
if (free <= ExtensionPrecision)
break;
travelled += free;
@@ -640,7 +755,7 @@ namespace OpenNest.Controls
private double DistanceToProfile(Vector point)
{
var nearest = double.MaxValue;
foreach (var entity in profile)
foreach (var entity in frame.Profile)
nearest = System.Math.Min(nearest, point.DistanceTo(entity.ClosestPointTo(point)));
return nearest;
}
@@ -648,7 +763,7 @@ namespace OpenNest.Controls
private void AddReferenceCircle(AnnotationLayout result, ShapeDimension d)
{
if (d.CircleCenter is { } center && d.CircleRadius > 0)
result.Circles.Add((ToScreen(center), LengthWorldToGui(d.CircleRadius)));
result.Circles.Add((ToScreen(center), FrameToGui(d.CircleRadius)));
}
/// <summary>The current zoom relative to the fitted view: 1 until zoomed by hand.</summary>
@@ -784,7 +899,7 @@ namespace OpenNest.Controls
return false;
var center = ToScreen(holeCenter);
var radius = LengthWorldToGui(d.HoleRadius);
var radius = FrameToGui(d.HoleRadius);
var toEnd = new PointF(end.X - center.X, end.Y - center.Y);
var distance = (float)System.Math.Sqrt(Dot(toEnd, toEnd));
+33 -11
View File
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Globalization;
@@ -388,21 +389,28 @@ namespace OpenNest.Forms
addButton.Enabled = true;
nameTextBox.Text = shape.GenerateName();
previewBox.ShowDrawing(drawing, newShape);
var sideView = shape.GetSideView();
previewBox.ShowDrawing(drawing, newShape, sideView?.Entities);
newShape = false;
var dimensions = shape.GetDimensions()
.Where(d => Parameter(d.Property) != null)
var dimensions = shape.GetDimensions().Select(d => (Dimension: d, OnSideView: false))
.Concat((sideView?.Dimensions ?? Array.Empty<ShapeDimension>()).Select(d => (Dimension: d, OnSideView: true)))
.Where(d => Parameter(d.Dimension.Property) != null)
.ToList();
var placed = dimensions.Select(d => d.Property)
.Concat(dimensions.Select(d => d.CountProperty).Where(p => p != null))
var placed = dimensions.Select(d => d.Dimension.Property)
.Concat(dimensions.Select(d => d.Dimension.CountProperty).Where(p => p != null))
.ToHashSet();
previewBox.SetAnnotations(
dimensions.Select(d => new ShapePreviewControl.Annotation(d,
d.Prefix + FormatLength((double)values[d.Property]),
d.CountProperty != null && values.TryGetValue(d.CountProperty, out var count)
? $"x {count} {d.CountNoun}"
: null)).ToList(),
dimensions.Select(item =>
{
var d = item.Dimension;
return new ShapePreviewControl.Annotation(d,
d.Prefix + FormatLength((double)values[d.Property]),
d.CountProperty != null && values.TryGetValue(d.CountProperty, out var count)
? $"x {count} {d.CountNoun}"
: null,
item.OnSideView);
}).ToList(),
parameters.Where(p => !placed.Contains(p.Name)).Select(NoteFor).ToList());
var bb = drawing.Program.BoundingBox();
@@ -444,14 +452,18 @@ namespace OpenNest.Forms
var text = value switch
{
bool b => b ? "Yes" : "No",
double d when IsUnitless(prop) => d.ToString("0.####", CultureInfo.CurrentCulture),
double d => FormatLength(d),
null => "None",
_ => value.ToString(),
};
var enabled = prop.Name != nameof(PipeFlangeShape.PipeSize) || !Equals(values.GetValueOrDefault(nameof(PipeFlangeShape.Blind)), true);
return new ShapePreviewControl.Note(prop.Name, $"{FriendlyName(prop.Name)}: {text}", enabled);
var label = prop.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName ?? FriendlyName(prop.Name);
return new ShapePreviewControl.Note(prop.Name, $"{label}: {text}", enabled);
}
private static bool IsUnitless(PropertyInfo prop) => prop.IsDefined(typeof(UnitlessAttribute));
internal static string FormatLength(double inches) => Fraction.Format(inches) + "\"";
/// <summary>The pipe sizes that fit inside the bolt holes: pipe OD + clearance &lt; pattern - hole.</summary>
@@ -669,6 +681,16 @@ namespace OpenNest.Forms
return null;
}
if (IsUnitless(prop))
{
if (!double.TryParse(text?.Trim(), NumberStyles.Float, CultureInfo.CurrentCulture, out var number) || !double.IsFinite(number))
return $"'{text}' is not a number.";
if (number < 0)
return "The value cannot be negative.";
value = number;
return null;
}
double length;
try
{