diff --git a/AGENTS.md b/AGENTS.md index a54029c6..907ff8ae 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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; the box never affects the program. Plan Cutting etches the number, with or without bend-group letters, in it as scribe marks per `CuttingParameters.LabelMode` (`PartLabelMode`, off by default) +- [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 in it, with or without each bend's group letter beside its bend line (no box needed), as scribe marks per `CuttingParameters.LabelMode` (`PartLabelMode`, 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 diff --git a/OpenNest.Console/Program.cs b/OpenNest.Console/Program.cs index 7f2322d5..b8b4f932 100644 --- a/OpenNest.Console/Program.cs +++ b/OpenNest.Console/Program.cs @@ -854,7 +854,7 @@ static class NestConsole Console.WriteLine("---"); Console.WriteLine($"Cutting settings: {(explicitParameters != null ? options.CuttingParamsFile : "saved with the plates")}"); var batch = CuttingPlanBatch.Capture(scope, parameters, options.KeepPartOrder, - scope.Select(p => nest.Plates.IndexOf(p)).ToArray(), token); + scope.Select(p => nest.Plates.IndexOf(p)).ToArray(), token, units: nest.Units); var proposal = batch.Plan(new PlanningProgress(scope.Length), token); token.ThrowIfCancellationRequested(); diff --git a/OpenNest.Core/CNC/CuttingPlanning/PlateCuttingState.cs b/OpenNest.Core/CNC/CuttingPlanning/PlateCuttingState.cs index ad0313e8..286f9167 100644 --- a/OpenNest.Core/CNC/CuttingPlanning/PlateCuttingState.cs +++ b/OpenNest.Core/CNC/CuttingPlanning/PlateCuttingState.cs @@ -230,8 +230,8 @@ public sealed class PlateCuttingState [BitConverter.DoubleToInt64Bits(box.X), BitConverter.DoubleToInt64Bits(box.Y), BitConverter.DoubleToInt64Bits(box.Width), BitConverter.DoubleToInt64Bits(box.Length)]; - // Exact text of what a part label is made from (PartLabels.Strokes): the name, the box, the - // bends and the source offset, doubles by bit pattern. + // Exact text of what a part label and its bend letters are made from (PartLabels.Strokes, + // BendLabels.Spots): the name, the box, the bends and the source offset, doubles by bit pattern. private static string LabelInputs(Drawing drawing) { var text = new System.Text.StringBuilder(); @@ -251,7 +251,9 @@ public sealed class PlateCuttingState if (bend == null) text.Append("null;"); else - Values(bend.StartPoint.X, bend.StartPoint.Y, bend.EndPoint.X, bend.EndPoint.Y); + // The direction, angle and radius place the bend's own letter (BendLabels.Place). + Values(bend.StartPoint.X, bend.StartPoint.Y, bend.EndPoint.X, bend.EndPoint.Y, + (double)bend.Direction, bend.Angle ?? double.NaN, bend.Radius ?? double.NaN); } return text.ToString(); diff --git a/OpenNest.Core/CNC/CuttingStrategy/CuttingParameters.cs b/OpenNest.Core/CNC/CuttingStrategy/CuttingParameters.cs index 06c0077a..a2fa31fb 100644 --- a/OpenNest.Core/CNC/CuttingStrategy/CuttingParameters.cs +++ b/OpenNest.Core/CNC/CuttingStrategy/CuttingParameters.cs @@ -101,9 +101,9 @@ namespace OpenNest.CNC.CuttingStrategy public bool SliceTippingSlugs { get; set; } /// - /// Etches each part's number, with or without its 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. + /// Etches each part's number in its drawing's label box, with or without each bend's group + /// letter beside its bend line, when cutting is planned (see docs/label-box.md). Off by + /// default; a drawing with no label box gets no number, and common-line members get nothing. /// public PartLabelMode LabelMode { get; set; } diff --git a/OpenNest.Core/CNC/CuttingStrategy/PartLabelMode.cs b/OpenNest.Core/CNC/CuttingStrategy/PartLabelMode.cs index 5cf99ac4..467c5012 100644 --- a/OpenNest.Core/CNC/CuttingStrategy/PartLabelMode.cs +++ b/OpenNest.Core/CNC/CuttingStrategy/PartLabelMode.cs @@ -9,7 +9,7 @@ namespace OpenNest.CNC.CuttingStrategy /// The drawing name only, for example 1234. PartNumber, - /// The drawing name and the bend groups of its bends, each letter etched in a circle, for example 1234 AB. + /// The drawing name in its label box, and each bend's group letter in a circle beside its bend line. PartNumberAndBendGroups, } } diff --git a/OpenNest.Core/Labels/BendLabels.cs b/OpenNest.Core/Labels/BendLabels.cs new file mode 100644 index 00000000..9b0d0960 --- /dev/null +++ b/OpenNest.Core/Labels/BendLabels.cs @@ -0,0 +1,272 @@ +using System.Collections.Generic; +using System.Linq; +using Clipper2Lib; +using OpenNest.Bending; +using OpenNest.CNC; +using OpenNest.Converters; +using OpenNest.Geometry; +using OpenNest.Math; + +namespace OpenNest.Labels +{ + /// + /// Where one bend's group letter is etched: the circle's center and diameter, and the index + /// of the bend in the list the spots were placed for. + /// + public readonly record struct BendLabelSpot(int Bend, Vector Center, double Diameter); + + /// + /// The bend group letter etched beside each bend line, so a part whose bends fall in several + /// groups shows which bend is which (the label box only lists the groups). + /// + /// + /// Each letter sits in a circle on flat material just past the bend's radius band, never on + /// the line, where forming would deform it, and reads along the line. Placement depends only + /// on the part and its bends (a label box is not needed, only kept clear of), so it is the + /// same however the part is turned; only the letter depends on the part's rotation against + /// the grain. + /// + public static class BendLabels + { + /// + /// A spot for each bend's letter that has room for one, in the frame of + /// , and (the + /// part's label box, kept clear of; null when it has none). + /// + /// + /// The circle is as big as the label text sizes (): + /// half an inch across is tried first, then three eighths, then a quarter (12, 9 and + /// 6 mm), each an eighth inch (3 mm) clear. For each size the stations along the bend are tried in order (beside each etch dash of an up + /// bend long enough to have two, then the middle and the quarter points), on the left of + /// the line and then the right; the first that fits is kept. A spot fits on material a + /// clearance inside every edge, clear of every bend's band, of scribe marks and break + /// cuts, of the label box and of the letters placed before it. A bend with no such spot + /// gets none. + /// + public static List Place(IEnumerable entities, IReadOnlyList bends, LabelBox box, + Units units = Units.Inches) + { + var spots = new List(); + if (entities == null || bends == null || bends.Count == 0) + return spots; + + var all = entities.ToList(); + var sizes = LabelBoxOptions.Sizes(units); + var clearance = sizes[0].Clearance; + var tolerance = System.Math.Max(clearance / 20, System.Math.Pow(10, -ClipperBridge.Precision)); + var free = LabelBoxFinder.Material(all, clearance, tolerance, out _); + if (free == null || free.Count == 0) + return spots; + + var blocked = new PathsD(); + foreach (var bend in bends) + { + if (IsBend(bend)) + blocked.AddRange(LabelBoxFinder.Strip(bend.StartPoint, bend.EndPoint, Band(bend, clearance), tolerance)); + } + + foreach (var mark in all.Where(e => ScribeLayerRepair.IsMarkLayer(e.Layer) || e.Layer == SpecialLayers.Break)) + blocked.AddRange(Grown(mark, clearance, tolerance)); + + if (box is { IsValid: true }) + { + var corners = new PathD(box.Corners().Select(corner => new PointD(corner.X, corner.Y))); + blocked.AddRange(Clipper.InflatePaths(new PathsD { corners }, clearance, JoinType.Miter, EndType.Polygon, 2.0, + ClipperBridge.Precision, tolerance)); + } + + free = Clipper.Difference(free, blocked, FillRule.NonZero, ClipperBridge.Precision); + if (free.Count == 0) + return spots; + + // Where a circle's center may be, per size: the free region eroded by its radius. + var centers = new PathsD[sizes.Count]; + for (var index = 0; index < bends.Count; index++) + { + var bend = bends[index]; + if (!IsBend(bend)) + continue; + + var length = bend.Length; + var along = new Vector((bend.EndPoint.X - bend.StartPoint.X) / length, (bend.EndPoint.Y - bend.StartPoint.Y) / length); + var left = new Vector(-along.Y, along.X); + var stations = Stations(bend); + var placed = false; + for (var size = 0; size < sizes.Count && !placed; size++) + { + var diameter = sizes[size].Height; + var radius = diameter / 2; + centers[size] ??= Clipper.InflatePaths(free, -radius, JoinType.Round, EndType.Polygon, 2.0, + ClipperBridge.Precision, tolerance); + + // Just past the band, so the erosion's rounding never rejects the spot. + var away = Band(bend, clearance) + radius + 2 * tolerance; + foreach (var station in stations) + { + foreach (var side in new[] { 1, -1 }) + { + var center = new Vector( + bend.StartPoint.X + along.X * station + left.X * side * away, + bend.StartPoint.Y + along.Y * station + left.Y * side * away); + if (!Inside(centers[size], center) + || spots.Any(s => s.Center.DistanceTo(center) < s.Diameter / 2 + radius + clearance)) + continue; + + spots.Add(new BendLabelSpot(index, center, diameter)); + placed = true; + break; + } + if (placed) + break; + } + } + } + return spots; + } + + /// + /// The strokes of each spot's circled letter, in the spots' frame, reading along its bend + /// line. The letter is the bend's group for a part placed at + /// on a sheet whose grain runs at ; + /// are the bends the spots were placed for, unrotated. + /// + public static List Layout(IEnumerable spots, IReadOnlyList bends, double partRotation, + double grainAngle) + { + var strokes = new List(); + if (spots == null || bends == null) + return strokes; + + foreach (var spot in spots) + { + if (spot.Bend < 0 || spot.Bend >= bends.Count || !IsBend(bends[spot.Bend])) + continue; + var line = bends[spot.Bend].LineAngle; + var letter = PartLabels.GroupLetter(line + partRotation, grainAngle); + // Along the line, turned at most a quarter so it never reads upside down. + strokes.AddRange(PartLabels.CircledLetter(letter, spot.Center, spot.Diameter, + LabelBox.ReadableRotation(line))); + } + return strokes; + } + + /// + /// The spots for 's bends, in its program's frame before any + /// rotation (the source frame less the program's offset). Empty without bends or a + /// program; a label box is only kept clear of. The same for every part of the drawing, so callers may keep it. + /// + public static List Spots(Drawing drawing, Units units = Units.Inches) + { + if (drawing?.Program == null || drawing.Bends == null || drawing.Bends.Count == 0) + return new List(); + var box = drawing.LabelBox is { IsValid: true } valid ? valid : null; + + // The program's geometry is in its own frame: the source frame less the offset, turned + // by the program's rotation. The bends and the box go there, and the spots come back. + var offset = drawing.Source?.Offset ?? Vector.Zero; + var turn = drawing.Program.Rotation; + Vector ToProgram(Vector point) + { + var moved = point - offset; + return turn == 0 ? moved : moved.Rotate(turn); + } + + var bends = drawing.Bends.Select(bend => bend == null ? null : new Bend + { + StartPoint = ToProgram(bend.StartPoint), + EndPoint = ToProgram(bend.EndPoint), + Direction = bend.Direction, + Angle = bend.Angle, + Radius = bend.Radius, + }).ToList(); + var spots = Place(ConvertProgram.ToGeometry(drawing.Program), bends, + box == null ? null : new LabelBox(ToProgram(box.Center), box.Width, box.Height, box.Rotation + turn), + units); + return turn == 0 ? spots : spots.ConvertAll(spot => spot with { Center = spot.Center.Rotate(-turn) }); + } + + /// + /// The etch strokes of the bend letters at (from ) + /// for a part placed at , in the drawing's program frame + /// turned with the part. + /// + public static List Strokes(Drawing drawing, IEnumerable spots, double partRotation, + double grainAngle) + { + if (drawing == null || !double.IsFinite(partRotation) || !double.IsFinite(grainAngle)) + return new List(); + + var strokes = Layout(spots, drawing.Bends, partRotation, grainAngle); + return partRotation == 0 + ? strokes + : strokes.ConvertAll(stroke => stroke.Map(point => point.Rotate(partRotation))); + } + + /// + /// Appends the bend letters to as scribe (etch) moves, as + /// does the label. Returns false and leaves the program + /// unchanged when there is nothing to etch. + /// + public static bool AddTo(Program program, Drawing drawing, IEnumerable spots, double partRotation, + double grainAngle) => + PartLabels.Append(program, Strokes(drawing, spots, partRotation, grainAngle)); + + private static bool IsBend(Bend bend) => bend != null && bend.Length > Tolerance.Epsilon; + + // Half the width kept clear along a bend line: the clearance, or half the arc the bend + // rolls the material through when that is wider, so the letter stays on flat material. + private static double Band(Bend bend, double clearance) => + bend.Radius is > 0 and var radius && bend.AngleRadians > 0 + ? System.Math.Max(clearance, radius * bend.AngleRadians / 2) + : clearance; + + // Distances from the bend's start to try, in order. + private static List Stations(Bend bend) + { + var length = bend.Length; + var stations = new List(); + var dashes = bend.GetEtchEntities(); + if (dashes.Count == 2) + { + foreach (var dash in dashes) + { + var middle = new Vector((dash.StartPoint.X + dash.EndPoint.X) / 2, (dash.StartPoint.Y + dash.EndPoint.Y) / 2); + stations.Add(bend.StartPoint.DistanceTo(middle)); + } + } + stations.Add(length / 2); + stations.Add(length / 4); + stations.Add(length * 3 / 4); + return stations; + } + + // A mark or break cut grown by the clearance. A curve is flattened outside itself and + // closed by its chord, so it never under-covers. + private static PathsD Grown(Entity entity, double clearance, double tolerance) + { + if (entity is Line line) + return LabelBoxFinder.Strip(line.StartPoint, line.EndPoint, clearance, tolerance); + + var shape = new Shape(); + shape.Entities.Add(entity); + var path = ClipperBridge.ToPath(ClipperBridge.Flatten(shape, tolerance, circumscribe: true), Vector.Zero); + return path.Count < 2 + ? new PathsD() + : Clipper.InflatePaths(new PathsD { path }, clearance, JoinType.Round, EndType.Joined, 2.0, + ClipperBridge.Precision, tolerance); + } + + // Even-odd over the region's paths: inside an outline and not inside a hole in it. + private static bool Inside(PathsD region, Vector point) + { + var at = new PointD(point.X, point.Y); + var count = 0; + foreach (var path in region) + { + if (Clipper.PointInPolygon(at, path) != PointInPolygonResult.IsOutside) + count++; + } + return count % 2 == 1; + } + } +} diff --git a/OpenNest.Core/Labels/LabelBoxFinder.cs b/OpenNest.Core/Labels/LabelBoxFinder.cs index 35dc0bf2..8895b4eb 100644 --- a/OpenNest.Core/Labels/LabelBoxFinder.cs +++ b/OpenNest.Core/Labels/LabelBoxFinder.cs @@ -13,8 +13,7 @@ namespace OpenNest.Labels public sealed class LabelBoxOptions { /// - /// Characters in the longest label: a four-digit part number and two circled bend group - /// letters ("1234 AB"), which take the room of eight. + /// Characters the label box is sized for: a part number of eight. /// public const int DefaultCharacters = 8; @@ -112,11 +111,6 @@ namespace OpenNest.Labels || !double.IsFinite(options.Height) || !(options.Clearance >= 0) || !double.IsFinite(options.Clearance)) throw new ArgumentException("The label size and clearance must be finite and positive.", nameof(options)); - var material = entities.Where(e => !ScribeLayerRepair.IsMarkLayer(e.Layer)).ForNesting(); - var shapes = ShapeBuilder.GetShapes(material).Where(s => s.IsClosed()).ToList(); - if (shapes.Count == 0) - return null; - var bendList = (bends ?? Enumerable.Empty()) .Where(b => b.Length > Tolerance.Epsilon) .ToList(); @@ -126,21 +120,13 @@ namespace OpenNest.Labels var tolerance = System.Math.Max(System.Math.Min(clearance, bendClearance) / 20, System.Math.Pow(10, -ClipperBridge.Precision)); - // The perimeter is flattened inside the true curve and cutouts outside it, so the - // region never reaches past the real material. - var region = ClipperBridge.ToRegion(ShapeProfile.FromShapes(shapes), tolerance, circumscribe: false); - var free = clearance > 0 - ? Clipper.InflatePaths(region, -(clearance + tolerance), JoinType.Round, EndType.Polygon, 2.0, - ClipperBridge.Precision, tolerance) - : region; + var free = Material(entities, clearance, tolerance, out var shapes); + if (free == null) + return null; var bands = new PathsD(); foreach (var bend in bendList) - { - bands.AddRange(Clipper.InflatePaths( - new PathsD { new PathD { new PointD(bend.StartPoint.X, bend.StartPoint.Y), new PointD(bend.EndPoint.X, bend.EndPoint.Y) } }, - bendClearance + tolerance, JoinType.Round, EndType.Round, 2.0, ClipperBridge.Precision, tolerance)); - } + bands.AddRange(Strip(bend.StartPoint, bend.EndPoint, bendClearance + tolerance, tolerance)); // A kept-out outline is flattened outside its curve so it never under-covers. foreach (var outline in keepOut ?? Enumerable.Empty>()) @@ -187,6 +173,31 @@ namespace OpenNest.Labels return best; } + // The part's material (marks and rapids are not material, a tabbed cutout's slug is) + // eroded by the clearance, or null without a closed outline. The perimeter is flattened + // inside the true curve and cutouts outside it, so the region never reaches past the + // real material. + internal static PathsD Material(IEnumerable entities, double clearance, double tolerance, + out List shapes) + { + var material = entities.Where(e => !ScribeLayerRepair.IsMarkLayer(e.Layer)).ForNesting(); + shapes = ShapeBuilder.GetShapes(material).Where(s => s.IsClosed()).ToList(); + if (shapes.Count == 0) + return null; + + var region = ClipperBridge.ToRegion(ShapeProfile.FromShapes(shapes), tolerance, circumscribe: false); + return clearance > 0 + ? Clipper.InflatePaths(region, -(clearance + tolerance), JoinType.Round, EndType.Polygon, 2.0, + ClipperBridge.Precision, tolerance) + : region; + } + + // A segment grown by halfWidth all round, ends rounded. + internal static PathsD Strip(Vector start, Vector end, double halfWidth, double tolerance) => + Clipper.InflatePaths( + new PathsD { new PathD { new PointD(start.X, start.Y), new PointD(end.X, end.Y) } }, + halfWidth, JoinType.Round, EndType.Round, 2.0, ClipperBridge.Precision, tolerance); + // The widest margin the label can have on every side, beyond the clearance already taken // out of the region, with the label upright in the region's frame; negative when it does // not fit at all. The label sits in the middle of the rectangle that gives it that margin. diff --git a/OpenNest.Core/Labels/PartLabels.cs b/OpenNest.Core/Labels/PartLabels.cs index 05159dab..015d779c 100644 --- a/OpenNest.Core/Labels/PartLabels.cs +++ b/OpenNest.Core/Labels/PartLabels.cs @@ -11,34 +11,23 @@ using OpenNest.Math; namespace OpenNest.Labels { /// - /// The text etched in a part's : its drawing name and the bend groups - /// its bends fall in for the way it is placed against the sheet grain. + /// The part number etched in a part's , and the bend group letters + /// etches beside its bend lines. /// /// /// A bend group is the bend line's direction relative to the grain (), /// 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. /// The grain changes springback, so bends sharing a letter take the same press brake angle - /// correction and can be formed together. 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. + /// correction and can be formed together. Like a dimension, the box only stores placement; + /// the text is made when the part is planned. /// public static class PartLabels { /// The smallest share of the box height the text may be shrunk to; a longer name is not etched. public const double MinimumHeightShare = 0.5; - /// - /// Separates the name from the bend groups in a label's text (1234 AB). Names never - /// hold one, so circles every letter after it. - /// - public const char GroupSeparator = ' '; - - // Shares of the character height: the gap from the name to the first circle, the gap - // between circles, and the height of a letter inside its circle (the circle's diameter is - // the character height). - private const double GroupGap = 0.375; - private const double CircleGap = 0.125; + // The height of a bend group letter inside its circle, as a share of the circle's diameter. private const double CircledLetterShare = 0.6; // Letter per bucket, indexed by BendGrain.Bucket: with the grain B, across it A, the rest C on. @@ -81,36 +70,16 @@ namespace OpenNest.Labels } /// - /// The label text for a drawing placed at : its name, then - /// and its bend groups when it has bends, for example - /// 1234 AB; etches each group letter in a circle. Characters the - /// stroke font lacks are dropped from the name. Empty when nothing is left to etch. - /// With it is the name alone, and with - /// it is empty. + /// The label text for a drawing: its name in capitals, with characters the stroke font + /// lacks, and spaces, dropped. Empty when nothing is left to etch or the mode is + /// . Bend groups are never part of it: each bend's letter + /// is etched beside its own line (). /// - public static string Text(Drawing drawing, double partRotation, double grainAngle, - PartLabelMode mode = PartLabelMode.PartNumberAndBendGroups) - { - if (drawing == null || mode == PartLabelMode.Off) - return string.Empty; + public static string Text(Drawing drawing, PartLabelMode mode = PartLabelMode.PartNumberAndBendGroups) => + drawing == null || mode == PartLabelMode.Off ? string.Empty : PreviewText(drawing.Name); - var groups = mode == PartLabelMode.PartNumberAndBendGroups - ? GroupLetters(drawing.Bends, partRotation, grainAngle) - : string.Empty; - return Join(EtchableName(drawing.Name), groups); - } - - /// - /// The label as the CAD Converter previews it before the part is placed: the full - /// text for the part unrotated on a sheet - /// whose grain runs along X. It is the longest the label gets for that placement, so a box - /// that fits it fits the part number alone; other placements may change the letters. - /// - public static string PreviewText(string name, IEnumerable bends) => - Join(EtchableName(name), GroupLetters(bends, 0, 0)); - - // The name in capitals with characters the stroke font lacks, and spaces, dropped. - private static string EtchableName(string name) + /// The label as the CAD Converter previews it: the name as etches it. + public static string PreviewText(string name) { var etchable = new StringBuilder(); foreach (var character in name ?? string.Empty) @@ -119,62 +88,35 @@ namespace OpenNest.Labels return etchable.ToString(); } - private static string Join(string name, string groups) => - groups.Length == 0 ? name : name + GroupSeparator + groups; - /// - /// The length of a label's at a character height of 1: the name, - /// then a gap and a circle per bend group, the circles one character height across. + /// A bend group letter in its circle: the circle across about + /// , the letter centered in it and reading along + /// (radians, counterclockwise). /// - public static double Measure(string text) + public static List CircledLetter(char letter, Vector center, double diameter, double rotation = 0) { - var (name, groups) = Split(text); - if (groups.Length == 0) - return StrokeFont.Measure(name); - return StrokeFont.Measure(name) + (name.Length == 0 ? 0 : GroupGap) - + groups.Length + (groups.Length - 1) * CircleGap; - } + var radius = diameter / 2; + var letterHeight = diameter * CircledLetterShare; + var strokes = new List(); - private static (string Name, string Groups) Split(string text) - { - text ??= string.Empty; - var separator = text.IndexOf(GroupSeparator); - return separator < 0 ? (text, string.Empty) : (text[..separator], text[(separator + 1)..]); - } + // A full circle as two half arcs, since a stroke's arc is less than a full turn. + var circle = new Stroke(new Vector(center.X + radius, center.Y)); + circle.Segments.Add(new StrokeSegment(new Vector(center.X - radius, center.Y), true, center, false)); + circle.Segments.Add(new StrokeSegment(new Vector(center.X + radius, center.Y), true, center, false)); + strokes.Add(circle); - // The text's strokes at height, lower left at the origin: the name, then each group letter - // centered in a circle the height of the text. - private static List TextStrokes(string text, double height) - { - var (name, groups) = Split(text); - var strokes = StrokeFont.Strokes(name, height); - if (groups.Length == 0) - return strokes; + var corner = new Vector(center.X - letterHeight * StrokeFont.GlyphWidth / 2, center.Y - letterHeight / 2); + foreach (var stroke in StrokeFont.Strokes(letter.ToString(), letterHeight)) + strokes.Add(stroke.Map(point => point + corner)); - var radius = height / 2; - var letterHeight = height * CircledLetterShare; - var left = name.Length == 0 ? 0 : (StrokeFont.Measure(name) + GroupGap) * height; - foreach (var letter in groups) - { - var center = new Vector(left + radius, radius); - // A full circle as two half arcs, since a stroke's arc is less than a full turn. - var circle = new Stroke(new Vector(center.X + radius, center.Y)); - circle.Segments.Add(new StrokeSegment(new Vector(center.X - radius, center.Y), true, center, false)); - circle.Segments.Add(new StrokeSegment(new Vector(center.X + radius, center.Y), true, center, false)); - strokes.Add(circle); - - var corner = new Vector(center.X - letterHeight * StrokeFont.GlyphWidth / 2, center.Y - letterHeight / 2); - foreach (var stroke in StrokeFont.Strokes(letter.ToString(), letterHeight)) - strokes.Add(stroke.Map(point => point + corner)); - - left += height * (1 + CircleGap); - } - return strokes; + return rotation == 0 + ? strokes + : strokes.ConvertAll(stroke => stroke.Map(point => center + (point - center).Rotate(rotation))); } /// /// Lays out in , in the box's own frame (the - /// drawing's source frame), each bend group letter in a circle: centered, reading along the box at its height, or shrunk to fit + /// drawing's source frame): centered, reading along the box at its height, or shrunk to fit /// its width. is false when the text had to shrink below /// of the box height, so Plan Cutting would not etch it; /// the shrunk strokes are still returned, for previewing. Null for an invalid box or no text. @@ -186,7 +128,7 @@ namespace OpenNest.Labels return null; var height = box.Height; - var width = Measure(text) * height; + var width = StrokeFont.Measure(text) * height; if (width > box.Width) { height *= box.Width / width; @@ -194,7 +136,7 @@ namespace OpenNest.Labels } fits = height >= box.Height * MinimumHeightShare - Tolerance.Epsilon; - return TextStrokes(text, height).ConvertAll(stroke => + return StrokeFont.Strokes(text, height).ConvertAll(stroke => stroke.Map(point => box.ToWorld(new Vector(point.X - width / 2, point.Y - height / 2)))); } @@ -209,14 +151,14 @@ namespace OpenNest.Labels /// less when the text is longer than the box: it is shrunk to fit, to /// of the box height at the least. /// - public static List Strokes(Drawing drawing, double partRotation, double grainAngle, + public static List Strokes(Drawing drawing, double partRotation, PartLabelMode mode = PartLabelMode.PartNumberAndBendGroups) { var box = drawing?.LabelBox; - if (box == null || !box.IsValid || !double.IsFinite(partRotation) || !double.IsFinite(grainAngle)) + if (box == null || !box.IsValid || !double.IsFinite(partRotation)) return null; - var text = Text(drawing, partRotation, grainAngle, mode); + var text = Text(drawing, mode); if (text.Length == 0) return null; @@ -243,10 +185,13 @@ namespace OpenNest.Labels /// drawing's) takes each move, and each arc's center, as a step from where the move starts, /// so the moves are written as steps from where the program stops. /// - public static bool AddTo(Program program, Drawing drawing, double partRotation, double grainAngle, - PartLabelMode mode = PartLabelMode.PartNumberAndBendGroups) + public static bool AddTo(Program program, Drawing drawing, double partRotation, + PartLabelMode mode = PartLabelMode.PartNumberAndBendGroups) => + Append(program, Strokes(drawing, partRotation, mode)); + + // Appends strokes (points in the program's frame) as scribe moves, each started by a rapid. + internal static bool Append(Program program, List strokes) { - var strokes = Strokes(drawing, partRotation, grainAngle, mode); if (program == null || strokes == null || strokes.Count == 0) return false; diff --git a/OpenNest.Engine/CuttingPlanning/CuttingPlanBatch.cs b/OpenNest.Engine/CuttingPlanning/CuttingPlanBatch.cs index 4b1135fe..cebbbf24 100644 --- a/OpenNest.Engine/CuttingPlanning/CuttingPlanBatch.cs +++ b/OpenNest.Engine/CuttingPlanning/CuttingPlanBatch.cs @@ -83,15 +83,16 @@ public sealed class CuttingPlanBatch /// and . The caller passes the operator's setting; the /// worker never reads it. /// + /// The nest's units, which size etched bend letters (docs/label-box.md). public static CuttingPlanBatch Capture(IReadOnlyList plates, CuttingParameters confirmedParameters, bool preservePartOrder, IReadOnlyList plateNumbers = null, CancellationToken token = default, - double budgetMultiplier = DefaultBudgetMultiplier) => - Capture(plates, confirmedParameters, preservePartOrder, plateNumbers, null, token, budgetMultiplier); + double budgetMultiplier = DefaultBudgetMultiplier, Units units = Units.Inches) => + Capture(plates, confirmedParameters, preservePartOrder, plateNumbers, null, token, budgetMultiplier, units); /// Overrides the new-order budget (tests); null gives . internal static CuttingPlanBatch Capture(IReadOnlyList plates, CuttingParameters confirmedParameters, bool preservePartOrder, IReadOnlyList plateNumbers, int? reorderBudget, CancellationToken token, - double budgetMultiplier = DefaultBudgetMultiplier) + double budgetMultiplier = DefaultBudgetMultiplier, Units units = Units.Inches) { ArgumentNullException.ThrowIfNull(plates); ArgumentNullException.ThrowIfNull(confirmedParameters); @@ -125,7 +126,7 @@ public sealed class CuttingPlanBatch // over the same owned geometry, programs and freshness record. var captured = CuttingPlanService.Capture(CuttingPlanRequest.ForPlate(plate, expansionBudget: budget, confirmedParameters: confirmedParameters, - preservePartOrder: preservePartOrder), token); + preservePartOrder: preservePartOrder, units: units), token); var keepOrder = preservePartOrder ? captured : captured.WithPreservedOrder(); var reorder = preservePartOrder ? null : reorderBudget is { } reorderLimit ? captured.WithSearchLimits(reorderLimit, captured.MaxEntries) : captured; @@ -133,7 +134,8 @@ public sealed class CuttingPlanBatch var fallback = reorder ?? keepOrder; if (fallback.Failure == CuttingPlanStatus.UnsupportedGeometry) fallback = CuttingPlanService.Capture(CuttingPlanRequest.ForPlate(plate, - confirmedParameters: confirmedParameters, preservePartOrder: preservePartOrder), token, bestEffort: true); + confirmedParameters: confirmedParameters, preservePartOrder: preservePartOrder, units: units), + token, bestEffort: true); entries[index] = new(plate, plateNumbers?[index] ?? index + 1, reorder, keepOrder, overlap, fallback); } return new(entries, owned); diff --git a/OpenNest.Engine/CuttingPlanning/CuttingPlanModels.cs b/OpenNest.Engine/CuttingPlanning/CuttingPlanModels.cs index eb484219..68a933d1 100644 --- a/OpenNest.Engine/CuttingPlanning/CuttingPlanModels.cs +++ b/OpenNest.Engine/CuttingPlanning/CuttingPlanModels.cs @@ -38,10 +38,10 @@ public sealed class CuttingPlanRequest /// public static CuttingPlanRequest ForPlate(Plate plate, Vector startPoint = default, int expansionBudget = 20000, CuttingParameters confirmedParameters = null, IEnumerable eligibleParts = null, - bool preservePartOrder = false, int maxEntries = 16) => + bool preservePartOrder = false, int maxEntries = 16, Units units = Units.Inches) => new(plate?.Parts, startPoint, expansionBudget, confirmedParameters, eligibleParts, preservePartOrder, maxEntries) - { Plate = plate, SupportBed = plate?.SupportBed, SupportQuadrant = plate?.Quadrant ?? 1 }; + { Plate = plate, SupportBed = plate?.SupportBed, SupportQuadrant = plate?.Quadrant ?? 1, Units = units }; /// The plate scope, or null for a detached part list that cannot be applied. public Plate Plate { get; private init; } @@ -55,6 +55,12 @@ public sealed class CuttingPlanRequest /// The sheet quadrant that places on the parts' coordinates. public int SupportQuadrant { get; init; } = 1; + + /// + /// The units the parts are drawn in (the nest's), which size the bend letters etched beside + /// bend lines (docs/label-box.md). + /// + public Units Units { get; init; } = Units.Inches; public CuttingParameters ConfirmedParameters { get; } public IReadOnlyList EligibleParts { get; } public bool PreservePartOrder { get; } diff --git a/OpenNest.Engine/CuttingPlanning/CuttingPlanService.cs b/OpenNest.Engine/CuttingPlanning/CuttingPlanService.cs index 47db9722..7aa05abb 100644 --- a/OpenNest.Engine/CuttingPlanning/CuttingPlanService.cs +++ b/OpenNest.Engine/CuttingPlanning/CuttingPlanService.cs @@ -71,6 +71,8 @@ public static class CuttingPlanService var identities = new HashSet(ReferenceEqualityComparer.Instance); // Every part's box, read once, for slug slices to keep clear of parts nested in a cutout. Box[] partBoxes = null; + // Where each drawing's bend letters go: the same for all its parts, so found once. + var bendSpots = new Dictionary>(ReferenceEqualityComparer.Instance); // The sheet every planned lead must stay on; none for a detached part list or a plate // with no usable size, which the pre-post plate edge check reports instead. var plateSize = request.Plate?.Size; @@ -165,8 +167,17 @@ public static class CuttingPlanService // 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?.LabelMode is { } labelMode && labelMode != PartLabelMode.Off) - PartLabels.AddTo(ownedClean, source.BaseDrawing, source.Rotation, - request.Plate?.GrainAngle ?? 0, labelMode); + { + var grain = request.Plate?.GrainAngle ?? 0; + PartLabels.AddTo(ownedClean, source.BaseDrawing, source.Rotation, labelMode); + // Each bend's own group letter beside its line, so the groups can be told apart. + if (labelMode == PartLabelMode.PartNumberAndBendGroups) + { + if (!bendSpots.TryGetValue(source.BaseDrawing, out var spots)) + bendSpots[source.BaseDrawing] = spots = BendLabels.Spots(source.BaseDrawing, request.Units); + BendLabels.AddTo(ownedClean, source.BaseDrawing, spots, source.Rotation, grain); + } + } // 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); diff --git a/OpenNest.Mcp/Tools/CuttingTools.cs b/OpenNest.Mcp/Tools/CuttingTools.cs index 6801bed8..6023940f 100644 --- a/OpenNest.Mcp/Tools/CuttingTools.cs +++ b/OpenNest.Mcp/Tools/CuttingTools.cs @@ -89,7 +89,7 @@ namespace OpenNest.Mcp.Tools var batch = CuttingPlanBatch.Capture(scope, parameters, keepPartOrder, scope.Select(p => all.FindIndex(candidate => ReferenceEquals(candidate, p))).ToArray(), - cancellationToken); + cancellationToken, units: _session.Nest?.Units ?? Units.Inches); var proposal = batch.Plan(token: cancellationToken); cancellationToken.ThrowIfCancellationRequested(); diff --git a/OpenNest.Tests/Labels/BendLabelTests.cs b/OpenNest.Tests/Labels/BendLabelTests.cs new file mode 100644 index 00000000..561671a0 --- /dev/null +++ b/OpenNest.Tests/Labels/BendLabelTests.cs @@ -0,0 +1,235 @@ +using OpenNest.Bending; +using OpenNest.CNC; +using OpenNest.Geometry; +using OpenNest.Labels; +using OpenNest.Tests.CuttingPlanning; + +namespace OpenNest.Tests.Labels; + +/// +/// The bend group letter etched beside each bend line (docs/label-box.md): where it goes, what +/// it keeps clear of and which letter it is for the part's rotation against the grain. +/// +public class BendLabelTests +{ + private const double Quarter = System.Math.PI / 2; + + // Inch drawings: an eighth inch clearance, and the erosion tolerance a twentieth of that. + private const double Clearance = 0.125; + private const double Tolerance = Clearance / 20; + + private static List Rectangle(double left, double bottom, double right, double top) => + [ + new Line(left, bottom, right, bottom), new Line(right, bottom, right, top), + new Line(right, top, left, top), new Line(left, top, left, bottom), + ]; + + private static Bend Bend(double x1, double y1, double x2, double y2, BendDirection direction = BendDirection.Up) => + new() { StartPoint = new Vector(x1, y1), EndPoint = new Vector(x2, y2), Direction = direction }; + + private static LabelBox Box(double x, double y, double height = 0.5) => new(new Vector(x, y), 2, height, 0); + + private static double DistanceToLine(Vector point, Bend bend) + { + var dx = bend.EndPoint.X - bend.StartPoint.X; + var dy = bend.EndPoint.Y - bend.StartPoint.Y; + return System.Math.Abs(dx * (point.Y - bend.StartPoint.Y) - dy * (point.X - bend.StartPoint.X)) / bend.Length; + } + + [Fact] + public void UpBend_GetsItsLetterBesideAnEtchDash_JustPastTheClearance() + { + var bend = Bend(5, 0, 5, 5); + + var spot = Assert.Single(BendLabels.Place(Rectangle(0, 0, 10, 5), [bend], Box(2, 2.5))); + + Assert.Equal(0, spot.Bend); + Assert.Equal(0.5, spot.Diameter, 9); + // The middle of the first inch-long dash, on the left of a line running up. + Assert.Equal(0.5, spot.Center.Y, 6); + Assert.Equal(5 - (Clearance + 0.25 + 2 * Tolerance), spot.Center.X, 6); + } + + [Fact] + public void DownBend_HasNoDashes_SoItsLetterSitsAtTheMiddle() + { + var bend = Bend(5, 0, 5, 5, BendDirection.Down); + + var spot = Assert.Single(BendLabels.Place(Rectangle(0, 0, 10, 5), [bend], Box(2, 4))); + + Assert.Equal(2.5, spot.Center.Y, 6); + } + + [Fact] + public void BendRadius_PushesTheLetterPastTheRolledBand() + { + var bend = Bend(5, 0, 5, 5); + bend.Radius = 0.5; + bend.Angle = 90; + + var spot = Assert.Single(BendLabels.Place(Rectangle(0, 0, 10, 5), [bend], Box(2, 2.5))); + + // Half the arc a 90 degree bend rolls at that radius, then the circle's own radius. + var band = 0.5 * Quarter / 2; + Assert.True(band > Clearance); + Assert.Equal(band + 0.25 + 2 * Tolerance, DistanceToLine(spot.Center, bend), 6); + } + + [Fact] + public void NoRoomOnTheLeft_UsesTheRight() + { + // The bend runs up a quarter inch from the left edge: only its right side has material. + var bend = Bend(0.25, 0, 0.25, 5); + + var spot = Assert.Single(BendLabels.Place(Rectangle(0, 0, 10, 5), [bend], Box(6, 2.5))); + + Assert.True(spot.Center.X > 0.25); + } + + [Fact] + public void Hole_LabelBoxAndMarks_AreKeptClear() + { + var bend = Bend(5, 0, 5, 5); + var free = Assert.Single(BendLabels.Place(Rectangle(0, 0, 10, 5), [bend], Box(2, 2.5))).Center; + + // A hole over the first spot. + var holed = Rectangle(0, 0, 10, 5); + holed.Add(new Circle(free.X, free.Y, 0.2)); + var pastHole = Assert.Single(BendLabels.Place(holed, [bend], Box(2, 2.5))); + Assert.True(pastHole.Center.DistanceTo(free) >= 0.2 + Clearance + 0.25 - 1e-3); + + // The label box over it. + var box = new LabelBox(free, 2, 0.5, 0); + var pastBox = Assert.Single(BendLabels.Place(Rectangle(0, 0, 10, 5), [bend], box)); + Assert.False(box.Contains(pastBox.Center)); + + // An etched mark through it. + var marked = Rectangle(0, 0, 10, 5); + marked.Add(new Line(free.X - 1, free.Y, free.X, free.Y) { Layer = OpenNest.Bending.Bend.EtchLayer }); + var pastMark = Assert.Single(BendLabels.Place(marked, [bend], Box(2, 2.5))); + Assert.True(pastMark.Center.DistanceTo(free) > 0.25); + } + + [Fact] + public void NarrowFlange_ShrinksTheLetter_AndNoRoomGetsNone() + { + // 0.7 either side of the bend holds a three eighths circle but not a half inch one. + var shrunk = Assert.Single(BendLabels.Place(Rectangle(0, 0, 1.4, 5), [Bend(0.7, 0, 0.7, 5)], Box(20, 20))); + Assert.Equal(0.375, shrunk.Diameter, 9); + + // Half an inch either side holds none, not even the smallest. + Assert.Empty(BendLabels.Place(Rectangle(0, 0, 1, 5), [Bend(0.5, 0, 0.5, 5)], Box(20, 20))); + } + + [Fact] + public void EachBendGetsItsOwnSpot_ClearOfTheOthers_AndIsDeterministic() + { + // Two bends meeting at a corner, as on a part bent two ways. + var bends = new List { Bend(2, 2, 6, 2), Bend(2, 2, 2, 6) }; + var entities = Rectangle(0, 0, 12, 12); + + var spots = BendLabels.Place(entities, bends, Box(8, 8)); + + Assert.Equal([0, 1], spots.Select(s => s.Bend)); + Assert.True(spots[0].Center.DistanceTo(spots[1].Center) + >= spots[0].Diameter / 2 + spots[1].Diameter / 2 + Clearance - 1e-9); + // Each circle stays off both bend lines. + foreach (var spot in spots) + Assert.All(bends, bend => Assert.True(DistanceToLine(spot.Center, bend) >= Clearance + spot.Diameter / 2 - 1e-9 + || spot.Center.X > 6 || spot.Center.Y > 6)); + Assert.Equal(spots, BendLabels.Place(entities, bends, Box(8, 8))); + } + + [Fact] + public void NoLabelBox_StillPlacesTheLetter_AndMillimeterDrawingsGetMillimeterSizes() + { + var spot = Assert.Single(BendLabels.Place(Rectangle(0, 0, 10, 5), [Bend(5, 0, 5, 5)], null)); + Assert.Equal(0.5, spot.Diameter, 9); + + var metric = Assert.Single(BendLabels.Place(Rectangle(0, 0, 250, 125), [Bend(125, 0, 125, 125, BendDirection.Down)], + null, Units.Millimeters)); + Assert.Equal(12, metric.Diameter, 9); + // 3 mm clear of the line, then the circle's radius. + Assert.InRange(DistanceToLine(metric.Center, Bend(125, 0, 125, 125)), 9, 9.5); + + var unboxed = new Drawing("1234", LeadPathValidationTests.Rectangle(0, 0, 12, 12)); + unboxed.Bends.Add(Bend(2, 2, 6, 2)); + var spots = BendLabels.Spots(unboxed); + Assert.Single(spots); + Assert.NotEmpty(BendLabels.Strokes(unboxed, spots, 0, 0)); + } + + [Fact] + public void NothingToPlace_IsEmpty() + { + var bend = Bend(5, 0, 5, 5); + Assert.Empty(BendLabels.Place(Rectangle(0, 0, 10, 5), [], Box(2, 2.5))); + Assert.Empty(BendLabels.Place([new Line(0, 0, 10, 0)], [bend], Box(2, 2.5))); + Assert.Empty(BendLabels.Place(Rectangle(0, 0, 10, 5), [null!, Bend(1, 1, 1, 1)], Box(2, 2.5))); + Assert.Empty(BendLabels.Spots(null)); + } + + [Fact] + public void Layout_CirclesEachBendsOwnLetter_ForThePartsRotationAgainstTheGrain() + { + // One bend with the grain (B) and one across it (A); a quarter turn swaps them. + var bends = new List { Bend(2, 2, 6, 2), Bend(2, 2, 2, 6) }; + var spots = BendLabels.Place(Rectangle(0, 0, 12, 12), bends, Box(8, 8)); + + var upright = BendLabels.Layout(spots, bends, 0, 0); + var turned = BendLabels.Layout(spots, bends, Quarter, 0); + + List Points(IEnumerable strokes) => strokes.SelectMany(s => s.Points()).ToList(); + // Each letter reads along its own bend line: level beside the first, turned a quarter + // beside the second. + var second = LabelBox.ReadableRotation(bends[1].LineAngle); + var expected = PartLabels.CircledLetter('B', spots[0].Center, spots[0].Diameter) + .Concat(PartLabels.CircledLetter('A', spots[1].Center, spots[1].Diameter, second)); + Assert.Equal(Points(expected), Points(upright)); + var swapped = PartLabels.CircledLetter('A', spots[0].Center, spots[0].Diameter) + .Concat(PartLabels.CircledLetter('B', spots[1].Center, spots[1].Diameter, second)); + Assert.Equal(Points(swapped), Points(turned)); + + // Every stroke stays inside its circle, however the bend runs. + var slanted = new List { Bend(2, 2, 6, 4) }; + var slantedSpots = BendLabels.Place(Rectangle(0, 0, 12, 12), slanted, null); + Assert.NotEmpty(slantedSpots); + foreach (var stroke in BendLabels.Layout(slantedSpots, slanted, 0, 0)) + Assert.Contains(slantedSpots, spot => stroke.Points().All(p => p.DistanceTo(spot.Center) <= spot.Diameter / 2 + 1e-9)); + } + + [Fact] + public void DrawingSpots_FollowTheSourceOffset_AndStrokesTurnWithThePart() + { + Drawing Panel(Vector offset) + { + var drawing = new Drawing("1234", LeadPathValidationTests.Rectangle(0, 0, 12, 12)) + { + LabelBox = new LabelBox(new Vector(8, 8) + offset, 3.5, 0.5, 0), + }; + drawing.Source.Offset = offset; + drawing.Bends.Add(Bend(2 + offset.X, 2 + offset.Y, 6 + offset.X, 2 + offset.Y)); + return drawing; + } + + // The box and bend are stored in the source frame; the program has the offset taken off. + var plain = Assert.Single(BendLabels.Spots(Panel(Vector.Zero))); + var moved = Assert.Single(BendLabels.Spots(Panel(new Vector(3, 1)))); + Assert.Equal(plain.Center.X, moved.Center.X, 6); + Assert.Equal(plain.Center.Y, moved.Center.Y, 6); + + var drawing = Panel(Vector.Zero); + var spots = BendLabels.Spots(drawing); + var turned = BendLabels.Strokes(drawing, spots, Quarter, 0); + var center = plain.Center.Rotate(Quarter); + Assert.NotEmpty(turned); + Assert.All(turned, stroke => Assert.All(stroke.Points(), + p => Assert.True(p.DistanceTo(center) <= plain.Diameter / 2 + 1e-9))); + + var program = (Program)drawing.Program.Clone(); + var before = program.Codes.Count; + Assert.True(BendLabels.AddTo(program, drawing, spots, 0, 0)); + Assert.All(program.Codes.Skip(before).OfType(), move => Assert.Equal(LayerType.Scribe, move.Layer)); + Assert.False(BendLabels.AddTo(program, drawing, [], 0, 0)); + } +} diff --git a/OpenNest.Tests/Labels/LabelPreviewTests.cs b/OpenNest.Tests/Labels/LabelPreviewTests.cs index dfefc79b..8f4acc07 100644 --- a/OpenNest.Tests/Labels/LabelPreviewTests.cs +++ b/OpenNest.Tests/Labels/LabelPreviewTests.cs @@ -1,4 +1,3 @@ -using OpenNest.Bending; using OpenNest.Geometry; using OpenNest.Labels; @@ -7,17 +6,11 @@ namespace OpenNest.Tests.Labels; public class LabelPreviewTests { [Fact] - public void PreviewText_IsTheFullLabelForTheUnrotatedPart() + public void PreviewText_IsTheNameAsItIsEtched() { - var bends = new List - { - new() { StartPoint = new Vector(1, 0), EndPoint = new Vector(1, 1) }, - new() { StartPoint = new Vector(0, 2), EndPoint = new Vector(3, 2) }, - }; - - Assert.Equal("4980A01PT103 AB", PartLabels.PreviewText("4980 A01 pt103", bends)); - Assert.Equal("1234", PartLabels.PreviewText("1234", null)); - Assert.Equal("", PartLabels.PreviewText(null, null)); + Assert.Equal("4980A01PT103", PartLabels.PreviewText("4980 A01 pt103")); + Assert.Equal("1234", PartLabels.PreviewText("1234")); + Assert.Equal("", PartLabels.PreviewText(null)); } [Fact] @@ -55,9 +48,9 @@ public class LabelPreviewTests { var drawing = new Drawing("12345") { LabelBox = new LabelBox(new Vector(1, 1), 0.3, 0.25, 0) }; - PartLabels.Layout(drawing.LabelBox, PartLabels.Text(drawing, 0, 0), out var fits); + PartLabels.Layout(drawing.LabelBox, PartLabels.Text(drawing), out var fits); Assert.False(fits); - Assert.Null(PartLabels.Strokes(drawing, 0, 0)); + Assert.Null(PartLabels.Strokes(drawing, 0)); } } diff --git a/OpenNest.Tests/Labels/PartLabelTests.cs b/OpenNest.Tests/Labels/PartLabelTests.cs index 32fbe49c..9355a61e 100644 --- a/OpenNest.Tests/Labels/PartLabelTests.cs +++ b/OpenNest.Tests/Labels/PartLabelTests.cs @@ -101,7 +101,7 @@ public class PartLabelTests { Assert.Equal(LabelBoxOptions.CharacterAdvance, StrokeFont.Advance); - var width = PartLabels.Measure("1234 AB") * 0.25; + var width = StrokeFont.Measure("12345678") * 0.25; var options = LabelBoxOptions.ForText(LabelBoxOptions.DefaultCharacters, 0.25, 0.125); Assert.True(width <= options.Width + 1e-9); @@ -164,72 +164,45 @@ public class PartLabelTests Assert.Equal(string.Empty, PartLabels.GroupLetters([], 0, 0)); } - // ---- circled groups ---- + // ---- circled letter ---- [Fact] - public void Layout_CirclesEachGroupLetter_ClearOfTheName() + public void CircledLetter_IsACircleWithTheLetterInside_HoweverItIsTurned() { - var box = new LabelBox(new Vector(0, 0), 10, 1, 0); - - var plain = PartLabels.Layout(box, "12", out _)!; - var circled = PartLabels.Layout(box, "12 AB", out var fits)!; - - Assert.True(fits); - // Each group adds a circle (two half arcs) and its letter's strokes. - var letters = StrokeFont.Strokes("A", 1).Count + StrokeFont.Strokes("B", 1).Count; - Assert.Equal(plain.Count + 2 + letters, circled.Count); - - var circles = circled.Where(s => s.Segments.Count == 2 && s.Segments.All(g => g.IsArc)).ToList(); - Assert.Equal(2, circles.Count); - var nameRight = circled.Take(StrokeFont.Strokes("12", 1).Count).SelectMany(s => s.Points()).Max(p => p.X); - foreach (var circle in circles) + var center = new Vector(3, 2); + foreach (var rotation in new[] { 0, Quarter / 3, Quarter }) { - var center = circle.Segments[0].Center; - Assert.Equal(0.5, center.DistanceTo(circle.Start), 9); - Assert.Equal(0, center.Y, 9); - Assert.True(center.X - 0.5 > nameRight, "A circle overlaps the name."); - } + var strokes = PartLabels.CircledLetter('A', center, 1, rotation); - // Every letter sits inside its circle. - var first = circles[0].Segments[0].Center; - var second = circles[1].Segments[0].Center; - foreach (var point in circled.Except(circles).SelectMany(s => s.Points()).Where(p => p.X > nameRight)) - { - var center = System.Math.Abs(point.X - first.X) < System.Math.Abs(point.X - second.X) ? first : second; - Assert.True(center.DistanceTo(point) < 0.5, $"{point} is outside its circle."); + // A circle (two half arcs) and the letter's strokes. + Assert.Equal(1 + StrokeFont.Strokes("A", 1).Count, strokes.Count); + var circle = Assert.Single(strokes, s => s.Segments.Count == 2 && s.Segments.All(g => g.IsArc)); + Assert.Equal(0.5, circle.Segments[0].Center.DistanceTo(circle.Start), 9); + Assert.Equal(center.X, circle.Segments[0].Center.X, 9); + Assert.Equal(center.Y, circle.Segments[0].Center.Y, 9); + foreach (var point in strokes.Where(s => s != circle).SelectMany(s => s.Points())) + Assert.True(center.DistanceTo(point) < 0.5, $"{point} is outside its circle."); } } - [Fact] - public void Measure_IsTheNameThenAGapAndACirclePerGroup() - { - Assert.Equal(StrokeFont.Measure("1234"), PartLabels.Measure("1234"), 9); - Assert.Equal(StrokeFont.Measure("1234") + 0.375 + 2 + 0.125, PartLabels.Measure("1234 AB"), 9); - Assert.Equal(1, PartLabels.Measure(" A"), 9); - Assert.True(PartLabels.Measure("1234 AB") <= LabelBoxOptions.DefaultCharacters * LabelBoxOptions.CharacterAdvance + 1e-9); - } - // ---- text ---- [Fact] - public void Text_IsTheNameThenTheBendGroups() + public void Text_IsTheNameAlone_EvenWithBends() { - 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)); + // The groups are etched beside the bend lines, never in the label box. + Assert.Equal("1234", PartLabels.Text(Panel("1234", BendAt(0), BendAt(Quarter)))); + Assert.Equal("1234", PartLabels.Text(Panel("1234"))); } [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)); + Assert.Equal("N26-2GT", PartLabels.Text(Panel("n26-2gt"))); + Assert.Equal("BRACKETA", PartLabels.Text(Panel("bracket (a)"))); + Assert.Equal(string.Empty, PartLabels.Text(Panel("()"))); + Assert.Equal(string.Empty, PartLabels.Text(Panel("()", BendAt(Quarter)))); + Assert.Equal(string.Empty, PartLabels.Text(null)); } // ---- strokes ---- @@ -237,13 +210,12 @@ public class PartLabelTests [Fact] public void Strokes_AreCenteredInTheBoxAtTheBoxHeight() { - // H fills its whole character cell and the group circles are the text's height, so the - // strokes' bounds are the text's. - var drawing = Panel("HH", BendAt(0), BendAt(Quarter)); + // H fills its whole character cell, so the strokes' bounds are the text's. Bends add nothing. + var drawing = Panel("HHH", BendAt(0), BendAt(Quarter)); - var bounds = BoundsOf(PartLabels.Strokes(drawing, 0, 0)); + var bounds = BoundsOf(PartLabels.Strokes(drawing, 0)); - var width = PartLabels.Measure("HH AB") * 0.5; + var width = StrokeFont.Measure("HHH") * 0.5; Assert.Equal(0.5, bounds.Height, 9); Assert.Equal(width, bounds.Width, 9); Assert.Equal(6, bounds.Left + bounds.Width / 2, 9); @@ -256,12 +228,12 @@ public class PartLabelTests var drawing = Panel("HH"); drawing.Source.Offset = new Vector(1, 2); - var upright = BoundsOf(PartLabels.Strokes(drawing, 0, 0)); + var upright = BoundsOf(PartLabels.Strokes(drawing, 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)); + var turned = BoundsOf(PartLabels.Strokes(drawing, Quarter)); 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); @@ -271,12 +243,12 @@ public class PartLabelTests [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)); + // 3.5 fits nine characters at the full 0.5 height; this name is twelve. + var shrunk = BoundsOf(PartLabels.Strokes(Panel("123456789012"), 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)); + Assert.Null(PartLabels.Strokes(Panel("1234567890123456789012345"), 0)); } [Fact] @@ -284,15 +256,15 @@ public class PartLabelTests { var none = Panel("1234"); none.LabelBox = null; - Assert.Null(PartLabels.Strokes(none, 0, 0)); + Assert.Null(PartLabels.Strokes(none, 0)); var broken = Panel("1234"); broken.LabelBox.Width = 0; - Assert.Null(PartLabels.Strokes(broken, 0, 0)); + Assert.Null(PartLabels.Strokes(broken, 0)); - Assert.Null(PartLabels.Strokes(Panel("()"), 0, 0)); - Assert.Null(PartLabels.Strokes(Panel("1234"), double.NaN, 0)); - Assert.Null(PartLabels.Strokes(null, 0, 0)); + Assert.Null(PartLabels.Strokes(Panel("()"), 0)); + Assert.Null(PartLabels.Strokes(Panel("1234"), double.NaN)); + Assert.Null(PartLabels.Strokes(null, 0)); } [Fact] @@ -302,7 +274,7 @@ public class PartLabelTests var program = (Program)drawing.Program.Clone(); var before = program.Codes.Count; - Assert.True(PartLabels.AddTo(program, drawing, 0, 0)); + Assert.True(PartLabels.AddTo(program, drawing, 0)); var added = program.Codes.Skip(before).ToList(); Assert.IsType(added[0]); @@ -313,7 +285,7 @@ public class PartLabelTests var untouched = (Program)drawing.Program.Clone(); drawing.LabelBox = null; - Assert.False(PartLabels.AddTo(untouched, drawing, 0, 0)); + Assert.False(PartLabels.AddTo(untouched, drawing, 0)); Assert.Equal(before, untouched.Codes.Count); } @@ -328,8 +300,8 @@ public class PartLabelTests incremental.Mode = Mode.Incremental; var before = absolute.Codes.Count; - Assert.True(PartLabels.AddTo(absolute, drawing, Quarter, 0)); - Assert.True(PartLabels.AddTo(incremental, drawing, Quarter, 0)); + Assert.True(PartLabels.AddTo(absolute, drawing, Quarter)); + Assert.True(PartLabels.AddTo(incremental, drawing, Quarter)); incremental.Mode = Mode.Absolute; var expected = absolute.Codes.Skip(before).OfType().Select(m => m.EndPoint) @@ -389,13 +361,39 @@ public class PartLabelTests 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) + bool InBox(ExecutionMotion mark) => + System.Math.Abs(mark.End.X - 7) <= 1.75 + 1e-6 && System.Math.Abs(mark.End.Y - 7) <= 0.25 + 1e-6; + Assert.True(marks.Count(InBox) > 5); + + // Every other mark is a bend's own letter: a half inch circle beside one of the two + // bend lines, which leave (3, 3) on the sheet along X and along Y. + var letters = marks.Where(mark => !InBox(mark)).ToList(); + Assert.NotEmpty(letters); + Assert.All(letters, mark => + { + var alongX = mark.End.X is >= 3 and <= 7 ? System.Math.Abs(mark.End.Y - 3) : double.MaxValue; + var alongY = mark.End.Y is >= 3 and <= 7 ? System.Math.Abs(mark.End.X - 3) : double.MaxValue; + Assert.InRange(System.Math.Min(alongX, alongY), 0.125 - 1e-6, 0.125 + 0.5 + 0.02); + }); + Assert.Contains(letters, mark => mark.End.Y > 3.6); + Assert.Contains(letters, mark => mark.End.X > 3.6); + } + + [Fact] + public void PlanCutting_PartNumberMode_EtchesNoBendLetters() + { + var (plate, _) = PlateOf(Panel("1234", BendAt(0), BendAt(Quarter)), Parameters(PartLabelMode.PartNumber)); + + var result = CuttingPlanService.Plan(CuttingPlanRequest.ForPlate(plate, Vector.Zero, + confirmedParameters: Parameters(PartLabelMode.PartNumber))); + + Assert.Equal(CuttingPlanStatus.Ready, result.Status); + Assert.All(ScribeOf(result), mark => { 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] @@ -409,13 +407,35 @@ public class PartLabelTests var unboxed = Panel("1234", BendAt(0)); unboxed.LabelBox = null; - var (onPlate, _) = PlateOf(unboxed, Parameters(true)); + var (onPlate, _) = PlateOf(unboxed, Parameters(PartLabelMode.PartNumber)); var on = CuttingPlanService.Plan(CuttingPlanRequest.ForPlate(onPlate, Vector.Zero, - confirmedParameters: Parameters(true))); + confirmedParameters: Parameters(PartLabelMode.PartNumber))); Assert.Equal(CuttingPlanStatus.Ready, on.Status); Assert.Empty(ScribeOf(on)); } + // The label box is only for the part number: a bend's letter needs none. + [Fact] + public void PlanCutting_WithoutABox_StillEtchesEachBendsLetterBesideItsLine() + { + var unboxed = Panel("1234", BendAt(0)); + unboxed.LabelBox = null; + var (plate, _) = PlateOf(unboxed, Parameters(true)); + + var result = CuttingPlanService.Plan(CuttingPlanRequest.ForPlate(plate, Vector.Zero, + confirmedParameters: Parameters(true))); + + Assert.Equal(CuttingPlanStatus.Ready, result.Status); + var marks = ScribeOf(result); + Assert.NotEmpty(marks); + // A half inch circle an eighth inch off the bend, which runs from (3, 3) along X on the sheet. + Assert.All(marks, mark => + { + Assert.InRange(mark.End.X, 3, 7); + Assert.InRange(System.Math.Abs(mark.End.Y - 3), 0.125 - 1e-6, 0.125 + 0.5 + 0.02); + }); + } + [Fact] public void PlanCutting_LabelsTheGroupsForThePartsRotationOnTheSheet() { @@ -429,7 +449,7 @@ public class PartLabelTests Assert.Equal(CuttingPlanStatus.Ready, a.Status); Assert.Equal(CuttingPlanStatus.Ready, b.Status); - // Circled A and circled B differ in their letter's glyph, so their strokes differ in count. + // The bend's circled A and circled B differ in their glyph, so their strokes differ in count. Assert.NotEqual(ScribeOf(a).Count, ScribeOf(b).Count); } @@ -474,7 +494,7 @@ public class PartLabelTests [Fact] public void PlanCutting_PartNumberMode_EtchesTheNumberWithoutTheGroups() { - // "7" alone is one glyph; "7 A" adds a circle and a letter, so it has more strokes. + // "7" alone is one glyph; the bend's circled letter beside its line adds more strokes. var drawing = Panel("7", BendAt(Quarter)); var strokesOf = (PartLabelMode mode) => { @@ -496,16 +516,16 @@ public class PartLabelTests // ---- the option ---- [Fact] - public void Text_PartNumberMode_OmitsTheGroups_AndOffIsEmpty() + public void Text_IsTheSameInBothModes_AndOffIsEmpty() { var drawing = Panel("1234", BendAt(0), BendAt(Quarter)); - Assert.Equal("1234", PartLabels.Text(drawing, 0, 0, PartLabelMode.PartNumber)); - Assert.Equal("1234 AB", PartLabels.Text(drawing, 0, 0, PartLabelMode.PartNumberAndBendGroups)); - Assert.Equal("1234 AB", PartLabels.Text(drawing, 0, 0)); - Assert.Equal(string.Empty, PartLabels.Text(drawing, 0, 0, PartLabelMode.Off)); + Assert.Equal("1234", PartLabels.Text(drawing, PartLabelMode.PartNumber)); + Assert.Equal("1234", PartLabels.Text(drawing, PartLabelMode.PartNumberAndBendGroups)); + Assert.Equal("1234", PartLabels.Text(drawing)); + Assert.Equal(string.Empty, PartLabels.Text(drawing, PartLabelMode.Off)); // A name the font cannot draw is nothing to etch in number mode, even with bends. - Assert.Equal(string.Empty, PartLabels.Text(Panel("()", BendAt(Quarter)), 0, 0, PartLabelMode.PartNumber)); + Assert.Equal(string.Empty, PartLabels.Text(Panel("()", BendAt(Quarter)), PartLabelMode.PartNumber)); } [Fact] @@ -515,9 +535,9 @@ public class PartLabelTests var program = (Program)drawing.Program.Clone(); var before = program.Codes.Count; - Assert.False(PartLabels.AddTo(program, drawing, 0, 0, PartLabelMode.Off)); + Assert.False(PartLabels.AddTo(program, drawing, 0, PartLabelMode.Off)); Assert.Equal(before, program.Codes.Count); - Assert.True(PartLabels.AddTo(program, drawing, 0, 0, PartLabelMode.PartNumber)); + Assert.True(PartLabels.AddTo(program, drawing, 0, PartLabelMode.PartNumber)); } [Fact] diff --git a/OpenNest.WinForms.Tests/Forms/CadConverterLabelBoxTests.cs b/OpenNest.WinForms.Tests/Forms/CadConverterLabelBoxTests.cs index 81eb37b9..78c1ab36 100644 --- a/OpenNest.WinForms.Tests/Forms/CadConverterLabelBoxTests.cs +++ b/OpenNest.WinForms.Tests/Forms/CadConverterLabelBoxTests.cs @@ -235,6 +235,35 @@ public class CadConverterLabelBoxTests form.Close(); }); + [Fact] + public void EachBendsLetterIsPreviewedBesideItsLine_WithOrWithoutABox_ClearOfTheBox() => ArchUnitsTests.RunSta(() => + { + using var form = new LabelTestForm(); + Show(form); + var bend = new Bend { StartPoint = new Vector(5, 0), EndPoint = new Vector(5, 6), Direction = BendDirection.Up }; + form.LoadDrawings([Part(10, 6, [bend])]); + var view = Field(form, "entityView1"); + var item = Field(form, "fileList").SelectedItem!; + + // The letter needs no label box: a half inch circle within an inch of the bend line. + Assert.Null(item.LabelBox); + var points = view.BendLabelPreview!().SelectMany(stroke => stroke.Points()).ToList(); + Assert.NotEmpty(points); + Assert.All(points, point => Assert.InRange(System.Math.Abs(point.X - 5), 0, 1)); + Assert.Equal(0.5, points.Max(p => p.Y) - points.Min(p => p.Y), 2); + var before = points[0]; + + // A label box over the letter moves it clear; painting works. + item.LabelBox = new LabelBox(before, 2, 0.5, 0); + Invoke(form, "RefreshLabelBox", item); + var moved = view.BendLabelPreview!().SelectMany(stroke => stroke.Points()).ToList(); + Assert.NotEmpty(moved); + Assert.All(moved, point => Assert.False(item.LabelBox.Contains(point))); + using var bitmap = new System.Drawing.Bitmap(view.Width, view.Height); + view.DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, view.Width, view.Height)); + form.Close(); + }); + private static Drawing Part(double width, double height, List? bends = null) { var entities = new List diff --git a/OpenNest/Controls/CuttingPanel.cs b/OpenNest/Controls/CuttingPanel.cs index 45d2b2a8..cb4096d8 100644 --- a/OpenNest/Controls/CuttingPanel.cs +++ b/OpenNest/Controls/CuttingPanel.cs @@ -280,7 +280,7 @@ namespace OpenNest.Controls column.Controls.Add(chkSliceSlugs); chkSliceSlugs.CheckedChanged += (s, e) => OnParametersChanged(); - // Marks: the part number and bend groups etched in each drawing's label box. + // Marks: the part number etched in each drawing's label box, and bend group letters. AddSection("Marks"); var marksGrid = ControlFactory.SettingsGrid(0); @@ -295,8 +295,9 @@ namespace OpenNest.Controls AddRow(marksGrid, "Etch part label:", cboLabelMode, 0); toolTip.SetToolTip(cboLabelMode, "Plan Cutting etches each part's number in the label box set in the CAD Converter, " - + "alone or with its bend groups (A across the grain, B with it, then C and on). " - + "Parts with no label box get none."); + + "alone or with each bend's group letter beside its bend line " + + "(A across the grain, B with it, then C and on). " + + "Parts with no label box get no part number."); column.Controls.Add(marksGrid); cboLabelMode.SelectedIndexChanged += (s, e) => OnParametersChanged(); diff --git a/OpenNest/Controls/EntityView.LabelBox.cs b/OpenNest/Controls/EntityView.LabelBox.cs index 0ec58470..ffe53269 100644 --- a/OpenNest/Controls/EntityView.LabelBox.cs +++ b/OpenNest/Controls/EntityView.LabelBox.cs @@ -36,6 +36,12 @@ namespace OpenNest.Controls /// public Func LabelPreviewText { get; set; } + /// + /// The bend group letters previewed beside the bend lines, read at each paint, with or + /// without a ; null previews none. + /// + public Func> BendLabelPreview { get; set; } + /// The label box was moved, resized or turned; the argument is its new placement. public event EventHandler LabelBoxChanged; @@ -138,6 +144,26 @@ namespace OpenNest.Controls _ => Cursors.SizeNWSE, }; + // Each bend's own group letter, where Plan Cutting would etch it beside the line. + private void DrawBendLabels(Graphics g) + { + if (BendLabelPreview?.Invoke() is not { Count: > 0 } letters) + return; + + using var pen = new Pen(LabelBoxColor, 1.5f) + { + StartCap = LineCap.Round, + EndCap = LineCap.Round, + LineJoin = LineJoin.Round, + }; + foreach (var stroke in letters) + { + var path = stroke.Points().Select(PointWorldToGraph).ToArray(); + if (path.Length > 1) + g.DrawLines(pen, path); + } + } + private void DrawLabelBox(Graphics g) { if (LabelBox is not { IsValid: true } box) diff --git a/OpenNest/Controls/EntityView.cs b/OpenNest/Controls/EntityView.cs index b6c24140..83c1bb30 100644 --- a/OpenNest/Controls/EntityView.cs +++ b/OpenNest/Controls/EntityView.cs @@ -163,6 +163,7 @@ namespace OpenNest.Controls DrawSelection(e.Graphics); DrawTexts(e.Graphics); DrawDimensions(e.Graphics); + DrawBendLabels(e.Graphics); DrawLabelBox(e.Graphics); if (ShowEntityLabels) diff --git a/OpenNest/Forms/CadConverterForm.LabelBox.cs b/OpenNest/Forms/CadConverterForm.LabelBox.cs index 3215189c..108dcdff 100644 --- a/OpenNest/Forms/CadConverterForm.LabelBox.cs +++ b/OpenNest/Forms/CadConverterForm.LabelBox.cs @@ -143,6 +143,44 @@ namespace OpenNest.Forms entityView1.Invalidate(); } + private string bendLabelPreviewKey; + private System.Collections.Generic.List bendLabelPreview; + + /// + /// The bend group letters as Plan Cutting would etch them beside the bend lines + /// (), for the part unrotated on a sheet whose grain runs + /// along X, like the label's own preview; null for a part without bends. Kept until the box, the bends or the cut + /// geometry's makeup change, since it is asked for at every paint. + /// + internal System.Collections.Generic.IReadOnlyList BendLabelPreview(FileListItem item) + { + if (item?.Bends == null || item.Bends.Count == 0) + return null; + + // The label box is only kept clear of; a part without one still gets its bend letters. + var box = item.LabelBox is { IsValid: true } valid ? valid : null; + var key = new System.Text.StringBuilder(); + key.Append(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(item)).Append('|').Append(DrawingUnits).Append('|') + .Append(box?.Center.X).Append(',').Append(box?.Center.Y).Append(',').Append(box?.Width).Append(',') + .Append(box?.Height).Append(',').Append(box?.Rotation).Append('|') + .Append(item.Entities.Count(en => en.Layer.IsVisible && en.IsVisible)).Append(',') + .Append(item.Breakoffs.Count).Append(',').Append(item.TabbedCutouts.Count).Append(',') + .Append(item.EntityRoles?.Count ?? 0); + foreach (var bend in item.Bends) + key.Append('|').Append(bend.StartPoint.X).Append(',').Append(bend.StartPoint.Y).Append(',') + .Append(bend.EndPoint.X).Append(',').Append(bend.EndPoint.Y).Append(',') + .Append((int)bend.Direction).Append(',').Append(bend.Angle).Append(',').Append(bend.Radius); + + var text = key.ToString(); + if (text != bendLabelPreviewKey) + { + bendLabelPreviewKey = text; + bendLabelPreview = BendLabels.Layout( + BendLabels.Place(DimensionedEntities(item), item.Bends, box, DrawingUnits), item.Bends, 0, 0); + } + return bendLabelPreview; + } + internal virtual void ShowLabelBoxMessage(string message) => MessageBox.Show(this, message, "Label Box", MessageBoxButtons.OK, MessageBoxIcon.Information); } diff --git a/OpenNest/Forms/CadConverterForm.cs b/OpenNest/Forms/CadConverterForm.cs index 21461598..06d0a230 100644 --- a/OpenNest/Forms/CadConverterForm.cs +++ b/OpenNest/Forms/CadConverterForm.cs @@ -73,7 +73,8 @@ namespace OpenNest.Forms filterPanel.DimensionRemoved += OnDimensionRemoved; entityView1.DimensionDragged += OnDimensionDragged; entityView1.LabelBoxChanged += OnLabelBoxChanged; - entityView1.LabelPreviewText = () => CurrentItem is { } item ? PartLabels.PreviewText(item.Name, item.Bends) : null; + entityView1.LabelPreviewText = () => CurrentItem is { } item ? PartLabels.PreviewText(item.Name) : null; + entityView1.BendLabelPreview = () => BendLabelPreview(CurrentItem); entityView1.TextConvertRequested += OnTextConvertRequested; entityView1.EntityActionRequested += OnEntityActionRequested; btnSplit.Click += OnSplitClicked; diff --git a/OpenNest/Forms/CuttingInspectionPanel.cs b/OpenNest/Forms/CuttingInspectionPanel.cs index fd1f1deb..b1f74ca0 100644 --- a/OpenNest/Forms/CuttingInspectionPanel.cs +++ b/OpenNest/Forms/CuttingInspectionPanel.cs @@ -835,7 +835,8 @@ internal sealed class CuttingInspectionPanel : UserControl { // Capture on the owner thread; no worker recapture of the live plate or settings. var batch = CuttingPlanBatch.Capture(plates, parameters, keepOrderCheckBox.Checked, plateNumbers, - budgetMultiplier: CuttingPlanBatch.ClampBudgetMultiplier(Properties.Settings.Default.CuttingPlanEffort)); + budgetMultiplier: CuttingPlanBatch.ClampBudgetMultiplier(Properties.Settings.Default.CuttingPlanEffort), + units: units); var run = ++generation; var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); PlanningTask = completion.Task; diff --git a/docs/label-box.md b/docs/label-box.md index 29b46248..0228cba2 100644 --- a/docs/label-box.md +++ b/docs/label-box.md @@ -1,7 +1,8 @@ # Part number label box -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 +A drawing can carry a label box: the rectangle where its part number is etched, found on flat +material clear of everything else. Bend group letters are not in it: each is etched beside its +own bend line and needs no box (see [Etching the label](#etching-the-label)). The CAD Converter stores and shows the placement; Plan Cutting etches the text when **Etch part label** is not Off (see [Etching the label](#etching-the-label)). @@ -17,9 +18,10 @@ angle is kept within a quarter turn either way of horizontal, so the text never down (a half turn covers the same rectangle). The box previews the label inside it as Plan Cutting would etch it, laid out by the same code -(`PartLabels.Layout`): the drawing name with its bend groups for the part unrotated on a sheet -whose grain runs along X (`PartLabels.PreviewText`), the longest the label gets there, so a box -that fits it also fits the part number alone. The text always reads along the box's width and +(`PartLabels.Layout`): the drawing name (`PartLabels.PreviewText`). Each bend's group letter is +previewed beside its bend line ([bend letters](#etching-the-label)), for the part unrotated on a +sheet whose grain runs along X, whether or not the part has a label box: the box is for the part +number, and a bend letter only keeps clear of it. The text always reads along the box's width and never turns by itself: a box made tall and narrow shrinks the text to fit its width, and when that leaves it under half the box height, the box turns red, the shrunk text is drawn faintly and **Too small to etch** shows under it, because Plan Cutting would etch nothing there. To run the @@ -43,8 +45,7 @@ nesting geometry, cut time or posts, and it does not appear in DXF, DWG or SVG e it will be cut (visible, roles, breakoffs and tabbed cutouts applied, as the Dimensions code reads it), its bends and a `LabelBoxOptions`. The converter tries `LabelBoxOptions.Sizes(units)` largest first and keeps the first box found: eight characters - (room for a four-digit part number and two circled bend group letters, `1234 AB`) of a half - inch, three eighths and quarter inch (12, 9 and 6 mm) stroke font, each an eighth inch (3 mm) + of a half inch, three eighths and quarter inch (12, 9 and 6 mm) stroke font, each an eighth inch (3 mm) clear of anything else. Boxes placed before keep their size until found again. - Material is what nesting reads (`NestingMaterial.ForNesting`, marks excluded), so a tabbed cutout's slug counts as part and etch, scribe and break cuts do not. The material is @@ -81,8 +82,8 @@ thickness settings). It has three choices: | Choice | Etched | Example | |--------|--------|---------| | Off | nothing | | -| Part number | the drawing name | `1234` | -| Part number and bend groups | the name, then each bend group letter in a circle | `1234 ⒶⒷ` | +| Part number | the drawing name in its label box | `1234` | +| Part number and bend groups | the same, and each bend's group letter in a circle beside its bend line | `1234`, and `Ⓐ` or `Ⓑ` by each bend | When it is not Off, 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, @@ -90,45 +91,63 @@ counts in cut time, posts through the etch path and never enters nesting or coll (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. The plan fingerprint records the mode, so changing it makes an earlier plan stale. While labels are on, so does changing a drawing's name, label box, -bends or source offset, or the plate's grain, between planning and Apply. Once applied, the etched +bends (their lines, direction, angle or radius) or source offset, or the plate's grain, between +planning and Apply. Once applied, the etched label stays as planned until the plate is planned again. Settings saved before the mode existed held an on/off `etchPartLabels` value (in the nest's cutting -parameters, the desktop settings and a machine thickness's cutting settings). It meant the full -label, so `true` loads as **Part number and bend groups** and `false` or a missing value as **Off**; +parameters, the desktop settings and a machine thickness's cutting settings). It meant the number +with the bend groups, so `true` loads as **Part number and bend groups** and `false` or a missing value as **Off**; the old key is read but never written again. When both keys are present, `labelMode` wins. A `labelMode` number that names no choice (the reader accepts numbers) loads as if it were absent. - **Text.** `PartLabels.Text` is the drawing name in capitals (characters the font lacks, and - spaces, are dropped), then, in **Part number and bend groups** mode, a space - (`PartLabels.GroupSeparator`) and the part's bend groups when it has bends: `1234 AB`. Layout - etches each letter after the space inside its own circle, so a group never reads as part of the - part number (a trailing `-A` looks like a revision). The circle is the text height across, the - letter inside it 0.6 of that, three eighths of the text height clear of the name and an eighth - apart (`PartLabels.Measure`). **Part number** mode leaves the groups out, so a part with bends - still gets `1234`. + spaces, are dropped), the same in both modes. The bend groups are never in the box: a list of + letters there does not say which bend is which. - **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, each within 5° (`BendGrain.AngleTolerance`), then **C** to **L** for the steps between, counterclockwise from the grain. A bend just past 5° goes to the neighboring step on its own side, never to A or B, and a bend 30° one way and one 30° the other way get different letters - (D and K). A part whose bends fall in several groups lists each once, in alphabetical order. + (D and K). The letter does not say which way a part bends. It says how the grain runs against its bends, which changes springback and so the angle correction at the press brake: bends with the same letter take the same correction and can be formed together. 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. + is rotated on the sheet, which is why they are made when cutting is planned, not stored with + the drawing. ![Bend group letters: A across the grain and B with it, each within 5°; C to G at 15° to 75° and H to L at 105° to 165°, counterclockwise from the grain](images/bend-groups.svg) +- **Bend letters.** In **Part number and bend groups** mode each bend gets its group letter in + a circle beside its line, so a part bent two ways shows which bend is which (`BendLabels`). The + letter inside is 0.6 of the circle's height. It is never on the line, where forming would deform it: the circle sits + just past the band kept clear along the bend, which is the clearance or, when the bend has a + radius and angle, half the arc it rolls the material through if that is wider. + - No label box is needed: the box is for the part number, and a letter only keeps clear of it. + - Size: a circle half an inch across, else three eighths, else a quarter (12, 9 or 6 mm), an + eighth inch (3 mm) clear, as the label text sizes are (`LabelBoxOptions.Sizes`). The nest's + units choose between them; Plan Cutting passes them (`CuttingPlanRequest.Units`, + `CuttingPlanBatch.Capture`), inches when a caller gives none. + - Position: for each size, beside each etch dash of an up bend long enough to have two, then the + middle of the line, then its quarter points, on the left of the line (from its start to its + end) and then the right. The first that fits is kept. Down bends have no dashes, so their + letter starts at the middle. + - Fit: on material a clearance inside every edge and hole, clear of every bend's band, of scribe + and etch marks and break cuts, of the label box and of the letters placed before it. A bend + with no such spot gets no letter. + - Each letter reads along its own bend line, turned at most a quarter so it is never upside + down. Where they go depends only on the drawing (its cut geometry, bends and box), so every + part of a drawing gets them in the same place; which letter each one is depends on the part's + rotation against the grain. + - A letter may sit on a breakoff's scrap (only the break cut itself is kept clear): it is read + before forming, and the scrap is still on the part then. - **Font.** `StrokeFont` is a small built-in single-stroke font (digits, capitals, `- _ . /`), so the label needs no font file. Strokes are lines and arcs: the round digits (0, 2, 3, 5, 6, 8, 9) are drawn on arcs and etch as arc moves; the zero keeps its slash so it never reads as the letter O. 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, circles - included. A name longer than the box is shrunk to fit, to half the box height at the least; a longer one is not etched. +- **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. @@ -141,18 +160,19 @@ A `labelMode` number that names no choice (the reader accepts numbers) loads as - **Reopening.** The label lives only in the applied part programs. Loading a nest never takes it back into the drawing as a lost etch mark (`DrawingMarkRecovery` skips drawings with a label box), so it is not etched twice and turning the option off removes it at the next plan. -- **What gets none.** A drawing with no box, parts whose cutting is locked or left out of the plan +- **What gets none.** A drawing with no box gets no part number (its bends still get their + letters); nothing is etched on 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. +Not done yet: a plan-time warning for a label or bend letter that cannot fit (it is skipped +without a message), 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" +dotnet test OpenNest.Tests/OpenNest.Tests.csproj -c Release --filter "FullyQualifiedName~BendLabelTests" scripts/Test-Hidden.ps1 OpenNest.WinForms.Tests/OpenNest.WinForms.Tests.csproj --filter FullyQualifiedName~CadConverterLabelBoxTests ```