feat(svg): add an SVG export for laser software such as LightBurn

The plate Export dialog gains "SVG for laser software, e.g. LightBurn":
only cut and mark geometry (no plate outline, rapids, display-only
geometry or uncut tabs), each kind stroked in its own LightBurn palette
color so it lands on its own layer. The plain SVG export is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-11-22 16:04:19 -05:00
1 parent 90149f1e8b
commit 04ef7d7764
7 files changed
+221 -14

No files matched your search

+19 -1
View File
@@ -37,12 +37,13 @@ public sealed class PlateExportTests : IDisposable
[InlineData(2, PlateExportFormat.Image)]
[InlineData(3, PlateExportFormat.PlacementText)]
[InlineData(4, PlateExportFormat.Svg)]
[InlineData(5, PlateExportFormat.SvgForLaser)]
public void FromFilterIndex_FollowsTheSaveDialogOrder(int index, PlateExportFormat expected) =>
Assert.Equal(expected, PlateExport.FromFilterIndex(index));
[Theory]
[InlineData(0)]
[InlineData(5)]
[InlineData(6)]
[InlineData(99)]
public void FromFilterIndex_RefusesOtherIndexes(int index) =>
Assert.Equal("filterIndex", Assert.Throws<ArgumentException>(() => PlateExport.FromFilterIndex(index)).ParamName);
@@ -147,6 +148,22 @@ public sealed class PlateExportTests : IDisposable
Assert.NotEmpty(root.Descendants().Where(e => e.Name.LocalName == "path"));
}
[Fact]
public void SvgForLaser_LeavesOutThePlateAndRapids()
{
var plate = CreateJob().Plates[0];
var path = Path.Combine(folder, "laser.svg");
PlateExport.Write(plate, Units.Millimeters, path, PlateExportFormat.SvgForLaser, null);
var root = XDocument.Load(path).Root!;
Assert.EndsWith("mm", root.Attribute("width")!.Value);
var layers = root.Elements().Select(g => g.Attribute("data-layer")!.Value).ToList();
Assert.DoesNotContain("PLATE", layers);
Assert.DoesNotContain("RAPID", layers);
Assert.Contains("CUT", layers);
}
[Fact]
public void Image_IsDrawnByTheFrontEnd_AtTheChosenPath()
{
@@ -182,6 +199,7 @@ public sealed class PlateExportTests : IDisposable
[InlineData(PlateExportFormat.Dxf)]
[InlineData(PlateExportFormat.PlacementText)]
[InlineData(PlateExportFormat.Svg)]
[InlineData(PlateExportFormat.SvgForLaser)]
public void Write_LeavesTheNestUntouched(PlateExportFormat format)
{
var nest = CreateJob();
+12 -1
View File
@@ -22,6 +22,12 @@ public enum PlateExportFormat
/// <summary>The plate's parts as SVG in the nest's units.</summary>
Svg,
/// <summary>
/// The plate's parts as SVG for laser software such as LightBurn: only what is cut or marked,
/// each kind in its own layer color (<see cref="SvgExportOptions.LaserSoftware"/>).
/// </summary>
SvgForLaser,
}
/// <summary>
@@ -48,6 +54,7 @@ public static class PlateExport
PlateExportFormat.Image,
PlateExportFormat.PlacementText,
PlateExportFormat.Svg,
PlateExportFormat.SvgForLaser,
};
/// <summary>The format for the save dialog's 1-based <paramref name="filterIndex"/>.</summary>
@@ -59,7 +66,8 @@ public static class PlateExport
/// <summary>
/// The format a chosen file's extension asks for (.dxf, .png/.jpg/.jpeg, .txt, .svg, any
/// case), or null for any other extension or none. Bitmap (.bmp) is not offered: no
/// cross-platform encoder writes it.
/// cross-platform encoder writes it. An extension cannot ask for
/// <see cref="PlateExportFormat.SvgForLaser"/>; only the save dialog's file type can.
/// </summary>
public static PlateExportFormat? FromPath(string path) =>
Path.GetExtension(path ?? "").ToLowerInvariant() switch
@@ -130,6 +138,9 @@ public static class PlateExport
case PlateExportFormat.Svg:
Svg.ExportPlate(plate, destination, units);
break;
case PlateExportFormat.SvgForLaser:
Svg.ExportPlate(plate, destination, units, SvgExportOptions.LaserSoftware);
break;
default:
throw new ArgumentException("Unsupported plate export format.", nameof(format));
}
+67 -11
View File
@@ -62,15 +62,16 @@ namespace OpenNest.IO
public static void ExportProgram(Program program, Stream stream, Units units) =>
ExportEntities(ConvertProgram.ToGeometry(program), stream, units);
public static void ExportPlate(Plate plate, string path, Units units)
public static void ExportPlate(Plate plate, string path, Units units, SvgExportOptions options = null)
{
using var stream = File.Create(path);
ExportPlate(plate, stream, units);
ExportPlate(plate, stream, units, options);
}
public static void ExportPlate(Plate plate, Stream stream, Units units)
public static void ExportPlate(Plate plate, Stream stream, Units units, SvgExportOptions options = null)
{
var entities = PlateOutline(plate);
options ??= SvgExportOptions.Default;
var entities = options.CutAndMarksOnly ? new List<Entity>() : PlateOutline(plate);
foreach (var part in plate.Parts)
{
@@ -80,7 +81,7 @@ namespace OpenNest.IO
entities.AddRange(geometry);
}
ExportEntities(entities, stream, units);
ExportEntities(entities, null, stream, units, options);
}
/// <summary>
@@ -116,10 +117,14 @@ namespace OpenNest.IO
IEnumerable<Entity> entities,
IEnumerable<Bend> bends,
Stream stream,
Units units
Units units,
SvgExportOptions options = null
)
{
var list = entities.ToList();
options ??= SvgExportOptions.Default;
var list = entities
.Where(e => !options.CutAndMarksOnly || !NeverCutLayers.Contains(LayerName(e)))
.ToList();
var bendList = bends?.ToList() ?? new List<Bend>();
var extents = list.Concat(bendList.Select(b => (Entity)b.ToLine())).ToList();
var bounds = extents.Count > 0 ? extents.GetBoundingBox() : new Box(0, 0, 1, 1);
@@ -144,8 +149,12 @@ namespace OpenNest.IO
new XAttribute("fill", "none")
);
foreach (var layer in list.GroupBy(e => e.Layer?.Name ?? Layer.Default.Name))
root.Add(LayerGroup(layer.Key, layer.ToList()));
var layers = list.GroupBy(LayerName).ToList();
var strokes = options.LaserLayerColors
? LaserStrokes(layers.Select(g => g.Key))
: layers.ToDictionary(g => g.Key, g => StrokeOf(g.Key));
foreach (var layer in layers)
root.Add(LayerGroup(layer.Key, layer.ToList(), strokes[layer.Key]));
if (bendList.Count > 0)
root.Add(BendGroup(bendList, units));
@@ -153,12 +162,12 @@ namespace OpenNest.IO
new XDocument(new XDeclaration("1.0", "utf-8", null), root).Save(stream);
}
private static XElement LayerGroup(string name, List<Entity> entities)
private static XElement LayerGroup(string name, List<Entity> entities, string stroke)
{
var group = new XElement(
Ns + "g",
new XAttribute("data-layer", name),
new XAttribute("stroke", StrokeOf(name)),
new XAttribute("stroke", stroke),
new XAttribute("stroke-width", "1"),
new XAttribute("vector-effect", "non-scaling-stroke")
);
@@ -277,6 +286,53 @@ namespace OpenNest.IO
new XAttribute("r", Number(radius))
);
// Geometry that is never cut: what SvgExportOptions.CutAndMarksOnly leaves out.
private static readonly HashSet<string> NeverCutLayers = new(StringComparer.OrdinalIgnoreCase)
{
PlateLayerName,
SpecialLayers.Rapid.Name,
SpecialLayers.Display.Name,
SpecialLayers.DisplayPerimeter.Name,
SpecialLayers.Tab.Name,
};
// A lead or common line is cut with its contour, so it shares the cut's layer color.
private static readonly HashSet<string> CutLayers = new(StringComparer.OrdinalIgnoreCase)
{
SpecialLayers.Cut.Name,
SpecialLayers.Leadin.Name,
SpecialLayers.Leadout.Name,
SpecialLayers.CommonLine.Name,
};
// LightBurn's first layer colors (C00 to C07), so each kind of cut lands on its own layer.
private static readonly string[] LaserPalette =
{
"#000000", "#0000FF", "#FF0000", "#00E000", "#D0D000", "#FF8000", "#00E0E0", "#FF00FF",
};
private static string LayerName(Entity entity) => entity.Layer?.Name ?? Layer.Default.Name;
// Cuts are C00, scribe marks C01 and break cuts C02; any other layer takes the next color
// in the order it first appears, cycling once the palette runs out.
private static Dictionary<string, string> LaserStrokes(IEnumerable<string> layers)
{
var strokes = new Dictionary<string, string>();
var next = 3;
foreach (var layer in layers)
{
if (CutLayers.Contains(layer))
strokes[layer] = LaserPalette[0];
else if (string.Equals(layer, SpecialLayers.Scribe.Name, StringComparison.OrdinalIgnoreCase))
strokes[layer] = LaserPalette[1];
else if (string.Equals(layer, SpecialLayers.Break.Name, StringComparison.OrdinalIgnoreCase))
strokes[layer] = LaserPalette[2];
else
strokes[layer] = LaserPalette[next++ % LaserPalette.Length];
}
return strokes;
}
private static string StrokeOf(string layer)
{
if (string.Equals(layer, SpecialLayers.Rapid.Name, StringComparison.OrdinalIgnoreCase))
+33
View File
@@ -0,0 +1,33 @@
namespace OpenNest.IO
{
/// <summary>
/// How <see cref="Svg"/> writes a plate or entities. The default keeps every layer with the
/// colors OpenNest reads back; <see cref="LaserSoftware"/> writes a file to cut from directly.
/// See docs/svg-import-export.md.
/// </summary>
public sealed class SvgExportOptions
{
/// <summary>Every layer, the plate outline included, in OpenNest's colors.</summary>
public static SvgExportOptions Default { get; } = new SvgExportOptions();
/// <summary>
/// For hobby laser software such as LightBurn, which makes one cut layer per stroke color:
/// only what is cut or marked, each kind in its own color.
/// </summary>
public static SvgExportOptions LaserSoftware { get; } =
new SvgExportOptions { CutAndMarksOnly = true, LaserLayerColors = true };
/// <summary>
/// Leaves out what is never cut: the plate outline and edge spacing, rapids, display-only
/// geometry and a tabbed cutout's uncut tabs.
/// </summary>
public bool CutAndMarksOnly { get; init; }
/// <summary>
/// Strokes each kind of cut in its own color from LightBurn's layer palette: cuts (with
/// their leads and common lines) black, scribe marks blue, break cuts red and any other
/// layer the next palette color. Off, every cut layer is black.
/// </summary>
public bool LaserLayerColors { get; init; }
}
}
+79
View File
@@ -134,6 +134,85 @@ namespace OpenNest.Tests.IO
Assert.Equal(expected.Length, imported.Length, 6);
}
[Fact]
public void LaserExportKeepsOnlyCutsAtTheSameSize()
{
var drawing = Plated();
var plate = new Plate(100, 50) { Quadrant = 1 };
plate.Parts.Add(new Part(drawing) { Location = new Vector(20, 30) });
plate.Parts.Add(new Part(drawing) { Location = new Vector(40, 30) });
var path = PathFor("laser.svg");
Svg.ExportPlate(plate, path, Units.Inches, SvgExportOptions.LaserSoftware);
var root = XDocument.Load(path).Root;
var layers = root.Elements().Select(g => g.Attribute("data-layer").Value).ToList();
Assert.DoesNotContain("PLATE", layers);
Assert.DoesNotContain("RAPID", layers);
Assert.Null(Svg.UndeclaredSize(path));
var imported = CadImporter.Import(path).Bounds;
var boxes = plate.Parts.Select(p => p.BoundingBox).ToList();
var left = boxes.Min(b => b.Left);
var bottom = boxes.Min(b => b.Bottom);
Assert.Equal(left, imported.Left, 6);
Assert.Equal(bottom, imported.Bottom, 6);
Assert.Equal(boxes.Max(b => b.Left + b.Length) - left, imported.Length, 6);
Assert.Equal(boxes.Max(b => b.Bottom + b.Width) - bottom, imported.Width, 6);
}
[Fact]
public void LaserColorsPutEachKindOfCutOnItsOwnLayerColor()
{
Entity On(Entity entity, Layer layer)
{
entity.Layer = layer;
return entity;
}
var entities = new[]
{
On(new Line(0, 0, 1, 0), SpecialLayers.Cut),
On(new Line(0, 0, 0, 1), SpecialLayers.Leadin),
On(new Line(1, 0, 1, 1), SpecialLayers.Scribe),
On(new Line(0, 1, 1, 1), SpecialLayers.Break),
On(new Line(0, 2, 1, 2), new Layer("ENGRAVE")),
On(new Line(0, 3, 1, 3), new Layer("OTHER")),
On(new Line(0, 4, 1, 4), SpecialLayers.Tab),
};
var path = PathFor("colors.svg");
using (var stream = File.Create(path))
Svg.ExportEntities(entities, null, stream, Units.Inches, SvgExportOptions.LaserSoftware);
var strokes = XDocument.Load(path).Root.Elements()
.ToDictionary(g => g.Attribute("data-layer").Value, g => g.Attribute("stroke").Value);
Assert.Equal("#000000", strokes["CUT"]);
Assert.Equal("#000000", strokes["LEADIN"]);
Assert.Equal("#0000FF", strokes["SCRIBE"]);
Assert.Equal("#FF0000", strokes["BREAK"]);
Assert.Equal("#00E000", strokes["ENGRAVE"]);
Assert.Equal("#D0D000", strokes["OTHER"]);
// A tabbed cutout's tabs are never cut.
Assert.False(strokes.ContainsKey("TAB"));
}
[Fact]
public void DefaultExportKeepsEveryLayerInOpenNestColors()
{
var entities = new Entity[] { new Line(0, 0, 1, 0), new Line(0, 1, 1, 1) };
entities[0].Layer = SpecialLayers.Cut;
entities[1].Layer = SpecialLayers.Tab;
var path = PathFor("default.svg");
Svg.ExportEntities(entities, path, Units.Inches);
var strokes = XDocument.Load(path).Root.Elements()
.ToDictionary(g => g.Attribute("data-layer").Value, g => g.Attribute("stroke").Value);
Assert.Equal("#000000", strokes["CUT"]);
Assert.Equal("#000000", strokes["TAB"]);
}
[Fact]
public void EmptyPlateStillWritesAValidFile()
{
+2 -1
View File
@@ -781,7 +781,8 @@ namespace OpenNest.Forms
Filter = "DXF file (*.dxf)|*.dxf|"
+ "Image as displayed (*.jpg)|*.jpg|"
+ "Locations and rotations (*.txt)|*.txt|"
+ "SVG file (*.svg)|*.svg",
+ "SVG file (*.svg)|*.svg|"
+ "SVG for laser software, e.g. LightBurn (*.svg)|*.svg",
FileName = suggestedFileName,
AddExtension = true,
DefaultExt = ".",
+9
View File
@@ -33,6 +33,15 @@ Import takes path centerlines: `path`, `rect` (with rounded corners), `circle`,
`ExportProgram`, `ExportPlate` and `ExportEntities` write one `<g data-layer>` per layer; the `ExportEntities` overload that takes bends adds a `BEND` group with each bend's `line` and `data-bend-*` attributes, plus its note as text for people. `width` and `height` are in the given units and match the `viewBox`, so one user unit is one drawing unit and the file needs no scale prompt. Arcs stay `A` commands. The plate outline and edge spacing go on `PLATE`. Plate export leaves out the rapids DXF draws between parts.
### For laser software
`SvgExportOptions.LaserSoftware` writes a file to cut from directly in hobby laser software such as LightBurn, which makes one cut layer per stroke color and ignores `data-layer`. File > Export offers it as **SVG for laser software, e.g. LightBurn** (WinForms only; the Avalonia picker chooses a format by extension, and `.svg` stays the plain export).
- `CutAndMarksOnly` leaves out what is never cut: `PLATE`, `RAPID`, `DISPLAY`, `DISPLAY PERIMETER` and `TAB`.
- `LaserLayerColors` strokes from LightBurn's palette: `CUT` with its leads and `COMMON LINE` C00 black, `SCRIBE` C01 blue, `BREAK` C02 red, and any other layer the next color from C03 in order of first appearance.
Units and arcs are written as in the default export, so the file still needs no scale prompt. The palette values are not yet checked against a LightBurn install.
## CAD Converter export
**Export...** writes the current drawing with `CadExporter`: DXF R14 to 2018, DWG 2004 to 2018 or SVG. Entities keep their layers. Bends go on `BEND` as `CENTER` lines with an MText note such as `UP 90° R 0.06`, the form `SolidWorksBendDetector` reads, so importing the file again gives back the same bends; a line picked as a bend is written only as that bend. Etch marks go on `ETCH`, which import drops and makes again from the bends. Files before 2007 write non-ASCII note characters as `\U+XXXX` escapes. ACadSharp cannot write DWG 2007, and its DWG R14 and 2000 output loses entities and layers, so those are not offered.