feat(labels): etch the part number and bend groups in the label box

Plan Cutting adds each part's label to the clean program it plans from
when CuttingParameters.EtchPartLabels is on (off by default, kept per
machine thickness like the other cutting options), so it is emitted as
scribe marks: shown, counted in cut time, posted through the etch path
and never part of nesting geometry.

The text is the drawing name plus its bend groups ("1234-AB"). A group
is the bend line's direction against the sheet grain in 15 degree steps
(BendGrain.Bucket), named by a fixed letter: A across the grain, B with
it, then C to L. A built-in single-stroke font (StrokeFont) draws it,
centered in the box and shrunk to fit down to half the box height.

Locked or unplanned parts, drawings without a box and common-line
members get no label. A plan-time warning for a label that cannot fit,
a letter beside each bend's etch dashes and a per-group list in the
reports are left for later.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Sonnet 5.5 committed 2026-11-22 17:51:01 -05:00
1 parent e173d6c987
commit 2a59ffb951
16 files changed
+726 -7

No files matched your search

+1 -1
View File
@@ -74,7 +74,7 @@ Read the relevant contract before changing its behavior:
- [Lead-in placement](docs/geometry/lead-in-placement.md) (including the planner's eroded pierce for cutouts too small for their lead-in and the stop at a feature's center line) and [pierce zones](docs/geometry/pierce-zone.md): opt-in `PierceDiameter` clearance, the hole pole fallback and the planner's perimeter scrap fallback
- [Breakoffs](docs/breakoffs.md): tabbed scrap; `Break`-layer open cuts that are cut but are not material
- [Tabbed cutouts](docs/tabbed-cutouts.md): holes cut in pieces around `Tab`-layer spans that are material but never cut; nesting reads material through `NestingMaterial.ForNesting`, so nothing nests in them
- [Label box](docs/label-box.md): CAD Converter placement for the etched part number, found by eroding the material clear of edges, holes, bend lines and breakoff scrap; placement only, never affects the program
- [Label box](docs/label-box.md): CAD Converter placement for the etched part number, found by eroding the material clear of edges, holes, bend lines and breakoff scrap; the box never affects the program. Plan Cutting etches the number and bend-group letters in it as scribe marks when `CuttingParameters.EtchPartLabels` is on (off by default)
- [Dimensions](docs/dimensions.md): CAD Converter annotations that store placement only, are measured from the cut geometry when shown and never affect the program
- [Common-line cutting](docs/common-line-cutting.md): parts one kerf apart in `Plate.CommonLines` share an edge; spans are derived, never stored, and spacing checks hold group members to the kerf. Plan Cutting cuts each shared span once (the owner, cut first, starts its compensated outside on the common line; partners cut only their remainders) unless the plate is set to cut them twice; only posts implementing `ICommonLinePostProcessor` (CI Fiber) may write it, others refuse. Machine trial pending. Auto Nest and Fill Area pair `AllowCommonLine` drawings at the nest's `CommonLineUsage` (Off by default, byte-identical to no common lines); `NestLayoutCheck` exempts only explicit result groups
- [Support tabs](docs/support-tabs.md): the nest's support grid, the center-of-gravity check, Plan Cutting's tab placement for parts the grid cannot hold level, and its opt-in slicing of slugs the grid cannot hold level
@@ -47,6 +47,7 @@ internal static class OwnedCuttingParameters
TabSizeMaxWidth = Dimension(source.TabSizeMaxWidth),
TabHeldMaxLength = Dimension(source.TabHeldMaxLength),
SliceTippingSlugs = source.SliceTippingSlugs,
EtchPartLabels = source.EtchPartLabels,
Sequencing = new SequenceParameters
{
Method = sequence.Method,
@@ -97,6 +97,8 @@ internal static class StateFingerprint
// Only when on, so fingerprints taken before the setting existed still match.
if (p.SliceTippingSlugs)
text.Append("slugSlices;");
if (p.EtchPartLabels)
text.Append("partLabels;");
Sequence(p.Sequencing);
Assignment(p.Assignment);
text.Append('}');
@@ -113,6 +113,13 @@ namespace OpenNest.CNC.CuttingStrategy
/// </summary>
public bool SliceTippingSlugs { get; set; }
/// <summary>
/// Etches each part's number and bend groups in its drawing's label box when cutting is
/// planned (see docs/label-box.md). Off by default; parts whose drawing has no label box,
/// and common-line members, get no label.
/// </summary>
public bool EtchPartLabels { get; set; }
public SequenceParameters Sequencing { get; set; } = new SequenceParameters();
public AssignmentParameters Assignment { get; set; } = new AssignmentParameters();
}
+159
View File
@@ -0,0 +1,159 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenNest.Bending;
using OpenNest.CNC;
using OpenNest.Geometry;
using OpenNest.Math;
namespace OpenNest.Labels
{
/// <summary>
/// The text etched in a part's <see cref="LabelBox"/>: its drawing name and the bend groups
/// its bends fall in for the way it is placed against the sheet grain.
/// </summary>
/// <remarks>
/// A bend group is the bend line's direction relative to the grain (<see cref="BendGrain.Bucket"/>),
/// named by a fixed letter so a group has the same letter on every part and sheet of a nest:
/// A across the grain, B with it, then C and on for the 15° steps between, in bucket order.
/// Bends sharing a letter can be formed in one setup. Like a dimension, the box only stores
/// placement; the text is made when the part is planned, because the letters depend on how the
/// part was rotated.
/// </remarks>
public static class PartLabels
{
/// <summary>The smallest share of the box height the text may be shrunk to; a longer name is not etched.</summary>
public const double MinimumHeightShare = 0.5;
// Letter per bucket, indexed by BendGrain.Bucket: with the grain B, across it A, the rest C on.
private static readonly char[] BucketLetters = BuildBucketLetters();
private static char[] BuildBucketLetters()
{
var letters = new char[BendGrain.BucketCount];
letters[0] = 'B';
letters[BendGrain.BucketCount / 2] = 'A';
var next = 'C';
for (var bucket = 0; bucket < letters.Length; bucket++)
if (letters[bucket] == 0)
letters[bucket] = next++;
return letters;
}
/// <summary>The bend group letter of a bend line (already rotated into the plate) against the grain.</summary>
public static char GroupLetter(double lineAngle, double grainAngle) =>
BucketLetters[BendGrain.Bucket(lineAngle, grainAngle)];
/// <summary>
/// The distinct bend group letters of <paramref name="bends"/> for a part placed at
/// <paramref name="partRotation"/>, in alphabetical order. Empty without bends.
/// </summary>
public static string GroupLetters(IEnumerable<Bend> bends, double partRotation, double grainAngle)
{
if (bends == null)
return string.Empty;
var letters = new SortedSet<char>();
foreach (var bend in bends)
{
if (bend == null || bend.Length <= Tolerance.Epsilon)
continue;
letters.Add(GroupLetter(bend.LineAngle + partRotation, grainAngle));
}
return new string(letters.ToArray());
}
/// <summary>
/// The label text for a drawing placed at <paramref name="partRotation"/>: its name, then a
/// dash and its bend groups when it has bends, for example <c>1234-AB</c>. Characters the
/// stroke font lacks are dropped from the name. Empty when nothing is left to etch.
/// </summary>
public static string Text(Drawing drawing, double partRotation, double grainAngle)
{
if (drawing == null)
return string.Empty;
var name = new StringBuilder();
foreach (var character in drawing.Name ?? string.Empty)
if (StrokeFont.Has(character) && !char.IsWhiteSpace(character))
name.Append(char.ToUpperInvariant(character));
var groups = GroupLetters(drawing.Bends, partRotation, grainAngle);
if (groups.Length == 0)
return name.ToString();
return name.Length == 0 ? groups : name + "-" + groups;
}
/// <summary>
/// The etch strokes of <paramref name="drawing"/>'s label for a part placed at
/// <paramref name="partRotation"/>, as polylines in the drawing's program frame turned with
/// the part (the frame <c>Part.Program</c> is in before it is located). Null when the drawing
/// has no valid box, no text, or the text cannot be shrunk to fit the box legibly.
/// </summary>
/// <remarks>
/// The text is centered in the box and reads along it. Its height is the box height, or
/// less when the text is longer than the box: it is shrunk to fit, to
/// <see cref="MinimumHeightShare"/> of the box height at the least.
/// </remarks>
public static List<List<Vector>> Strokes(Drawing drawing, double partRotation, double grainAngle)
{
var box = drawing?.LabelBox;
if (box == null || !box.IsValid || !double.IsFinite(partRotation) || !double.IsFinite(grainAngle))
return null;
var text = Text(drawing, partRotation, grainAngle);
if (text.Length == 0)
return null;
var height = box.Height;
var width = StrokeFont.Measure(text) * height;
if (width > box.Width)
{
height *= box.Width / width;
width = box.Width;
}
if (height < box.Height * MinimumHeightShare - Tolerance.Epsilon)
return null;
var offset = drawing.Source?.Offset ?? Vector.Zero;
var strokes = StrokeFont.Strokes(text, height);
foreach (var stroke in strokes)
for (var i = 0; i < stroke.Count; i++)
{
var local = new Vector(stroke[i].X - width / 2, stroke[i].Y - height / 2);
// The source frame loses the program's offset, then turns with the part, as bends do.
var point = box.ToWorld(local) - offset;
stroke[i] = partRotation == 0 ? point : point.Rotate(partRotation);
}
return strokes;
}
/// <summary>
/// Appends <paramref name="drawing"/>'s label to <paramref name="program"/> as scribe
/// (etch) moves, each stroke started by a rapid. Returns false and leaves the program
/// unchanged when <see cref="Strokes"/> has nothing to etch.
/// </summary>
public static bool AddTo(Program program, Drawing drawing, double partRotation, double grainAngle)
{
var strokes = Strokes(drawing, partRotation, grainAngle);
if (program == null || strokes == null || strokes.Count == 0)
return false;
foreach (var stroke in strokes)
{
if (stroke.Count < 2)
continue;
program.Codes.Add(new RapidMove(stroke[0]));
for (var i = 1; i < stroke.Count; i++)
program.Codes.Add(new LinearMove(stroke[i]) { Layer = LayerType.Scribe });
}
return true;
}
}
}
+115
View File
@@ -0,0 +1,115 @@
using System.Collections.Generic;
using OpenNest.Geometry;
namespace OpenNest.Labels
{
/// <summary>
/// A small built-in single-stroke font for etched labels: digits, capital letters and a few
/// marks, drawn as polylines. It needs no font file, so the same text etches on every machine.
/// </summary>
/// <remarks>
/// A glyph is drawn on a grid four wide and eight tall; at a character height of 1 a glyph is
/// <see cref="GlyphWidth"/> wide and the next one starts <see cref="Advance"/> after it, the
/// advance <see cref="LabelBoxOptions.CharacterAdvance"/> sizes a label box with. Lowercase
/// letters are drawn as capitals; characters the font lacks leave a gap.
/// </remarks>
public static class StrokeFont
{
private const double GridWidth = 4;
private const double GridHeight = 8;
private const double GridAdvance = 6;
/// <summary>A glyph's width as a share of the character height.</summary>
public const double GlyphWidth = GridWidth / GridHeight;
/// <summary>The distance from one character's start to the next, as a share of the character height.</summary>
public const double Advance = GridAdvance / GridHeight;
// Each glyph is a list of strokes; each stroke is x,y pairs on the grid.
private static readonly Dictionary<char, double[][]> Glyphs = new()
{
['0'] = new[] { P(0, 0, 4, 0, 4, 8, 0, 8, 0, 0), P(0, 0, 4, 8) },
['1'] = new[] { P(1, 6, 2, 8, 2, 0), P(1, 0, 3, 0) },
['2'] = new[] { P(0, 7, 1, 8, 3, 8, 4, 7, 4, 5, 0, 0, 4, 0) },
['3'] = new[] { P(0, 7, 1, 8, 3, 8, 4, 7, 4, 5, 3, 4, 1, 4), P(3, 4, 4, 3, 4, 1, 3, 0, 1, 0, 0, 1) },
['4'] = new[] { P(3, 0, 3, 8, 0, 3, 4, 3) },
['5'] = new[] { P(4, 8, 0, 8, 0, 4, 3, 4, 4, 3, 4, 1, 3, 0, 1, 0, 0, 1) },
['6'] = new[] { P(4, 7, 3, 8, 1, 8, 0, 7, 0, 1, 1, 0, 3, 0, 4, 1, 4, 3, 3, 4, 0, 4) },
['7'] = new[] { P(0, 8, 4, 8, 1, 0) },
['8'] = new[] { P(1, 4, 0, 5, 0, 7, 1, 8, 3, 8, 4, 7, 4, 5, 3, 4, 1, 4, 0, 3, 0, 1, 1, 0, 3, 0, 4, 1, 4, 3, 3, 4) },
['9'] = new[] { P(0, 1, 1, 0, 3, 0, 4, 1, 4, 7, 3, 8, 1, 8, 0, 7, 0, 5, 1, 4, 4, 4) },
['-'] = new[] { P(0, 4, 4, 4) },
['_'] = new[] { P(0, 0, 4, 0) },
['.'] = new[] { P(1.5, 0, 2.5, 0) },
['/'] = new[] { P(0, 0, 4, 8) },
['A'] = new[] { P(0, 0, 0, 6, 2, 8, 4, 6, 4, 0), P(0, 4, 4, 4) },
['B'] = new[] { P(0, 0, 0, 8, 3, 8, 4, 7, 4, 5, 3, 4, 0, 4), P(3, 4, 4, 3, 4, 1, 3, 0, 0, 0) },
['C'] = new[] { P(4, 7, 3, 8, 1, 8, 0, 7, 0, 1, 1, 0, 3, 0, 4, 1) },
['D'] = new[] { P(0, 0, 0, 8, 3, 8, 4, 7, 4, 1, 3, 0, 0, 0) },
['E'] = new[] { P(4, 8, 0, 8, 0, 0, 4, 0), P(0, 4, 3, 4) },
['F'] = new[] { P(4, 8, 0, 8, 0, 0), P(0, 4, 3, 4) },
['G'] = new[] { P(4, 7, 3, 8, 1, 8, 0, 7, 0, 1, 1, 0, 3, 0, 4, 1, 4, 4, 2, 4) },
['H'] = new[] { P(0, 0, 0, 8), P(4, 0, 4, 8), P(0, 4, 4, 4) },
['I'] = new[] { P(1, 8, 3, 8), P(2, 8, 2, 0), P(1, 0, 3, 0) },
['J'] = new[] { P(4, 8, 4, 1, 3, 0, 1, 0, 0, 1) },
['K'] = new[] { P(0, 0, 0, 8), P(4, 8, 0, 3), P(1, 4, 4, 0) },
['L'] = new[] { P(0, 8, 0, 0, 4, 0) },
['M'] = new[] { P(0, 0, 0, 8, 2, 4, 4, 8, 4, 0) },
['N'] = new[] { P(0, 0, 0, 8, 4, 0, 4, 8) },
['O'] = new[] { P(1, 0, 3, 0, 4, 1, 4, 7, 3, 8, 1, 8, 0, 7, 0, 1, 1, 0) },
['P'] = new[] { P(0, 0, 0, 8, 3, 8, 4, 7, 4, 5, 3, 4, 0, 4) },
['Q'] = new[] { P(1, 0, 3, 0, 4, 1, 4, 7, 3, 8, 1, 8, 0, 7, 0, 1, 1, 0), P(2, 2, 4, 0) },
['R'] = new[] { P(0, 0, 0, 8, 3, 8, 4, 7, 4, 5, 3, 4, 0, 4), P(2, 4, 4, 0) },
['S'] = new[] { P(4, 7, 3, 8, 1, 8, 0, 7, 0, 5, 1, 4, 3, 4, 4, 3, 4, 1, 3, 0, 1, 0, 0, 1) },
['T'] = new[] { P(0, 8, 4, 8), P(2, 8, 2, 0) },
['U'] = new[] { P(0, 8, 0, 1, 1, 0, 3, 0, 4, 1, 4, 8) },
['V'] = new[] { P(0, 8, 2, 0, 4, 8) },
['W'] = new[] { P(0, 8, 1, 0, 2, 4, 3, 0, 4, 8) },
['X'] = new[] { P(0, 8, 4, 0), P(0, 0, 4, 8) },
['Y'] = new[] { P(0, 8, 2, 4, 4, 8), P(2, 4, 2, 0) },
['Z'] = new[] { P(0, 8, 4, 8, 0, 0, 4, 0) },
};
private static double[] P(params double[] coordinates) => coordinates;
/// <summary>True when the font draws <paramref name="character"/> (case ignored).</summary>
public static bool Has(char character) => Glyphs.ContainsKey(char.ToUpperInvariant(character));
/// <summary>The length of <paramref name="text"/> at a character height of 1: the last glyph's width, not its advance.</summary>
public static double Measure(string text)
{
if (string.IsNullOrEmpty(text))
return 0;
return (text.Length - 1) * Advance + GlyphWidth;
}
/// <summary>
/// The strokes of <paramref name="text"/> at <paramref name="height"/>, as polylines with
/// the text's lower left at the origin and reading along +X.
/// </summary>
public static List<List<Vector>> Strokes(string text, double height)
{
var strokes = new List<List<Vector>>();
if (string.IsNullOrEmpty(text))
return strokes;
var scale = height / GridHeight;
for (var index = 0; index < text.Length; index++)
{
if (!Glyphs.TryGetValue(char.ToUpperInvariant(text[index]), out var glyph))
continue;
var left = index * GridAdvance;
foreach (var coordinates in glyph)
{
var stroke = new List<Vector>(coordinates.Length / 2);
for (var i = 0; i + 1 < coordinates.Length; i += 2)
stroke.Add(new Vector((left + coordinates[i]) * scale, coordinates[i + 1] * scale));
strokes.Add(stroke);
}
}
return strokes;
}
}
}
+2
View File
@@ -132,6 +132,7 @@ public static class MachineCuttingDefaults
TabSizeMinWidth = parameters.TabSizeMinWidth * scale,
TabSizeMaxWidth = parameters.TabSizeMaxWidth * scale,
SliceTippingSlugs = parameters.SliceTippingSlugs,
EtchPartLabels = parameters.EtchPartLabels,
PierceClearance = parameters.PierceClearance * scale,
PierceDiameter = parameters.PierceDiameter * scale,
Unknown = previous?.Unknown,
@@ -150,6 +151,7 @@ public static class MachineCuttingDefaults
parameters.TabSizeMinWidth = cutting.TabSizeMinWidth * scale;
parameters.TabSizeMaxWidth = cutting.TabSizeMaxWidth * scale;
parameters.SliceTippingSlugs = cutting.SliceTippingSlugs;
parameters.EtchPartLabels = cutting.EtchPartLabels;
parameters.PierceClearance = cutting.PierceClearance * scale;
parameters.PierceDiameter = cutting.PierceDiameter * scale;
}
+3
View File
@@ -33,6 +33,9 @@ public class ThicknessCuttingConfig
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public bool SliceTippingSlugs { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public bool EtchPartLabels { get; set; }
public double PierceClearance { get; set; } = 0.0625;
/// <summary>The pierce zone's diameter; 0 turns it off.</summary>
@@ -7,6 +7,7 @@ using OpenNest.CNC.CuttingPlanning;
using OpenNest.CutOffs;
using OpenNest.Diagnostics;
using OpenNest.Geometry;
using OpenNest.Labels;
using OpenNest.Support;
namespace OpenNest.Engine.CuttingPlanning;
@@ -153,6 +154,11 @@ public static class CuttingPlanService
+ ", or cut the plate's common lines twice.");
ownedClean = commonLines.Mark(source, ownedClean, source.Location, index);
}
// The label is etched, never material: clean bounds and lead material skip scribe
// moves, and the planner emits them like any other mark (docs/label-box.md).
else if (request.ConfirmedParameters?.EtchPartLabels == true)
PartLabels.AddTo(ownedClean, source.BaseDrawing, source.Rotation,
request.Plate?.GrainAngle ?? 0);
// Material extent only: remote rapids and scribe marks must not widen it, or a
// genuine insert could fail the containment prefilter.
var cleanBounds = NestedPartContainment.CleanBounds(ownedClean, source.Location, token);
+2
View File
@@ -41,6 +41,8 @@ public class CuttingParametersDto
// Written only when on, so files and settings saved without it are unchanged.
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingDefault)]
public bool SliceTippingSlugs { get; set; }
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingDefault)]
public bool EtchPartLabels { get; set; }
public SequenceDto Sequencing { get; set; } = new();
public AssignmentDto Assignment { get; set; } = new();
@@ -95,6 +95,7 @@ public static class CuttingParametersSerializer
NoBedTabMaxWidth = parameters.TabSizeMaxWidth,
TabHeldMaxLength = parameters.TabHeldMaxLength,
SliceTippingSlugs = parameters.SliceTippingSlugs,
EtchPartLabels = parameters.EtchPartLabels,
Sequencing = ToSequenceDto(parameters.Sequencing),
Assignment = ToAssignmentDto(parameters.Assignment),
};
@@ -133,6 +134,7 @@ public static class CuttingParametersSerializer
TabSizeMaxWidth = dto.NoBedTabMaxWidth,
TabHeldMaxLength = dto.TabHeldMaxLength,
SliceTippingSlugs = dto.SliceTippingSlugs,
EtchPartLabels = dto.EtchPartLabels,
Sequencing = FromSequenceDto(dto.Sequencing),
Assignment = FromAssignmentDto(dto.Assignment),
};
+351
View File
@@ -0,0 +1,351 @@
using OpenNest.Bending;
using OpenNest.CNC;
using OpenNest.CNC.CuttingPlanning;
using OpenNest.CNC.CuttingStrategy;
using OpenNest.Data;
using OpenNest.Engine.CuttingPlanning;
using OpenNest.Geometry;
using OpenNest.IO;
using OpenNest.Labels;
using OpenNest.Math;
using OpenNest.Tests.CuttingPlanning;
namespace OpenNest.Tests.Labels;
/// <summary>
/// The etched part label (docs/label-box.md): the stroke font, the bend group letters, the text
/// and strokes in a drawing's label box, and Plan Cutting emitting them as scribe moves.
/// </summary>
public class PartLabelTests
{
private const double Quarter = System.Math.PI / 2;
private static Bend BendAt(double lineAngle, double length = 4)
{
var start = new Vector(2, 2);
return new Bend
{
StartPoint = start,
EndPoint = new Vector(start.X + length * System.Math.Cos(lineAngle), start.Y + length * System.Math.Sin(lineAngle)),
Direction = BendDirection.Up,
};
}
// A 12 inch square with a 3.5 x 0.5 label box at (6, 6).
private static Drawing Panel(string name = "1234", params Bend[] bends)
{
var drawing = new Drawing(name, LeadPathValidationTests.Rectangle(0, 0, 12, 12))
{
LabelBox = new LabelBox(new Vector(6, 6), 3.5, 0.5, 0),
};
drawing.Bends.AddRange(bends);
return drawing;
}
private readonly record struct Bounds(double Left, double Bottom, double Width, double Height)
{
public double Right => Left + Width;
public double Top => Bottom + Height;
}
private static Bounds BoundsOf(IEnumerable<List<Vector>> strokes)
{
var points = strokes.SelectMany(s => s).ToList();
var minX = points.Min(p => p.X);
var minY = points.Min(p => p.Y);
return new Bounds(minX, minY, points.Max(p => p.X) - minX, points.Max(p => p.Y) - minY);
}
// ---- stroke font ----
[Fact]
public void Font_DrawsEveryDigitLetterAndTheDash_AsStrokesInsideTheCharacterCell()
{
foreach (var character in "0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ")
{
Assert.True(StrokeFont.Has(character), character.ToString());
var strokes = StrokeFont.Strokes(character.ToString(), 1);
Assert.NotEmpty(strokes);
Assert.All(strokes, s => Assert.True(s.Count >= 2));
var bounds = BoundsOf(strokes);
Assert.InRange(bounds.Left, -1e-9, StrokeFont.GlyphWidth + 1e-9);
Assert.InRange(bounds.Right, -1e-9, StrokeFont.GlyphWidth + 1e-9);
Assert.InRange(bounds.Bottom, -1e-9, 1 + 1e-9);
Assert.InRange(bounds.Top, -1e-9, 1 + 1e-9);
}
}
[Fact]
public void Font_AdvanceMatchesTheLabelBoxSizing_AndLowercaseIsCapitals()
{
Assert.Equal(LabelBoxOptions.CharacterAdvance, StrokeFont.Advance);
var width = StrokeFont.Measure("1234-AB") * 0.25;
var options = LabelBoxOptions.ForText(7, 0.25, 0.125);
Assert.True(width <= options.Width + 1e-9);
Assert.Equal(BoundsOf(StrokeFont.Strokes("AB", 1)), BoundsOf(StrokeFont.Strokes("ab", 1)));
}
[Fact]
public void Font_ScalesWithHeight_AndLeavesAGapForACharacterItLacks()
{
var one = BoundsOf(StrokeFont.Strokes("H", 1));
var four = BoundsOf(StrokeFont.Strokes("H", 4));
Assert.Equal(one.Width * 4, four.Width, 9);
Assert.Equal(one.Height * 4, four.Height, 9);
Assert.False(StrokeFont.Has('#'));
var gap = BoundsOf(StrokeFont.Strokes("H#H", 1));
var tight = BoundsOf(StrokeFont.Strokes("HH", 1));
Assert.True(gap.Width > tight.Width);
Assert.Empty(StrokeFont.Strokes("", 1));
Assert.Equal(0, StrokeFont.Measure(""));
}
// ---- bend groups ----
[Fact]
public void GroupLetters_AAcrossTheGrain_BWithIt_AndEachOtherStepItsOwnLetter()
{
Assert.Equal('A', PartLabels.GroupLetter(Quarter, 0));
Assert.Equal('B', PartLabels.GroupLetter(0, 0));
// Undirected: a bend line and its reverse are the same group.
Assert.Equal(PartLabels.GroupLetter(Quarter, 0), PartLabels.GroupLetter(Quarter + System.Math.PI, 0));
// Every 15 degree step has a letter of its own, so no two groups share one.
var letters = Enumerable.Range(0, BendGrain.BucketCount)
.Select(step => PartLabels.GroupLetter(step * BendGrain.BucketStep, 0))
.ToList();
Assert.Equal(BendGrain.BucketCount, letters.Distinct().Count());
Assert.Equal(['B', 'C', 'D', 'E', 'F', 'G', 'A', 'H', 'I', 'J', 'K', 'L'], letters);
}
[Fact]
public void GroupLetters_FollowThePartsRotationAgainstTheGrain()
{
var bends = new[] { BendAt(Quarter), BendAt(Quarter, 2) };
Assert.Equal("A", PartLabels.GroupLetters(bends, 0, 0));
Assert.Equal("B", PartLabels.GroupLetters(bends, Quarter, 0));
// A grain turned with the part gives the same answer as neither turning.
Assert.Equal("A", PartLabels.GroupLetters(bends, Quarter, Quarter));
}
[Fact]
public void GroupLetters_AreDistinctAndAlphabetical_AndSkipEmptyBends()
{
var bends = new[] { BendAt(0), BendAt(Quarter), BendAt(Quarter), BendAt(0.3), BendAt(1, length: 0) };
Assert.Equal("ABC", PartLabels.GroupLetters(bends, 0, 0));
Assert.Equal(string.Empty, PartLabels.GroupLetters(null, 0, 0));
Assert.Equal(string.Empty, PartLabels.GroupLetters([], 0, 0));
}
// ---- text ----
[Fact]
public void Text_IsTheNameThenTheBendGroups()
{
var drawing = Panel("1234", BendAt(0), BendAt(Quarter));
Assert.Equal("1234-AB", PartLabels.Text(drawing, 0, 0));
// Turned a quarter, the same bends are in the same two groups: A and B swap.
Assert.Equal("1234-AB", PartLabels.Text(drawing, Quarter, 0));
Assert.Equal("1234", PartLabels.Text(Panel("1234"), 0, 0));
}
[Fact]
public void Text_UppercasesTheNameAndDropsWhatTheFontLacks()
{
Assert.Equal("N26-2GT", PartLabels.Text(Panel("n26-2gt"), 0, 0));
Assert.Equal("BRACKETA", PartLabels.Text(Panel("bracket (a)"), 0, 0));
Assert.Equal(string.Empty, PartLabels.Text(Panel("()"), 0, 0));
Assert.Equal("A", PartLabels.Text(Panel("()", BendAt(Quarter)), 0, 0));
Assert.Equal(string.Empty, PartLabels.Text(null, 0, 0));
}
// ---- strokes ----
[Fact]
public void Strokes_AreCenteredInTheBoxAtTheBoxHeight()
{
// H, A and B fill their whole character cell, so the strokes' bounds are the text's.
var drawing = Panel("HH", BendAt(0), BendAt(Quarter));
var bounds = BoundsOf(PartLabels.Strokes(drawing, 0, 0));
var width = StrokeFont.Measure("HH-AB") * 0.5;
Assert.Equal(0.5, bounds.Height, 9);
Assert.Equal(width, bounds.Width, 9);
Assert.Equal(6, bounds.Left + bounds.Width / 2, 9);
Assert.Equal(6, bounds.Bottom + bounds.Height / 2, 9);
}
[Fact]
public void Strokes_LeaveTheProgramFrameBySourceOffset_AndTurnWithThePart()
{
var drawing = Panel("HH");
drawing.Source.Offset = new Vector(1, 2);
var upright = BoundsOf(PartLabels.Strokes(drawing, 0, 0));
Assert.Equal(5, upright.Left + upright.Width / 2, 9);
Assert.Equal(4, upright.Bottom + upright.Height / 2, 9);
// A quarter turn about the program origin: (5, 4) goes to (-4, 5), and the text stands on end.
var turned = BoundsOf(PartLabels.Strokes(drawing, Quarter, 0));
Assert.Equal(-4, turned.Left + turned.Width / 2, 9);
Assert.Equal(5, turned.Bottom + turned.Height / 2, 9);
Assert.Equal(upright.Width, turned.Height, 9);
Assert.Equal(upright.Height, turned.Width, 9);
}
[Fact]
public void Strokes_ShrinkALongNameToFitTheBox_AndSkipOneThatWouldBeTooSmall()
{
// 3.5 fits "1234-AB" (7 characters) at the full 0.5 height; "123456789-AB" is 11.
var shrunk = BoundsOf(PartLabels.Strokes(Panel("123456789", BendAt(0), BendAt(Quarter)), 0, 0));
Assert.True(shrunk.Width <= 3.5 + 1e-9);
Assert.InRange(shrunk.Height, 0.25 - 1e-9, 0.5);
Assert.Null(PartLabels.Strokes(Panel("1234567890123456789012345"), 0, 0));
}
[Fact]
public void Strokes_AreNull_WithoutAValidBoxOrAnyText()
{
var none = Panel("1234");
none.LabelBox = null;
Assert.Null(PartLabels.Strokes(none, 0, 0));
var broken = Panel("1234");
broken.LabelBox.Width = 0;
Assert.Null(PartLabels.Strokes(broken, 0, 0));
Assert.Null(PartLabels.Strokes(Panel("()"), 0, 0));
Assert.Null(PartLabels.Strokes(Panel("1234"), double.NaN, 0));
Assert.Null(PartLabels.Strokes(null, 0, 0));
}
[Fact]
public void AddTo_AppendsScribeMovesEachStrokeStartedByARapid_OrLeavesTheProgramAlone()
{
var drawing = Panel("1234", BendAt(Quarter));
var program = (Program)drawing.Program.Clone();
var before = program.Codes.Count;
Assert.True(PartLabels.AddTo(program, drawing, 0, 0));
var added = program.Codes.Skip(before).ToList();
Assert.IsType<RapidMove>(added[0]);
Assert.All(added.OfType<LinearMove>(), move => Assert.Equal(LayerType.Scribe, move.Layer));
Assert.True(added.OfType<LinearMove>().Count() > 10);
var untouched = (Program)drawing.Program.Clone();
drawing.LabelBox = null;
Assert.False(PartLabels.AddTo(untouched, drawing, 0, 0));
Assert.Equal(before, untouched.Codes.Count);
}
// ---- Plan Cutting ----
private static CuttingParameters Parameters(bool labels)
{
var parameters = ExplicitContourTests.Parameters();
parameters.EtchPartLabels = labels;
return parameters;
}
private static (Plate Plate, Part Part) PlateOf(Drawing drawing, CuttingParameters parameters, double grain = 0,
double rotation = 0)
{
var plate = new Plate(30, 30) { CuttingParameters = parameters, GrainAngle = grain };
var part = new Part(drawing, new Vector(1, 1));
if (rotation != 0)
part.Rotate(rotation);
plate.Parts.Add(part);
return (plate, part);
}
private static List<ExecutionMotion> ScribeOf(CuttingPlanResult result)
{
var proposal = Assert.Single(result.ProposedOrder);
return ExecutionMotionReader.Read(proposal.CopyProgram(), proposal.Location, null, default).Motions
.Where(m => !m.Rapid && m.Layer == LayerType.Scribe).ToList();
}
[Fact]
public void PlanCutting_EtchesTheLabelInsideTheBoxOnTheSheet_WhenOn()
{
var drawing = Panel("1234", BendAt(0), BendAt(Quarter));
var (plate, _) = PlateOf(drawing, Parameters(true));
var result = CuttingPlanService.Plan(CuttingPlanRequest.ForPlate(plate, Vector.Zero,
confirmedParameters: Parameters(true)));
Assert.True(result.Status == CuttingPlanStatus.Ready, string.Join("\n", result.Findings.Select(f => f.Message)));
var marks = ScribeOf(result);
Assert.True(marks.Count > 10);
// The box is centered at (6, 6) on the part, which sits at (1, 1) on the sheet.
foreach (var mark in marks)
{
Assert.InRange(mark.End.X, 7 - 1.75 - 1e-6, 7 + 1.75 + 1e-6);
Assert.InRange(mark.End.Y, 7 - 0.25 - 1e-6, 7 + 0.25 + 1e-6);
}
}
[Fact]
public void PlanCutting_EtchesNothing_WhenOffOrWithoutABox()
{
var (offPlate, _) = PlateOf(Panel("1234", BendAt(0)), Parameters(false));
var off = CuttingPlanService.Plan(CuttingPlanRequest.ForPlate(offPlate, Vector.Zero,
confirmedParameters: Parameters(false)));
Assert.Equal(CuttingPlanStatus.Ready, off.Status);
Assert.Empty(ScribeOf(off));
var unboxed = Panel("1234", BendAt(0));
unboxed.LabelBox = null;
var (onPlate, _) = PlateOf(unboxed, Parameters(true));
var on = CuttingPlanService.Plan(CuttingPlanRequest.ForPlate(onPlate, Vector.Zero,
confirmedParameters: Parameters(true)));
Assert.Equal(CuttingPlanStatus.Ready, on.Status);
Assert.Empty(ScribeOf(on));
}
[Fact]
public void PlanCutting_LabelsTheGroupsForThePartsRotationOnTheSheet()
{
// One bend across the grain: group A upright, group B when the part is turned a quarter.
var drawing = Panel("7", BendAt(Quarter));
var (upright, _) = PlateOf(drawing, Parameters(true));
var (turned, _) = PlateOf(drawing, Parameters(true), rotation: Quarter);
var a = CuttingPlanService.Plan(CuttingPlanRequest.ForPlate(upright, Vector.Zero, confirmedParameters: Parameters(true)));
var b = CuttingPlanService.Plan(CuttingPlanRequest.ForPlate(turned, Vector.Zero, confirmedParameters: Parameters(true)));
Assert.Equal(CuttingPlanStatus.Ready, a.Status);
Assert.Equal(CuttingPlanStatus.Ready, b.Status);
// "7-A" and "7-B" differ in their last glyph, so their strokes differ in count.
Assert.NotEqual(ScribeOf(a).Count, ScribeOf(b).Count);
}
// ---- the option ----
[Fact]
public void Option_IsOffByDefault_AndSurvivesEveryCopyAndSave()
{
Assert.False(new CuttingParameters().EtchPartLabels);
var on = Parameters(true);
Assert.True(OwnedCuttingParameters.Copy(on).EtchPartLabels);
Assert.True(CuttingParametersSerializer.Deserialize(CuttingParametersSerializer.Serialize(on)).EtchPartLabels);
Assert.False(CuttingParametersSerializer.Deserialize(CuttingParametersSerializer.Serialize(Parameters(false))).EtchPartLabels);
var config = MachineCuttingDefaults.ToCuttingConfig(on);
Assert.True(config.EtchPartLabels);
Assert.True(MachineCuttingDefaults.CuttingOf(config).EtchPartLabels);
Assert.False(MachineCuttingDefaults.CuttingOf(null).EtchPartLabels);
}
}
@@ -62,6 +62,20 @@ public class CuttingPanelTests
}, TimeSpan.FromSeconds(30), "The cutting panel did not build tabs by size.");
}
[Fact]
public void EtchPartLabels_IsOffByDefault_AndRoundTrips()
{
StaTestThread.Run(() =>
{
using var panel = new CuttingPanel();
panel.LoadFromParameters(new CuttingParameters());
Assert.False(panel.BuildParameters().EtchPartLabels);
panel.LoadFromParameters(new CuttingParameters { EtchPartLabels = true });
Assert.True(panel.BuildParameters().EtchPartLabels);
}, TimeSpan.FromSeconds(30), "The cutting panel did not round-trip the part label option.");
}
[Fact]
public void TabEveryPart_LoadsAsTabsBySizeOverEveryWidth()
{
+18
View File
@@ -32,6 +32,7 @@ namespace OpenNest.Controls
private readonly NumericUpDown nudTabSizeMax;
private readonly NumericUpDown nudTabHeldMax;
private readonly CheckBox chkSliceSlugs;
private readonly CheckBox chkEtchPartLabels;
private readonly NumericUpDown nudPierceClearance;
private readonly NumericUpDown nudPierceDiameter;
@@ -283,6 +284,21 @@ namespace OpenNest.Controls
layout.Controls.Add(chkSliceSlugs);
chkSliceSlugs.CheckedChanged += (s, e) => OnParametersChanged();
// Marks: the part number and bend groups etched in each drawing's label box.
AddSection("Marks");
chkEtchPartLabels = new CheckBox
{
Text = "Etch part number and bend groups",
AutoSize = true,
Margin = new Padding(0, 3, 0, 3),
};
toolTip.SetToolTip(chkEtchPartLabels,
"Plan Cutting etches each part's number and bend groups (A across the grain, B with it, "
+ "then C and on) in the label box set in the CAD Converter. Parts with no label box get none.");
layout.Controls.Add(chkEtchPartLabels);
chkEtchPartLabels.CheckedChanged += (s, e) => OnParametersChanged();
// Pierce
AddSection("Pierce");
@@ -373,6 +389,7 @@ namespace OpenNest.Controls
parameters.TabSizeMaxWidth = (double)nudTabSizeMax.Value;
parameters.TabHeldMaxLength = (double)nudTabHeldMax.Value;
parameters.SliceTippingSlugs = chkSliceSlugs.Checked;
parameters.EtchPartLabels = chkEtchPartLabels.Checked;
return parameters;
}
@@ -400,6 +417,7 @@ namespace OpenNest.Controls
tabOptions.Enabled = chkTabsEnabled.Checked;
UpdateSupportTabOptions();
chkSliceSlugs.Checked = p.SliceTippingSlugs;
chkEtchPartLabels.Checked = p.EtchPartLabels;
nudPierceClearance.Value = Clamp(nudPierceClearance, p.PierceClearance);
nudPierceDiameter.Value = Clamp(nudPierceDiameter, p.PierceDiameter);
chkRoundLeadInAngles.Checked = p.RoundLeadInAngles;
+42 -5
View File
@@ -1,8 +1,9 @@
# Part number label box
A drawing can carry a label box: the rectangle where its part number will be etched, found
on flat material clear of everything else. This stage stores and shows the placement only;
nothing is etched yet.
A drawing can carry a label box: the rectangle where its part number and bend groups are
etched, found on flat material clear of everything else. The CAD Converter stores and shows the
placement; Plan Cutting etches the text when **Etch part number and bend groups** is on (see
[Etching the label](#etching-the-label)).
In the CAD Converter, **Label Box...** (bottom bar) finds the best spot for the shown part.
The box is drawn as a dashed rectangle. Drag its body to move it and a corner to resize it
@@ -40,14 +41,50 @@ nesting geometry, cut time or posts, and it does not appear in DXF, DWG or SVG e
clearance.
- Split pieces start with no label box, like dimensions, breakoffs and tabbed cutouts.
Out of scope for now: etching the text, the bend group letters, and an automatic placement
on import; the box is placed when asked.
The box is placed when asked, not automatically on import.
File format: see [drawing label box](nest-file-format.md#drawing-label-box).
## Etching the label
Cutting Parameters > Marks > **Etch part number and bend groups** (`CuttingParameters.EtchPartLabels`)
is off by default and kept per machine thickness like the other cutting options
([machine cutting defaults](machine-cutting-defaults.md), saved with the nest and the machine's
thickness settings). When it is on, Plan Cutting adds each part's label to the clean program it
plans from, so the label is emitted as scribe (etch) moves like any other mark: it shows in the plan,
counts in cut time, posts through the etch path and never enters nesting or collision geometry
(marks are not material). Nothing changes while the option is off, and parts planned before it was
turned on keep no label until planned again.
- **Text.** `PartLabels.Text` is the drawing name in capitals (characters the font lacks are
dropped), then a dash and the part's bend groups when it has bends: `1234-AB`.
- **Bend groups.** A bend's group is its line's direction against the sheet grain in 15° steps
(`BendGrain.Bucket`, bend line plus the part's rotation against `Plate.GrainAngle`), named by a
fixed letter so a group means the same thing on every part and sheet: **A** across the grain,
**B** with it, then **C** to **L** for the steps between, in bucket order from the grain. Bends
with the same letter can be formed in one setup. The letters depend on how the part is
rotated on the sheet, which is why the text is made when cutting is planned, not stored with the
box.
- **Font.** `StrokeFont` is a small built-in single-stroke font (digits, capitals, `- _ . /`), so
the label needs no font file. The CHR reader (`ChrFont`) loads vendor fonts from disk and is not
used.
- **Fit.** The text is centered in the box and reads along it at the box's height. A name longer
than the box is shrunk to fit, to half the box height at the least; a longer one is not etched.
The text turns with the part, so it can read upside down or sideways on the sheet.
- **Frames.** The box and the bends are in the source frame: the program's offset
(`Drawing.Source.Offset`) comes off, then the part's rotation applies, as `BendToWorld` does.
- **What gets none.** A drawing with no box, parts whose cutting is locked or left out of the plan
(the label is added only where Plan Cutting regenerates the program), and common-line members
(their programs are rebuilt from their shared spans).
Not done yet: a plan-time warning for a label that cannot fit (it is skipped without a message),
a group letter next to each bend's own etch dashes, and a parts-per-bend-group list in the part
printout and nest report.
## Regression checks
```sh
dotnet test OpenNest.Tests/OpenNest.Tests.csproj -c Release --filter "FullyQualifiedName~Labels"
dotnet test OpenNest.Tests/OpenNest.Tests.csproj -c Release --filter "FullyQualifiedName~PartLabelTests"
scripts/Test-Hidden.ps1 OpenNest.WinForms.Tests/OpenNest.WinForms.Tests.csproj --filter FullyQualifiedName~CadConverterLabelBoxTests
```
+1 -1
View File
@@ -27,7 +27,7 @@ save them on close; thicknesses matching none stay blank.
Every setting in Plan Cutting's Cutting Parameters dialog and the Place Lead-in panel is kept on
the nest's machine thickness: leads on the Outside Cuts and Inside Cuts tabs, lead-in angle
rounding, tabs, [slug slicing](support-tabs.md#slug-slices) and pierce on the Tabs & Pierce tab
rounding, tabs, [slug slicing](support-tabs.md#slug-slices), [part label etching](label-box.md#etching-the-label) and pierce on the Tabs & Pierce tab
(`ThicknessConfig.Cutting`). So 0.25 in can
tab parts while 0.5 in tabs none, and in Database mode every workstation gets the same
settings. The dialog names what it edits above its fields ("Saved for Fiber 1 · Mild Steel A36