Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Convert DWG and DXF drawings without AutoCAD

KnifeLemon1f1889746f94
diff --git a/Directory.Packages.props b/Directory.Packages.props
index 7fbcbe54..676dcb47 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -34,6 +34,7 @@
<PackageVersion Include="Unhwp" Version="0.13.0" />
<PackageVersion Include="Markdig" Version="1.4.0" />
<PackageVersion Include="ExcelNumberFormat" Version="1.1.0" />
+ <PackageVersion Include="ACadSharp" Version="3.8.0" />
</ItemGroup>
<ItemGroup Label="Tests">
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index 05fb3bc0..a323e5ce 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -20,6 +20,7 @@ Each component remains under its own license.
| Unhwp | MIT | https://github.com/iyulab/unhwp |
| Markdig | BSD-2-Clause | https://github.com/xoofx/markdig |
| ExcelNumberFormat | MIT | https://github.com/andersnm/ExcelNumberFormat |
+| ACadSharp (DWG/DXF reading and writing; includes CSMath and CSUtilities) | MIT, Copyright (c) Albert Domenech | https://github.com/DomCR/ACadSharp |
| pypandoc-hwpx (Pandoc AST mapping and package layout in `Filee.Engines/Hwp/Hwpx`, incl. the `blank.hwpx` reference document) | MIT, Copyright (c) 2024 pypandoc-hwpx Contributors | https://github.com/msjang/pypandoc-hwpx |
| Microsoft.Extensions.* | MIT | https://github.com/dotnet/runtime |
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 15adb4d1..24403169 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -11,6 +11,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| Unhwp | built in (library) | HWP/HWPX → TXT, Markdown, HTML |
| Markdown (Markdig) | built in (library) | **Markdown → HTML, TXT** (and → PDF / DOCX through the HWPX writer, rhwp or LibreOffice) |
| Spreadsheets | built in | **XLSX ↔ CSV** (one CSV per sheet) |
+| CAD (ACadSharp + built-in renderer) | built in (library) | **DWG ↔ DXF**; DWG/DXF → **PDF** (vector), **SVG**, PNG, JPG, WEBP, TIFF, BMP, GIF, ICO, AVIF |
| **HWPX writer** | built in | **DOCX, XLSX, CSV, PPTX, TXT, Markdown → HWPX** (and with rhwp → PDF and images); HTML, ODT, RTF → HWPX with Pandoc |
| rhwp | bundled with the installer (`engines/rhwp`) | HWP/HWPX → PDF, **HWP → HWPX, HWPX → HWP** |
| LibreOffice + H2Orestart + Java | **optional download** (~420 MB, 1.3 GB on disk) | older and rare formats only: DOC, XLS, PPT, RTF and OpenDocument → PDF and to each other, output as DOCX/ODT/ODS; HWP/HWPX → DOCX/ODT |
@@ -92,6 +93,55 @@ text) and LibreOffice + H2Orestart (opens it), see `tests/Filee.Engines.Tests/Do
Not converted: Word charts, SmartArt, equations (kept as text), free-form shapes, tracked changes and comments.
+## CAD drawings (DWG, DXF)
+
+Built in, no AutoCAD or ODA software (`Filee.Engines/Cad`). [ACadSharp](https://github.com/DomCR/ACadSharp) reads
+and writes the files; Filee's own renderer draws them with SkiaSharp (one drawing routine for PDF, SVG and images).
+
+- **Reading**: DWG from R14 (AC1014) to the AutoCAD 2018 format (AC1032, still current in AutoCAD 2026); DXF R12 to
+ 2018, ASCII and binary. DWG R13 and older fail with "version not supported". Korean AutoCAD writes pre-2007 DXF with
+ the code page name `ANSI_949`, which ACadSharp 3.8 does not map; Filee rewrites that header in memory so the text
+ is decoded as CP949 (`CadFile.OpenDxf`, covered by a test that fails once ACadSharp handles it).
+- **Writing** (DWG ↔ DXF): always **AutoCAD 2018 (AC1032)** — the current DWG format (AutoCAD 2018 and later, DWG
+ TrueView, BricsCAD, ODA tools); 2018 DXF stores text as UTF-8. ACadSharp's DWG writer is younger than its reader
+ and its DXF writer, so DXF is the safer format to hand on. Objects ACadSharp does not model (proxy and AEC objects,
+ some 3D and underlay data) are not written; degenerate dimensions it cannot measure are left out of DWG output
+ instead of failing the file.
+- **What is drawn**: model space seen from the top (Z is dropped). If model space has nothing visible, the active
+ layout (paper space) is drawn instead; viewports inside it are not followed. The page is fitted to the extents of
+ what is actually drawn — the header's EXTMIN/EXTMAX are ignored, so drawings far from the origin still fill it.
+ - PDF: an ISO A3 sheet (A4 or Letter when the preset asks for it), landscape when the drawing is wider than tall,
+ 10 mm margins (or the preset's margin). Vector paths, text as text with embedded fonts.
+ - SVG: the drawing's aspect ratio with a 420 mm (A3) long edge at 96 px/inch, white background, text as `<text>`.
+ - Images: the same page rendered at the preset's render resolution (150 dpi → 2480 px on the long edge, at most
+ 12 000 px / 80 MP), then the preset's image options (resize, grayscale, quality, DPI) as for other images.
+- **Entities**: LINE, XLINE/RAY (clipped to the page), LWPOLYLINE and POLYLINE (bulges, constant and tapered widths,
+ spline-fit and 3D), CIRCLE, ARC, ELLIPSE (also partial), SPLINE (NURBS from control points, knots and weights, or
+ a smooth curve through fit points), TEXT, ATTRIB and MTEXT (justification, rotation, width factor, oblique,
+ mirroring; MTEXT word wrap, height/colour/font/width codes, stacked fractions shown as `1/2`, `%%d` `%%c` `%%p`,
+ `\U+` and `\M+` escapes), INSERT (base point, scale, rotation, MINSERT arrays, nesting, attributes), DIMENSION and
+ TABLE (their anonymous block), LEADER, MULTILEADER (lines, arrows, text or block content), HATCH, SOLID/TRACE,
+ 3DFACE edges, POINT, MLINE, polyface and polygon meshes (edges).
+- **Hatches**: solid fills, gradients as a linear gradient, patterns as their real pattern lines clipped to the
+ boundary; a pattern too dense to draw (over 20 000 segments) becomes a light tint of its colour.
+- **Colours and lines**: ACI index table and true colour, BYLAYER / BYBLOCK (inside blocks, entities on layer "0"
+ follow the insert's layer). White and near-white (ACI 7, which AutoCAD shows white on black) draw black on the white
+ page. Line weights are plotted in millimetres ("Default" as a thin 0.18 mm line); line types become dash patterns
+ scaled by LTSCALE, the entity's scale and the block scale (shapes and text inside complex line types are omitted).
+- **Layers**: off, frozen and non-plotting layers (including Defpoints) are not drawn, like a plot. A frozen layer
+ hides a whole block reference; an OFF one only its layer-0 contents.
+- **Fonts**: drawings name SHX fonts, which are not available, so text uses the text style's TrueType font when it is
+ installed (arial.ttf, malgun.ttf ...) and otherwise a sans-serif face (Noto Sans, Arial, Liberation Sans ...).
+ Characters the font lacks fall back per character to a CJK font (Noto Sans KR/CJK, Malgun Gothic, Apple SD Gothic
+ Neo, ...). These come from the fonts SkiaSharp finds on the system; without any, SkiaSharp's default typeface is
+ used and the geometry is unaffected.
+- **Not drawn** (counted per type in the log): 3DSOLID, REGION and BODY (ACIS), IMAGE, OLE objects, PDF/DWF/DGN
+ underlays, WIPEOUT (its masking is not applied), SHAPE, TOLERANCE, proxy entities. MTEXT columns, tabs, underline
+ and overline are ignored.
+- **Limits**: 1 000 000 drawn primitives, block nesting depth 16, 10 000 MINSERT cells, 2 000 000 hatch pattern
+ segments in total; beyond that the drawing is cut short with a warning in the log. Damaged or truncated files fail
+ with "The file is not a valid DWG/DXF drawing or is damaged: …".
+
## HWP ↔ HWPX
rhwp converts between the two 한글 formats without Hancom Office (`export-hwpx` and `convert`). Anything → HWP goes
diff --git a/src/Filee.Engines/Cad/CadConverter.cs b/src/Filee.Engines/Cad/CadConverter.cs
new file mode 100644
index 00000000..d0a45ff0
--- /dev/null
+++ b/src/Filee.Engines/Cad/CadConverter.cs
@@ -0,0 +1,119 @@
+// DWG / DXF conversion without AutoCAD: ACadSharp (MIT) reads DWG R13–2018+ and DXF (ASCII and binary) and writes
+// DXF and DWG; the drawing is rendered with SkiaSharp to PDF (vector), SVG and raster images.
+
+using Filee.Core.Conversion;
+using Filee.Engines.Magick;
+using ImageMagick;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
+using SkiaSharp;
+
+namespace Filee.Engines.Cad;
+
+/// <summary>
+/// DWG ↔ DXF and DWG / DXF → PDF, SVG, PNG, JPG, WEBP, TIFF, BMP, GIF, ICO, AVIF.
+/// </summary>
+/// <remarks>
+/// Rendering draws model space as seen from the top (the active layout when model space is empty), fitted to the
+/// page: PDF on an A3 sheet (A4 / Letter when the preset says so), SVG and images with the drawing's aspect ratio
+/// on a white background. See docs/ENGINES.md for what is and is not drawn.
+/// </remarks>
+public sealed class CadConverter(ILogger? logger = null) : IConverter
+{
+ private static readonly string[] Sources = ["dwg", "dxf"];
+
+ private readonly ILogger _logger = logger ?? NullLogger.Instance;
+
+ public string Id => "cad";
+ public string DisplayName => "CAD (built-in)";
+ /// <summary>
+ /// A loaded drawing takes several times its file size in memory (a 55 MB DXF peaks around 800 MB), so only
+ /// a few are converted at once.
+ /// </summary>
+ public int MaxParallelism => Math.Clamp(Environment.ProcessorCount / 2, 1, 4);
+
+ public IReadOnlyList<ConversionEdge> Edges { get; } =
+ [
+ new("dwg", "dxf"),
+ new("dxf", "dwg"),
+ .. from source in Sources
+ from target in (string[])["pdf", "svg", .. ImageEncoder.Writable]
+ select new ConversionEdge(source, target),
+ ];
+
+ public EngineStatus GetStatus() => EngineStatus.Available("ACadSharp: DWG R13–2018+, DXF");
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
+ Task.Run<IReadOnlyList<string>>(() =>
+ {
+ progress?.Report(0.05);
+ var document = CadFile.Read(step.InputPath, step.From, message => _logger.LogDebug("{File}: {Message}", step.InputPath, message));
+ cancellationToken.ThrowIfCancellationRequested();
+ progress?.Report(0.4);
+
+ if (step.To is "dxf" or "dwg")
+ {
+ if (step.Output.Allocate(step.To) is not { } path)
+ return [];
+ CadFile.Write(document, path, step.To, message => _logger.LogDebug("{File}: {Message}", path, message));
+ progress?.Report(1);
+ return [path];
+ }
+
+ var scene = CadSceneBuilder.Build(document, cancellationToken);
+ Report(step.InputPath, scene);
+ if (scene.Items.Count == 0)
+ throw new InvalidDataException(scene.Skipped.Count > 0
+ ? $"The drawing only contains objects Filee cannot draw ({string.Join(", ", scene.Skipped.Keys)})."
+ : "The drawing has nothing visible to draw: model space and the layout are empty, or every entity is on a layer that is off, frozen or not plotted.");
+ cancellationToken.ThrowIfCancellationRequested();
+ progress?.Report(0.7);
+
+ var output = step.Output.Allocate(step.To);
+ if (output is null)
+ return [];
+ switch (step.To)
+ {
+ case "pdf":
+ using (var stream = File.Create(output))
+ CadRenderer.WritePdf(scene, step.Preset.Pdf, Path.GetFileNameWithoutExtension(step.InputPath), stream);
+ break;
+ case "svg":
+ using (var stream = File.Create(output))
+ CadRenderer.WriteSvg(scene, stream);
+ break;
+ default:
+ WriteImage(scene, step, output);
+ break;
+ }
+ progress?.Report(1);
+ return [output];
+ }, cancellationToken);
+
+ /// <summary>
+ /// Renders at the preset's render resolution (PDF → image uses the same setting; 150 dpi by default, for an
+ /// A3-sized page that is about 2500 px on the long edge), then applies the image options like other image
+ /// conversions do (resize, grayscale, quality, DPI).
+ /// </summary>
+ private static void WriteImage(CadScene scene, ConversionStep step, string output)
+ {
+ var dpi = Math.Clamp(step.Preset.Pdf.RenderDpi, 36, 1200);
+ using var bitmap = CadRenderer.RenderBitmap(scene, dpi);
+ using var data = bitmap.Encode(SKEncodedImageFormat.Png, 100);
+ using var image = new MagickImage(data.ToArray());
+ image.Density = new Density(dpi, dpi, DensityUnit.PixelsPerInch);
+ ImageEncoder.ApplyOptions(image, step.Preset.Image, step.To);
+ image.Write(output, ImageEncoder.ToMagickFormat(step.To));
+ }
+
+ private void Report(string input, CadScene scene)
+ {
+ if (scene.Space != "model")
+ _logger.LogInformation("{File}: model space is empty, drew layout {Layout}", input, scene.Space);
+ if (scene.Skipped.Count > 0)
+ _logger.LogInformation("{File}: skipped {Count} unsupported entities ({Types})", input,
+ scene.Skipped.Values.Sum(), string.Join(", ", scene.Skipped.Select(p => $"{p.Key} ×{p.Value}")));
+ if (scene.Truncated)
+ _logger.LogWarning("{File}: the drawing exceeds the rendering limits and was cut short", input);
+ }
+}
diff --git a/src/Filee.Engines/Cad/CadCurves.cs b/src/Filee.Engines/Cad/CadCurves.cs
new file mode 100644
index 00000000..47e02ec6
--- /dev/null
+++ b/src/Filee.Engines/Cad/CadCurves.cs
@@ -0,0 +1,164 @@
+// Curve math for the CAD renderer: NURBS evaluation (SPLINE entities, spline hatch edges, spline-fit polylines),
+// smooth curves through fit points, and polyline bulge arcs.
+
+namespace Filee.Engines.Cad;
+
+/// <summary>Curve evaluation helpers. Everything works in the entity's own coordinates.</summary>
+internal static class CadCurves
+{
+ /// <summary>Upper bound for the points generated for one curve, so a broken knot vector cannot explode.</summary>
+ private const int MaxSamples = 4000;
+
+ /// <summary>
+ /// Samples a (rational) B-spline with de Boor's algorithm. Missing or inconsistent knots are replaced by a
+ /// clamped uniform knot vector; missing weights mean 1. Returns an empty list for unusable input.
+ /// </summary>
+ public static List<Vec3> SampleNurbs(int degree, IReadOnlyList<Vec3> controlPoints, IReadOnlyList<double> knots, IReadOnlyList<double>? weights)
+ {
+ var n = controlPoints.Count;
+ var result = new List<Vec3>();
+ if (n < 2)
+ return result;
+
+ var p = Math.Clamp(degree, 1, n - 1);
+ var t = knots.Count == n + p + 1 && IsNonDecreasing(knots) ? knots.ToArray() : ClampedUniform(n, p);
+ var w = weights is { Count: > 0 } && weights.Count == n && weights.All(v => v > 0 && double.IsFinite(v))
+ ? weights.ToArray()
+ : null;
+
+ var spans = new List<int>();
+ for (var k = p; k < n; k++)
+ if (t[k + 1] > t[k])
+ spans.Add(k);
+ if (spans.Count == 0)
+ return result;
+
+ // Straight segments need only their end points; curved spans get up to 32 points (smooth in vector output).
+ var perSpan = p == 1 ? 1 : Math.Clamp(MaxSamples / spans.Count, 1, 32);
+ var homogeneous = new (double X, double Y, double Z, double W)[p + 1];
+ foreach (var k in spans)
+ {
+ for (var s = 0; s < perSpan; s++)
+ result.Add(Evaluate(t[k] + (t[k + 1] - t[k]) * s / perSpan, k));
+ }
+ result.Add(Evaluate(t[spans[^1] + 1], spans[^1]));
+ return result;
+
+ Vec3 Evaluate(double u, int k)
+ {
+ for (var j = 0; j <= p; j++)
+ {
+ var point = controlPoints[k - p + j];
+ var weight = w?[k - p + j] ?? 1;
+ homogeneous[j] = (point.X * weight, point.Y * weight, point.Z * weight, weight);
+ }
+ for (var r = 1; r <= p; r++)
+ {
+ for (var j = p; j >= r; j--)
+ {
+ var denominator = t[j + 1 + k - r] - t[j + k - p];
+ var alpha = denominator == 0 ? 0 : (u - t[j + k - p]) / denominator;
+ var a = homogeneous[j - 1];
+ var b = homogeneous[j];
+ homogeneous[j] = (
+ (1 - alpha) * a.X + alpha * b.X,
+ (1 - alpha) * a.Y + alpha * b.Y,
+ (1 - alpha) * a.Z + alpha * b.Z,
+ (1 - alpha) * a.W + alpha * b.W);
+ }
+ }
+ var h = homogeneous[p];
+ return h.W == 0 ? new Vec3(h.X, h.Y, h.Z) : new Vec3(h.X / h.W, h.Y / h.W, h.Z / h.W);
+ }
+ }
+
+ /// <summary>
+ /// A smooth curve through fit points (centripetal Catmull-Rom), used for splines stored only as fit points
+ /// and for spline leaders. Close to what AutoCAD draws, without solving the interpolation system.
+ /// </summary>
+ public static List<Vec3> ThroughPoints(IReadOnlyList<Vec3> points, bool closed)
+ {
+ var count = points.Count;
+ var result = new List<Vec3>();
+ if (count < 3)
+ {
+ result.AddRange(points);
+ return result;
+ }
+
+ var segments = closed ? count : count - 1;
+ var perSegment = Math.Clamp(MaxSamples / segments, 1, 10);
+ for (var i = 0; i < segments; i++)
+ {
+ var p0 = Get(i - 1);
+ var p1 = Get(i);
+ var p2 = Get(i + 1);
+ var p3 = Get(i + 2);
+ for (var s = 0; s < perSegment; s++)
+ result.Add(CatmullRom(p0, p1, p2, p3, (double)s / perSegment));
+ }
+ result.Add(closed ? points[0] : points[^1]);
+ return result;
+
+ Vec3 Get(int index)
+ {
+ if (closed)
+ return points[((index % count) + count) % count];
+ // Open ends: mirror the neighbour so the tangent at the end points follows the polygon.
+ if (index < 0)
+ return points[0] + (points[0] - points[1]);
+ if (index >= count)
+ return points[^1] + (points[^1] - points[^2]);
+ return points[index];
+ }
+ }
+
+ /// <summary>
+ /// The arc of a polyline segment with bulge <paramref name="bulge"/> (tan of a quarter of the included angle,
+ /// positive = counter-clockwise) from <paramref name="p0"/> to <paramref name="p1"/>.
+ /// </summary>
+ public static (Vec2 Center, double Radius, double StartAngle, double Sweep) BulgeArc(Vec2 p0, Vec2 p1, double bulge)
+ {
+ var chord = p1 - p0;
+ var center = p0 + chord * 0.5 + chord.Perp * ((1 - bulge * bulge) / (4 * bulge));
+ var radius = (p0 - center).Length;
+ var start = Math.Atan2(p0.Y - center.Y, p0.X - center.X);
+ return (center, radius, start, 4 * Math.Atan(bulge));
+ }
+
+ private static Vec3 CatmullRom(Vec3 p0, Vec3 p1, Vec3 p2, Vec3 p3, double u)
+ {
+ // Centripetal parameterisation (alpha = 0.5) avoids loops and cusps on unevenly spaced points.
+ var t0 = 0.0;
+ var t1 = t0 + Math.Sqrt(Math.Max((p1 - p0).Length, 1e-12));
+ var t2 = t1 + Math.Sqrt(Math.Max((p2 - p1).Length, 1e-12));
+ var t3 = t2 + Math.Sqrt(Math.Max((p3 - p2).Length, 1e-12));
+ var t = t1 + (t2 - t1) * u;
+
+ var a1 = Lerp(p0, p1, t0, t1, t);
+ var a2 = Lerp(p1, p2, t1, t2, t);
+ var a3 = Lerp(p2, p3, t2, t3, t);
+ var b1 = Lerp(a1, a2, t0, t2, t);
+ var b2 = Lerp(a2, a3, t1, t3, t);
+ return Lerp(b1, b2, t1, t2, t);
+
+ static Vec3 Lerp(Vec3 a, Vec3 b, double ta, double tb, double t) =>
+ a * ((tb - t) / (tb - ta)) + b * ((t - ta) / (tb - ta));
+ }
+
+ private static bool IsNonDecreasing(IReadOnlyList<double> values)
+ {
+ for (var i = 1; i < values.Count; i++)
+ if (!(values[i] >= values[i - 1]) || !double.IsFinite(values[i]))
+ return false;
+ return values.Count > 0 && values[^1] > values[0];
+ }
+
+ private static double[] ClampedUniform(int n, int p)
+ {
+ var knots = new double[n + p + 1];
+ for (var i = 0; i < knots.Length; i++)
+ knots[i] = i <= p ? 0 : i >= n ? 1 : (double)(i - p) / (n - p);
+ return knots;
+ }
+}
diff --git a/src/Filee.Engines/Cad/CadFile.cs b/src/Filee.Engines/Cad/CadFile.cs
new file mode 100644
index 00000000..ce16c85f
--- /dev/null
+++ b/src/Filee.Engines/Cad/CadFile.cs
@@ -0,0 +1,176 @@
+// Reads DWG / DXF files and writes DXF / DWG with ACadSharp (MIT). Output is always AutoCAD 2018 (AC1032): the
+// current DWG format (AutoCAD 2018–2026, DWG TrueView, BricsCAD, LibreCAD ...), and for DXF the first-choice
+// version whose text is UTF-8, so Korean and Chinese text survive without code page guessing.
+
+using System.Text;
+using ACadSharp;
+using ACadSharp.Exceptions;
+using ACadSharp.IO;
+
+namespace Filee.Engines.Cad;
+
+/// <summary>DWG and DXF input and output.</summary>
+internal static class CadFile
+{
+ /// <summary>Version of every written DWG and DXF.</summary>
+ public const ACadVersion OutputVersion = ACadVersion.AC1032;
+
+ /// <summary>
+ /// Reads a drawing. Binary and ASCII DXF are detected automatically. Throws <see cref="InvalidDataException"/>
+ /// with a readable message for files that are not drawings, are damaged, or use an unsupported version.
+ /// </summary>
+ public static CadDocument Read(string path, string format, Action<string>? warning = null)
+ {
+ void Notify(object? sender, NotificationEventArgs e)
+ {
+ if (e.NotificationType is NotificationType.Warning or NotificationType.Error)
+ warning?.Invoke(e.Message);
+ }
+
+ var kind = format == "dwg" ? "DWG" : "DXF";
+ try
+ {
+ if (format == "dwg")
+ {
+ RequireDwgSignature(path);
+ return DwgReader.Read(path, new DwgReaderConfiguration { Failsafe = true }, Notify);
+ }
+
+ // CreateDefaults adds missing tables (layer 0, standard styles, model space) so that files from simple
+ // DXF writers can be rendered and saved as DWG.
+ var configuration = new DxfReaderConfiguration { Failsafe = true, CreateDefaults = true };
+ using var stream = OpenDxf(path);
+ using var reader = new DxfReader(stream, Notify) { Configuration = configuration };
+ return reader.Read();
+ }
+ catch (CadNotSupportedException ex)
+ {
+ throw new InvalidDataException($"This {kind} version is not supported ({ex.Message}).", ex);
+ }
+ catch (Exception ex) when (ex is not (InvalidDataException or OperationCanceledException or UnauthorizedAccessException or OutOfMemoryException)
+ && (ex is not IOException || ex is EndOfStreamException))
+ {
+ // File system errors (locked, missing) keep their own message; a truncated file is damage.
+ throw new InvalidDataException($"The file is not a valid {kind} drawing or is damaged: {ex.Message}", ex);
+ }
+ }
+
+ /// <summary>Writes the drawing as an AutoCAD 2018 DXF (ASCII) or DWG.</summary>
+ public static void Write(CadDocument document, string path, string format, Action<string>? warning = null)
+ {
+ void Notify(object? sender, NotificationEventArgs e)
+ {
+ if (e.NotificationType is NotificationType.Warning or NotificationType.Error)
+ warning?.Invoke(e.Message);
+ }
+
+ document.Header.Version = OutputVersion;
+ try
+ {
+ DropStraySequenceEnds(document);
+ if (format == "dwg")
+ {
+ DropUnwritableDimensions(document, warning);
+ DwgWriter.Write(path, document, new DwgWriterConfiguration(), Notify);
+ }
+ else
+ DxfWriter.Write(path, document, binary: false, new DxfWriterConfiguration(), Notify);
+ }
+ catch (Exception ex) when (ex is not (OperationCanceledException or IOException or UnauthorizedAccessException))
+ {
+ TryDelete(path);
+ throw new InvalidDataException($"The drawing could not be written as {format.ToUpperInvariant()}: {ex.Message}", ex);
+ }
+ }
+
+ /// <summary>
+ /// R12 DXF files can leave SEQEND markers behind as loose entities; the writers reject them (DWG) or would
+ /// write them as garbage (DXF). They carry no geometry.
+ /// </summary>
+ private static void DropStraySequenceEnds(CadDocument document)
+ {
+ foreach (var record in document.BlockRecords)
+ foreach (var marker in record.Entities.OfType<ACadSharp.Entities.Seqend>().ToList())
+ record.Entities.Remove(marker);
+ }
+
+ /// <summary>
+ /// DWG stores each dimension's measured value, which ACadSharp computes from the definition points and cannot
+ /// compute for degenerate ones (e.g. an angular dimension with coincident points, seen in old R12 files).
+ /// Those dimensions are left out instead of failing the whole file.
+ /// </summary>
+ private static void DropUnwritableDimensions(CadDocument document, Action<string>? warning)
+ {
+ foreach (var record in document.BlockRecords)
+ {
+ var broken = new List<ACadSharp.Entities.Dimension>();
+ foreach (var dimension in record.Entities.OfType<ACadSharp.Entities.Dimension>())
+ {
+ try
+ {
+ _ = dimension.Measurement;
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or ArgumentException or ArithmeticException)
+ {
+ broken.Add(dimension);
+ }
+ }
+ foreach (var dimension in broken)
+ record.Entities.Remove(dimension);
+ if (broken.Count > 0)
+ warning?.Invoke($"{broken.Count} degenerate dimension(s) in {record.Name} were left out of the DWG.");
+ }
+ }
+
+ /// <summary>DWG files start with "AC10xx"; anything else fails early with a clear message.</summary>
+ private static void RequireDwgSignature(string path)
+ {
+ Span<byte> head = stackalloc byte[6];
+ using var stream = File.OpenRead(path);
+ if (stream.ReadAtLeast(head, head.Length, throwOnEndOfStream: false) < head.Length
+ || head[0] != 'A' || head[1] != 'C' || !char.IsAsciiDigit((char)head[2]))
+ throw new InvalidDataException("The file is not a DWG drawing (it does not start with an AutoCAD version tag).");
+ }
+
+ /// <summary>
+ /// Opens a DXF for reading. Korean AutoCAD saves pre-2007 DXF with <c>$DWGCODEPAGE ANSI_949</c>, a name
+ /// ACadSharp 3.8 does not map (it would decode the text as UTF-8); such headers are rewritten to the
+ /// equivalent name it knows, in memory.
+ /// </summary>
+ private static Stream OpenDxf(string path)
+ {
+ var stream = File.OpenRead(path);
+ var head = new byte[(int)Math.Min(stream.Length, 64 * 1024)];
+ stream.ReadExactly(head);
+ stream.Position = 0;
+
+ var text = Encoding.ASCII.GetString(head);
+ var key = text.IndexOf("$DWGCODEPAGE", StringComparison.Ordinal);
+ if (key < 0)
+ return stream;
+ var value = text.IndexOf("ANSI_949", key, Math.Min(64, text.Length - key), StringComparison.OrdinalIgnoreCase);
+ if (value < 0)
+ return stream;
+
+ using (stream)
+ {
+ var bytes = File.ReadAllBytes(path);
+ var replacement = Encoding.ASCII.GetBytes("KCS5601");
+ var patched = new byte[bytes.Length - 8 + replacement.Length];
+ bytes.AsSpan(0, value).CopyTo(patched);
+ replacement.CopyTo(patched.AsSpan(value));
+ bytes.AsSpan(value + 8).CopyTo(patched.AsSpan(value + replacement.Length));
+ return new MemoryStream(patched, writable: false);
+ }
+ }
+
+ private static void TryDelete(string path)
+ {
+ try
+ {
+ File.Delete(path);
+ }
+ catch (IOException) { }
+ catch (UnauthorizedAccessException) { }
+ }
+}
diff --git a/src/Filee.Engines/Cad/CadFonts.cs b/src/Filee.Engines/Cad/CadFonts.cs
new file mode 100644
index 00000000..81def30a
--- /dev/null
+++ b/src/Filee.Engines/Cad/CadFonts.cs
@@ -0,0 +1,185 @@
+// Fonts for CAD text. Drawings name SHX fonts (txt.shx, romans.shx, Korean big fonts) that Filee does not ship, so
+// text is drawn with a sans-serif typeface; a TrueType style font (arial.ttf, malgun.ttf ...) is used when available.
+// Characters the chosen typeface lacks (Hangul, Hanzi ...) fall back per character to a CJK font.
+
+using System.Collections.Concurrent;
+using SkiaSharp;
+
+namespace Filee.Engines.Cad;
+
+/// <summary>A piece of one text line drawn with one typeface.</summary>
+/// <param name="Advance">Advance width in em (font size 1).</param>
+internal readonly record struct GlyphRun(string Text, SKTypeface Typeface, double Advance);
+
+/// <summary>Typeface lookup and text measurement shared by the scene builder and the renderer.</summary>
+internal static class CadFonts
+{
+ /// <summary>Font size used for measuring; advances are divided by it (small sizes suffer from rounding).</summary>
+ private const float MeasureSize = 64;
+
+ /// <summary>Families tried for Latin text, in order.</summary>
+ private static readonly string[] SansFamilies =
+ ["Noto Sans", "Arial", "Helvetica", "Liberation Sans", "DejaVu Sans", "Segoe UI"];
+
+ /// <summary>
+ /// Families tried for characters the main typeface lacks: Korean first (Filee's main audience), then Chinese and
+ /// Japanese. Only fonts Skia can find are used; without any, SkiaSharp's own fallback decides.
+ /// </summary>
+ private static readonly string[] CjkFamilies =
+ [
+ "Noto Sans KR", "Noto Sans CJK KR", "Malgun Gothic", "Apple SD Gothic Neo", "NanumGothic",
+ "Noto Sans SC", "Noto Sans CJK SC", "Microsoft YaHei", "PingFang SC", "Yu Gothic", "MS Gothic",
+ ];
+
+ /// <summary>Common Windows font files named by text styles, mapped to their family names.</summary>
+ private static readonly Dictionary<string, string> FileFamilies = new(StringComparer.OrdinalIgnoreCase)
+ {
+ ["arial"] = "Arial",
+ ["arialn"] = "Arial Narrow",
+ ["times"] = "Times New Roman",
+ ["cour"] = "Courier New",
+ ["calibri"] = "Calibri",
+ ["tahoma"] = "Tahoma",
+ ["verdana"] = "Verdana",
+ ["isocpeur"] = "ISOCPEUR",
+ ["malgun"] = "Malgun Gothic",
+ ["gulim"] = "Gulim",
+ ["batang"] = "Batang",
+ ["dotum"] = "Dotum",
+ ["gungsuh"] = "Gungsuh",
+ ["simsun"] = "SimSun",
+ ["simhei"] = "SimHei",
+ ["msyh"] = "Microsoft YaHei",
+ ["msgothic"] = "MS Gothic",
+ ["msmincho"] = "MS Mincho",
+ };
+
+ private static readonly ConcurrentDictionary<(string Family, bool Bold, bool Italic), SKTypeface?> Families = new();
+ private static readonly ConcurrentDictionary<(int CodePoint, SKTypeface Primary), SKTypeface?> Fallbacks = new();
+ private static readonly ConcurrentDictionary<(bool Bold, bool Italic), SKTypeface> Defaults = new();
+ private static readonly ConcurrentDictionary<SKTypeface, (double CapHeight, double Descent)> FontMetrics = new();
+
+ [ThreadStatic]
+ private static Dictionary<SKTypeface, SKFont>? _measuringFonts;
+
+ /// <summary>
+ /// The typeface for a text style: its TrueType family if installed (family name or font file), else the
+ /// default sans-serif typeface. Never null.
+ /// </summary>
+ public static SKTypeface Resolve(string? familyOrFile, bool bold, bool italic)
+ {
+ var family = FamilyOf(familyOrFile);
+ if (family is not null && Find(family, bold, italic) is { } typeface)
+ return typeface;
+ return Defaults.GetOrAdd((bold, italic), key =>
+ SansFamilies.Select(f => Find(f, key.Bold, key.Italic)).FirstOrDefault(t => t is not null)
+ ?? SKTypeface.FromFamilyName(null, Style(key.Bold, key.Italic))
+ ?? SKTypeface.Default);
+ }
+
+ /// <summary>Splits a line into runs by typeface coverage and measures each run in em.</summary>
+ public static List<GlyphRun> Layout(string text, SKTypeface primary)
+ {
+ var runs = new List<GlyphRun>();
+ if (text.Length == 0)
+ return runs;
+
+ var start = 0;
+ SKTypeface? current = null;
+ for (var i = 0; i < text.Length;)
+ {
+ var width = char.IsSurrogatePair(text, i) ? 2 : 1;
+ var codePoint = width == 2 ? char.ConvertToUtf32(text[i], text[i + 1]) : text[i];
+ // Spaces stay in the current run, so a Korean phrase is one run in one typeface.
+ var face = char.IsWhiteSpace(text[i]) ? current ?? primary
+ : primary.ContainsGlyph(codePoint) ? primary
+ : Fallback(codePoint, primary);
+ if (current is not null && !ReferenceEquals(face, current))
+ {
+ runs.Add(Measure(text[start..i], current));
+ start = i;
+ }
+ current = face;
+ i += width;
+ }
+ runs.Add(Measure(text[start..], current!));
+ return runs;
+ }
+
+ /// <summary>Cap height and descent of a typeface as fractions of the em size.</summary>
+ public static (double CapHeight, double Descent) Metrics(SKTypeface typeface) =>
+ FontMetrics.GetOrAdd(typeface, face =>
+ {
+ var metrics = MeasuringFont(face).Metrics;
+ var cap = metrics.CapHeight / MeasureSize;
+ var descent = metrics.Descent / MeasureSize;
+ // Some fonts report no cap height; 0.7 em is typical for sans-serif faces.
+ return (cap is > 0.3f and < 1.2f ? cap : 0.7, descent is > 0 and < 1 ? descent : 0.21);
+ });
+
+ /// <summary>A font set up for geometric layout: no hinting, so measured and drawn advances agree at any scale.</summary>
+ public static SKFont CreateFont(SKTypeface typeface, float size) => new(typeface, size)
+ {
+ Hinting = SKFontHinting.None,
+ Subpixel = true,
+ LinearMetrics = true,
+ Edging = SKFontEdging.Antialias,
+ };
+
+ private static GlyphRun Measure(string text, SKTypeface typeface)
+ {
+ double advance = MeasuringFont(typeface).MeasureText(text) / MeasureSize;
+ if (advance <= 0 && text.Trim().Length > 0)
+ advance = 0.6 * text.Length; // a typeface without glyphs: keep a plausible width for extents and alignment
+ return new GlyphRun(text, typeface, advance);
+ }
+
+ /// <summary>
+ /// One measuring font per typeface and thread (SKFont is not thread-safe, and creating one per text is slow
+ /// for drawings with tens of thousands of texts).
+ /// </summary>
+ private static SKFont MeasuringFont(SKTypeface typeface)
+ {
+ _measuringFonts ??= [];
+ if (!_measuringFonts.TryGetValue(typeface, out var font))
+ _measuringFonts[typeface] = font = CreateFont(typeface, MeasureSize);
+ return font;
+ }
+
+ private static SKTypeface Fallback(int codePoint, SKTypeface primary) =>
+ Fallbacks.GetOrAdd((codePoint, primary), key =>
+ {
+ using var style = key.Primary.FontStyle;
+ var bold = style.Weight >= (int)SKFontStyleWeight.SemiBold;
+ foreach (var family in CjkFamilies)
+ if (Find(family, bold, false) is { } face && face.ContainsGlyph(key.CodePoint))
+ return face;
+ return SKFontManager.Default.MatchCharacter(null, Style(bold, false), ["ko", "zh", "ja"], key.CodePoint);
+ }) ?? primary;
+
+ private static SKTypeface? Find(string family, bool bold, bool italic) =>
+ Families.GetOrAdd((family, bold, italic), key =>
+ {
+ // MatchFamily returns null for unknown families (FromFamilyName would silently substitute).
+ var face = SKFontManager.Default.MatchFamily(key.Family, Style(key.Bold, key.Italic));
+ return face is not null && face.GlyphCount > 0 ? face : null;
+ });
+
+ private static string? FamilyOf(string? familyOrFile)
+ {
+ if (string.IsNullOrWhiteSpace(familyOrFile))
+ return null;
+ var name = familyOrFile.Trim();
+ var extension = Path.GetExtension(name);
+ if (extension.Equals(".shx", StringComparison.OrdinalIgnoreCase))
+ return null;
+ if (extension.Length > 0)
+ name = Path.GetFileNameWithoutExtension(name);
+ return FileFamilies.TryGetValue(name, out var family) ? family : name;
+ }
+
+ private static SKFontStyle Style(bool bold, bool italic) => new(
+ bold ? SKFontStyleWeight.Bold : SKFontStyleWeight.Normal,
+ SKFontStyleWidth.Normal,
+ italic ? SKFontStyleSlant.Italic : SKFontStyleSlant.Upright);
+}
diff --git a/src/Filee.Engines/Cad/CadGeometry.cs b/src/Filee.Engines/Cad/CadGeometry.cs
new file mode 100644
index 00000000..3f0512e7
--- /dev/null
+++ b/src/Filee.Engines/Cad/CadGeometry.cs
@@ -0,0 +1,282 @@
+// Geometry for the CAD renderer: 3D affine transforms (block inserts, object coordinate systems), 2D paths whose
+// arcs are stored as cubic Béziers so they stay exact under any affine transform, and bounding boxes.
+
+using CSMath;
+
+namespace Filee.Engines.Cad;
+
+/// <summary>A point or vector in the drawing plane (WCS X/Y after the top-view projection).</summary>
+internal readonly record struct Vec2(double X, double Y)
+{
+ public static Vec2 operator +(Vec2 a, Vec2 b) => new(a.X + b.X, a.Y + b.Y);
+ public static Vec2 operator -(Vec2 a, Vec2 b) => new(a.X - b.X, a.Y - b.Y);
+ public static Vec2 operator -(Vec2 a) => new(-a.X, -a.Y);
+ public static Vec2 operator *(Vec2 a, double k) => new(a.X * k, a.Y * k);
+ public static Vec2 operator *(double k, Vec2 a) => new(a.X * k, a.Y * k);
+
+ public double Length => Math.Sqrt(X * X + Y * Y);
+
+ /// <summary>The vector rotated by +90°.</summary>
+ public Vec2 Perp => new(-Y, X);
+
+ public bool IsFinite => double.IsFinite(X) && double.IsFinite(Y);
+
+ public Vec2 Normalized()
+ {
+ var length = Length;
+ return length > 0 ? new Vec2(X / length, Y / length) : new Vec2(1, 0);
+ }
+
+ public static double Dot(Vec2 a, Vec2 b) => a.X * b.X + a.Y * b.Y;
+
+ // The generated record ToString would print Perp, which is a Vec2 again: endless recursion.
+ public override string ToString() => FormattableString.Invariant($"({X}, {Y})");
+}
+
+/// <summary>A 3D point or vector (double precision) used while walking entities and blocks.</summary>
+internal readonly record struct Vec3(double X, double Y, double Z)
+{
+ public static Vec3 operator +(Vec3 a, Vec3 b) => new(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
+ public static Vec3 operator -(Vec3 a, Vec3 b) => new(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
+ public static Vec3 operator *(Vec3 a, double k) => new(a.X * k, a.Y * k, a.Z * k);
+
+ public double Length => Math.Sqrt(X * X + Y * Y + Z * Z);
+
+ public static implicit operator Vec3(XYZ p) => new(p.X, p.Y, p.Z);
+
+ public static Vec3 Cross(Vec3 a, Vec3 b) => new(a.Y * b.Z - a.Z * b.Y, a.Z * b.X - a.X * b.Z, a.X * b.Y - a.Y * b.X);
+
+ public Vec3 Normalized()
+ {
+ var length = Length;
+ return length > 0 ? new Vec3(X / length, Y / length, Z / length) : new Vec3(0, 0, 1);
+ }
+
+ public override string ToString() => FormattableString.Invariant($"({X}, {Y}, {Z})");
+}
+
+/// <summary>
+/// A 3D affine transform from an entity's own coordinates to WCS: the images of the X, Y and Z axes plus a
+/// translation. Block inserts, arrays and object coordinate systems (OCS) are chained as products of these.
+/// </summary>
+internal readonly struct Affine3(Vec3 x, Vec3 y, Vec3 z, Vec3 t)
+{
+ public static readonly Affine3 Identity = new(new(1, 0, 0), new(0, 1, 0), new(0, 0, 1), default);
+
+ public Vec3 X { get; } = x;
+ public Vec3 Y { get; } = y;
+ public Vec3 Z { get; } = z;
+ public Vec3 T { get; } = t;
+
+ public static Affine3 Translation(Vec3 t) => new(new(1, 0, 0), new(0, 1, 0), new(0, 0, 1), t);
+
+ public static Affine3 Scale(double sx, double sy, double sz) => new(new(sx, 0, 0), new(0, sy, 0), new(0, 0, sz), default);
+
+ public static Affine3 RotationZ(double angle)
+ {
+ var (sin, cos) = Math.SinCos(angle);
+ return new(new(cos, sin, 0), new(-sin, cos, 0), new(0, 0, 1), default);
+ }
+
+ /// <summary>
+ /// The object coordinate system of an entity with the given extrusion direction, built with AutoCAD's
+ /// "arbitrary axis algorithm". Mirrored 2D entities typically carry the normal (0, 0, -1).
+ /// </summary>
+ public static Affine3 Ocs(Vec3 normal)
+ {
+ var n = normal.Normalized();
+ if (Math.Abs(n.X) < 1e-12 && Math.Abs(n.Y) < 1e-12 && n.Z > 0)
+ return Identity;
+ const double Limit = 1.0 / 64;
+ var ax = Math.Abs(n.X) < Limit && Math.Abs(n.Y) < Limit
+ ? Vec3.Cross(new Vec3(0, 1, 0), n)
+ : Vec3.Cross(new Vec3(0, 0, 1), n);
+ ax = ax.Normalized();
+ var ay = Vec3.Cross(n, ax).Normalized();
+ return new(ax, ay, n, default);
+ }
+
+ public Vec3 Apply(Vec3 p) => new(
+ T.X + X.X * p.X + Y.X * p.Y + Z.X * p.Z,
+ T.Y + X.Y * p.X + Y.Y * p.Y + Z.Y * p.Z,
+ T.Z + X.Z * p.X + Y.Z * p.Y + Z.Z * p.Z);
+
+ public Vec3 ApplyVector(Vec3 v) => new(
+ X.X * v.X + Y.X * v.Y + Z.X * v.Z,
+ X.Y * v.X + Y.Y * v.Y + Z.Y * v.Z,
+ X.Z * v.X + Y.Z * v.Y + Z.Z * v.Z);
+
+ /// <summary>Maps a point and projects it onto the drawing plane.</summary>
+ public Vec2 Point(Vec3 p)
+ {
+ var w = Apply(p);
+ return new Vec2(w.X, w.Y);
+ }
+
+ /// <summary>Maps a point given in the entity's XY plane (Z = <paramref name="z"/>).</summary>
+ public Vec2 Point(double x, double y, double z = 0) => Point(new Vec3(x, y, z));
+
+ /// <summary>Maps a direction vector and projects it onto the drawing plane.</summary>
+ public Vec2 Vector(Vec3 v)
+ {
+ var w = ApplyVector(v);
+ return new Vec2(w.X, w.Y);
+ }
+
+ public Vec2 Vector(double x, double y) => Vector(new Vec3(x, y, 0));
+
+ /// <summary>Composition: first <paramref name="inner"/>, then this transform.</summary>
+ public Affine3 Multiply(Affine3 inner) =>
+ new(ApplyVector(inner.X), ApplyVector(inner.Y), ApplyVector(inner.Z), Apply(inner.T));
+
+ /// <summary>
+ /// Average scale of the projected XY plane (square root of the area ratio), used for widths and dash lengths
+ /// that are defined in the entity's units.
+ /// </summary>
+ public double PlanScale
+ {
+ get
+ {
+ var det = Math.Abs(X.X * Y.Y - X.Y * Y.X);
+ if (det > 1e-300)
+ return Math.Sqrt(det);
+ // A plane seen edge-on: fall back to the longest axis image so widths do not vanish.
+ return Math.Max(new Vec2(X.X, X.Y).Length, new Vec2(Y.X, Y.Y).Length);
+ }
+ }
+}
+
+/// <summary>One segment of a <see cref="Figure"/>: a straight line or a cubic Bézier ending in <see cref="P"/>.</summary>
+internal readonly record struct Segment(Vec2 C1, Vec2 C2, Vec2 P, bool IsCubic)
+{
+ public static Segment Line(Vec2 p) => new(default, default, p, false);
+
+ public static Segment Cubic(Vec2 c1, Vec2 c2, Vec2 p) => new(c1, c2, p, true);
+}
+
+/// <summary>A connected run of segments in WCS (a polyline, an arc, a hatch loop ...).</summary>
+internal sealed class Figure(Vec2 start)
+{
+ public Vec2 Start { get; } = start;
+ public List<Segment> Segments { get; } = [];
+ public bool Closed { get; set; }
+
+ public Vec2 End => Segments.Count == 0 ? Start : Segments[^1].P;
+
+ public void LineTo(Vec2 p) => Segments.Add(Segment.Line(p));
+
+ /// <summary>
+ /// Appends the elliptical arc <c>C + U·cos t + V·sin t</c> for t from <paramref name="t0"/> to
+ /// <paramref name="t1"/> as cubic Béziers of at most 90° each. The figure should already end at the arc start.
+ /// Because U and V are the images of the original axes, this is exact for circles seen through any affine
+ /// transform (non-uniform block scales, tilted planes).
+ /// </summary>
+ public void ArcTo(Vec2 center, Vec2 u, Vec2 v, double t0, double t1)
+ {
+ var sweep = t1 - t0;
+ var count = Math.Max(1, (int)Math.Ceiling(Math.Abs(sweep) / (Math.PI / 2) - 1e-9));
+ var step = sweep / count;
+ var k = 4.0 / 3.0 * Math.Tan(step / 4);
+ for (var i = 0; i < count; i++)
+ {
+ var a = t0 + step * i;
+ var b = a + step;
+ var (sa, ca) = Math.SinCos(a);
+ var (sb, cb) = Math.SinCos(b);
+ var p0 = center + u * ca + v * sa;
+ var p3 = center + u * cb + v * sb;
+ var d0 = u * -sa + v * ca;
+ var d3 = u * -sb + v * cb;
+ Segments.Add(Segment.Cubic(p0 + d0 * k, p3 - d3 * k, p3));
+ }
+ }
+
+ /// <summary>Includes every point of the figure (not just the Bézier control points) in <paramref name="box"/>.</summary>
+ public void AddTo(ref Box2 box)
+ {
+ box.Add(Start);
+ var previous = Start;
+ foreach (var segment in Segments)
+ {
+ if (segment.IsCubic)
+ AddCubic(ref box, previous, segment.C1, segment.C2, segment.P);
+ else
+ box.Add(segment.P);
+ previous = segment.P;
+ }
+ }
+
+ /// <summary>Exact bounds of a cubic Bézier: its end points and the roots of the derivative per axis.</summary>
+ private static void AddCubic(ref Box2 box, Vec2 p0, Vec2 p1, Vec2 p2, Vec2 p3)
+ {
+ box.Add(p3);
+ Span<double> roots = stackalloc double[4];
+ var count = DerivativeRoots(p0.X, p1.X, p2.X, p3.X, roots);
+ count += DerivativeRoots(p0.Y, p1.Y, p2.Y, p3.Y, roots[count..]);
+ for (var i = 0; i < count; i++)
+ {
+ var t = roots[i];
+ var mt = 1 - t;
+ var a = mt * mt * mt;
+ var b = 3 * mt * mt * t;
+ var c = 3 * mt * t * t;
+ var d = t * t * t;
+ box.Add(new Vec2(
+ a * p0.X + b * p1.X + c * p2.X + d * p3.X,
+ a * p0.Y + b * p1.Y + c * p2.Y + d * p3.Y));
+ }
+ }
+
+ private static int DerivativeRoots(double p0, double p1, double p2, double p3, Span<double> roots)
+ {
+ // B'(t)/3 = a t² + b t + c
+ var a = -p0 + 3 * p1 - 3 * p2 + p3;
+ var b = 2 * (p0 - 2 * p1 + p2);
+ var c = p1 - p0;
+ var count = 0;
+ if (Math.Abs(a) < 1e-12)
+ {
+ if (Math.Abs(b) > 1e-12)
+ count = Keep(-c / b, roots, count);
+ return count;
+ }
+ var disc = b * b - 4 * a * c;
+ if (disc < 0)
+ return 0;
+ var sq = Math.Sqrt(disc);
+ count = Keep((-b + sq) / (2 * a), roots, count);
+ count = Keep((-b - sq) / (2 * a), roots, count);
+ return count;
+
+ static int Keep(double t, Span<double> roots, int count)
+ {
+ if (t > 0 && t < 1)
+ roots[count++] = t;
+ return count;
+ }
+ }
+}
+
+/// <summary>An axis-aligned bounding box in WCS; empty until the first point is added.</summary>
+internal struct Box2
+{
+ public double MinX, MinY, MaxX, MaxY;
+ public bool IsEmpty;
+
+ public static Box2 Empty => new() { MinX = double.MaxValue, MinY = double.MaxValue, MaxX = double.MinValue, MaxY = double.MinValue, IsEmpty = true };
+
+ public readonly double Width => IsEmpty ? 0 : MaxX - MinX;
+ public readonly double Height => IsEmpty ? 0 : MaxY - MinY;
+
+ public void Add(Vec2 p)
+ {
+ // Garbage coordinates (NaN, 1e300 from corrupt files) must not blow up the page fit.
+ if (!p.IsFinite || Math.Abs(p.X) > 1e15 || Math.Abs(p.Y) > 1e15)
+ return;
+ MinX = Math.Min(MinX, p.X);
+ MinY = Math.Min(MinY, p.Y);
+ MaxX = Math.Max(MaxX, p.X);
+ MaxY = Math.Max(MaxY, p.Y);
+ IsEmpty = false;
+ }
+}
diff --git a/src/Filee.Engines/Cad/CadRenderer.cs b/src/Filee.Engines/Cad/CadRenderer.cs
new file mode 100644
index 00000000..3e404972
--- /dev/null
+++ b/src/Filee.Engines/Cad/CadRenderer.cs
@@ -0,0 +1,432 @@
+// Draws a CadScene with SkiaSharp. One drawing routine serves every output: SKDocument (PDF, vector),
+// SKSvgCanvas (SVG) and a raster SKBitmap (PNG and the other image formats). Only the page setup differs.
+
+using Filee.Core.Presets;
+using SkiaSharp;
+
+namespace Filee.Engines.Cad;
+
+/// <summary>
+/// Where the drawing lands on the page: a uniform scale that fits the extents into the printable area, centred,
+/// with Y pointing down as on every page.
+/// </summary>
+internal sealed class PageLayout
+{
+ private readonly double _offsetX;
+ private readonly double _offsetY;
+
+ private PageLayout(float width, float height, double unitsPerMm, double scale, double offsetX, double offsetY)
+ {
+ Width = width;
+ Height = height;
+ UnitsPerMm = unitsPerMm;
+ Scale = scale;
+ _offsetX = offsetX;
+ _offsetY = offsetY;
+ }
+
+ /// <summary>Page width in output units (PDF points, SVG pixels, bitmap pixels).</summary>
+ public float Width { get; }
+
+ public float Height { get; }
+
+ /// <summary>Output units per millimetre of paper (line weights are given in millimetres).</summary>
+ public double UnitsPerMm { get; }
+
+ /// <summary>Output units per drawing unit.</summary>
+ public double Scale { get; }
+
+ public Vec2 ToPage(Vec2 p) => new(p.X * Scale + _offsetX, -p.Y * Scale + _offsetY);
+
+ public Vec2 VectorToPage(Vec2 v) => new(v.X * Scale, -v.Y * Scale);
+
+ public SKPoint Point(Vec2 p)
+ {
+ var q = ToPage(p);
+ return new SKPoint((float)q.X, (float)q.Y);
+ }
+
+ /// <summary>The WCS point shown at page position (x, y).</summary>
+ public Vec2 FromPage(double x, double y) => new((x - _offsetX) / Scale, -(y - _offsetY) / Scale);
+
+ /// <summary>
+ /// PDF: an ISO sheet (A3 unless the preset asks for A4 or Letter), landscape when the drawing is wider than
+ /// tall, 10 mm margins unless the preset sets its own.
+ /// </summary>
+ public static PageLayout ForPdf(Box2 extents, PdfOptions options)
+ {
+ var (shortMm, longMm) = options.PageSize switch
+ {
+ PdfPageSize.A4 => (210.0, 297.0),
+ PdfPageSize.Letter => (215.9, 279.4),
+ _ => (297.0, 420.0),
+ };
+ var (width, height) = Size(extents);
+ var landscape = width >= height;
+ var margin = options.MarginMm > 0 ? Math.Min(options.MarginMm, shortMm / 4) : 10;
+ return Fit(extents, landscape ? longMm : shortMm, landscape ? shortMm : longMm, margin, 72 / 25.4);
+ }
+
+ /// <summary>
+ /// SVG and images: a page with the drawing's aspect ratio whose long edge is an A3 sheet (420 mm) and a
+ /// 6 mm margin. <paramref name="unitsPerMm"/> sets the resolution (96/25.4 for SVG pixels, dpi/25.4 for bitmaps).
+ /// </summary>
+ public static PageLayout ForImage(Box2 extents, double unitsPerMm)
+ {
+ const double LongMm = 420;
+ const double MarginMm = 6;
+ var (width, height) = Size(extents);
+ // Very thin drawings (one long line) still get a usable page: at most 20:1.
+ var aspect = Math.Clamp(height / width, 1.0 / 20, 20);
+ var content = LongMm - 2 * MarginMm;
+ var (contentWidth, contentHeight) = aspect <= 1 ? (content, content * aspect) : (content / aspect, content);
+ return Fit(extents, contentWidth + 2 * MarginMm, contentHeight + 2 * MarginMm, MarginMm, unitsPerMm);
+ }
+
+ private static PageLayout Fit(Box2 extents, double pageWidthMm, double pageHeightMm, double marginMm, double unitsPerMm)
+ {
+ var (width, height) = Size(extents);
+ var availableWidth = (pageWidthMm - 2 * marginMm) * unitsPerMm;
+ var availableHeight = (pageHeightMm - 2 * marginMm) * unitsPerMm;
+ var scale = Math.Min(availableWidth / width, availableHeight / height);
+ var centerX = extents.IsEmpty ? 0 : (extents.MinX + extents.MaxX) / 2;
+ var centerY = extents.IsEmpty ? 0 : (extents.MinY + extents.MaxY) / 2;
+ var pageWidth = pageWidthMm * unitsPerMm;
+ var pageHeight = pageHeightMm * unitsPerMm;
+ return new PageLayout(
+ (float)pageWidth, (float)pageHeight, unitsPerMm, scale,
+ pageWidth / 2 - centerX * scale,
+ pageHeight / 2 + centerY * scale);
+ }
+
+ /// <summary>Extents size with degenerate cases (a point, a horizontal line) given some room.</summary>
+ private static (double Width, double Height) Size(Box2 extents)
+ {
+ var width = extents.Width;
+ var height = extents.Height;
+ var size = Math.Max(width, height);
+ if (size <= 0)
+ return (1, 1);
+ return (Math.Max(width, size * 1e-3), Math.Max(height, size * 1e-3));
+ }
+}
+
+/// <summary>Renders scenes to PDF, SVG and bitmaps.</summary>
+internal static class CadRenderer
+{
+ /// <summary>Dash patterns shorter than this on paper are drawn as continuous lines (they would look solid anyway).</summary>
+ private const double MinDashPatternMm = 0.8;
+
+ /// <summary>Upper bound for dashes of one figure; beyond it the line is drawn continuous.</summary>
+ private const int MaxDashesPerFigure = 20_000;
+
+ /// <summary>Writes a one-page vector PDF.</summary>
+ public static void WritePdf(CadScene scene, PdfOptions options, string title, Stream output)
+ {
+ var page = PageLayout.ForPdf(scene.Extents, options);
+ var metadata = new SKDocumentPdfMetadata
+ {
+ Title = title,
+ Creator = "Filee",
+ Producer = "Filee (SkiaSharp)",
+ RasterDpi = 300,
+ Creation = DateTime.Now,
+ Modified = DateTime.Now,
+ };
+ using var document = SKDocument.CreatePdf(output, metadata);
+ var canvas = document.BeginPage(page.Width, page.Height);
+ Draw(canvas, scene, page, background: false);
+ document.EndPage();
+ document.Close();
+ }
+
+ /// <summary>Writes an SVG (pixel units at 96 dpi) with a white background.</summary>
+ public static void WriteSvg(CadScene scene, Stream output)
+ {
+ var page = PageLayout.ForImage(scene.Extents, 96 / 25.4);
+ // The SVG canvas writes its XML when disposed; the stream must stay open until then.
+ using (var canvas = SKSvgCanvas.Create(new SKRect(0, 0, page.Width, page.Height), output))
+ Draw(canvas, scene, page, background: true);
+ output.Flush();
+ }
+
+ /// <summary>
+ /// Renders a white-background bitmap at <paramref name="dpi"/> (for the virtual A3 page), limited to a
+ /// sensible pixel count.
+ /// </summary>
+ public static SKBitmap RenderBitmap(CadScene scene, double dpi)
+ {
+ const double MaxEdge = 12_000;
+ const double MaxPixels = 80_000_000;
+ var page = PageLayout.ForImage(scene.Extents, dpi / 25.4);
+ var reduce = Math.Min(1, Math.Min(MaxEdge / Math.Max(page.Width, page.Height), Math.Sqrt(MaxPixels / ((double)page.Width * page.Height))));
+ if (reduce < 1)
+ page = PageLayout.ForImage(scene.Extents, dpi * reduce / 25.4);
+
+ var bitmap = new SKBitmap(new SKImageInfo(Math.Max(1, (int)Math.Round(page.Width)), Math.Max(1, (int)Math.Round(page.Height)), SKColorType.Rgba8888, SKAlphaType.Premul));
+ using var canvas = new SKCanvas(bitmap);
+ Draw(canvas, scene, page, background: true);
+ canvas.Flush();
+ return bitmap;
+ }
+
+ /// <summary>Draws every primitive in order. Consecutive strokes with the same pen are merged into one path.</summary>
+ public static void Draw(SKCanvas canvas, CadScene scene, PageLayout page, bool background)
+ {
+ if (background)
+ {
+ using var white = new SKPaint { Color = SKColors.White, Style = SKPaintStyle.Fill };
+ canvas.DrawRect(0, 0, page.Width, page.Height, white);
+ }
+
+ using var batch = new StrokeBatch(canvas);
+ foreach (var item in scene.Items)
+ {
+ switch (item)
+ {
+ case StrokePrimitive stroke:
+ DrawStroke(batch, stroke, page);
+ break;
+ case InfiniteLinePrimitive line:
+ DrawInfinite(batch, line, page);
+ break;
+ case FillPrimitive fill:
+ batch.Flush();
+ DrawFill(canvas, fill, page);
+ break;
+ case HatchLinesPrimitive hatch:
+ batch.Flush();
+ DrawHatchLines(canvas, hatch, page);
+ break;
+ case TextPrimitive text:
+ batch.Flush();
+ DrawText(canvas, text, page);
+ break;
+ case PointPrimitive point:
+ batch.Flush();
+ DrawPoint(canvas, point, page);
+ break;
+ }
+ }
+ batch.Flush();
+ }
+
+ private static void DrawStroke(StrokeBatch batch, StrokePrimitive stroke, PageLayout page)
+ {
+ var penWidth = stroke.WidthMm * page.UnitsPerMm;
+ var wide = stroke.WorldWidth > 0 && stroke.WorldWidth * page.Scale > penWidth;
+ var width = wide ? stroke.WorldWidth * page.Scale : penWidth;
+ using var path = new SKPath();
+ foreach (var figure in stroke.Figures)
+ AddFigure(path, figure, page);
+ var dashes = PageDashes(stroke.Dashes, page);
+ if (dashes is null)
+ {
+ batch.Add(path, stroke.Color, (float)width, wide);
+ return;
+ }
+ using var dashed = Dash(path, dashes);
+ batch.Add(dashed ?? path, stroke.Color, (float)width, wide);
+ }
+
+ private static void DrawInfinite(StrokeBatch batch, InfiniteLinePrimitive line, PageLayout page)
+ {
+ // Clip to the page: the lines only need to reach its corners.
+ var corners = new[] { page.FromPage(0, 0), page.FromPage(page.Width, 0), page.FromPage(0, page.Height), page.FromPage(page.Width, page.Height) };
+ var tMax = corners.Max(c => Vec2.Dot(c - line.Origin, line.Direction));
+ var tMin = line.IsRay ? 0 : corners.Min(c => Vec2.Dot(c - line.Origin, line.Direction));
+ if (tMax <= tMin)
+ return;
+ var figure = new Figure(line.Origin + line.Direction * tMin);
+ figure.LineTo(line.Origin + line.Direction * tMax);
+ DrawStroke(batch, new StrokePrimitive { Color = line.Color, WidthMm = line.WidthMm, Dashes = line.Dashes, Figures = { figure } }, page);
+ }
+
+ private static void DrawFill(SKCanvas canvas, FillPrimitive fill, PageLayout page)
+ {
+ using var path = new SKPath { FillType = SKPathFillType.EvenOdd };
+ foreach (var figure in fill.Figures)
+ AddFigure(path, figure, page, close: true);
+ using var paint = new SKPaint { Color = fill.Color, Style = SKPaintStyle.Fill, IsAntialias = true };
+ if (fill.GradientColor is { } second)
+ {
+ var bounds = path.Bounds;
+ var (sin, cos) = Math.SinCos(fill.GradientAngle);
+ var half = (float)(Math.Abs(cos) * bounds.Width + Math.Abs(sin) * bounds.Height) / 2;
+ var direction = new SKPoint((float)cos * half, (float)-sin * half);
+ paint.Shader = SKShader.CreateLinearGradient(
+ new SKPoint(bounds.MidX - direction.X, bounds.MidY - direction.Y),
+ new SKPoint(bounds.MidX + direction.X, bounds.MidY + direction.Y),
+ [fill.Color, second], SKShaderTileMode.Clamp);
+ }
+ canvas.DrawPath(path, paint);
+ }
+
+ private static void DrawHatchLines(SKCanvas canvas, HatchLinesPrimitive hatch, PageLayout page)
+ {
+ using var clip = new SKPath { FillType = SKPathFillType.EvenOdd };
+ foreach (var figure in hatch.Boundary)
+ AddFigure(clip, figure, page, close: true);
+ using var lines = new SKPath();
+ foreach (var (a, b) in hatch.Lines)
+ {
+ lines.MoveTo(page.Point(a));
+ lines.LineTo(page.Point(b));
+ }
+ using var paint = Pen(hatch.Color, (float)(hatch.WidthMm * page.UnitsPerMm), wide: false);
+ canvas.Save();
+ canvas.ClipPath(clip, SKClipOperation.Intersect, antialias: true);
+ canvas.DrawPath(lines, paint);
+ canvas.Restore();
+ }
+
+ private static void DrawText(SKCanvas canvas, TextPrimitive text, PageLayout page)
+ {
+ var origin = page.ToPage(text.Origin);
+ var x = page.VectorToPage(text.XAxis);
+ var y = page.VectorToPage(text.YAxis);
+ // Draw at a font size equal to the em height on the page and put only the direction into the matrix:
+ // PDF and SVG viewers handle normal font sizes better than tiny ones blown up by a transform.
+ var size = y.Length;
+ if (size < 0.01 || !double.IsFinite(size) || size > 1e6)
+ return;
+ var matrix = new SKMatrix(
+ (float)(x.X / size), (float)(y.X / size), (float)origin.X,
+ (float)(x.Y / size), (float)(y.Y / size), (float)origin.Y,
+ 0, 0, 1);
+ using var font = CadFonts.CreateFont(text.Typeface, (float)size);
+ using var paint = new SKPaint { Color = text.Color, IsAntialias = true, Style = SKPaintStyle.Fill };
+ canvas.Save();
+ canvas.Concat(in matrix);
+ canvas.DrawText(text.Text, 0, 0, font, paint);
+ canvas.Restore();
+ }
+
+ private static void DrawPoint(SKCanvas canvas, PointPrimitive point, PageLayout page)
+ {
+ var radius = (float)Math.Max(point.WidthMm * page.UnitsPerMm, 0.3 * page.UnitsPerMm) / 2;
+ using var paint = new SKPaint { Color = point.Color, IsAntialias = true, Style = SKPaintStyle.Fill };
+ canvas.DrawCircle(page.Point(point.Location), radius, paint);
+ }
+
+ private static void AddFigure(SKPath path, Figure figure, PageLayout page, bool close = false)
+ {
+ path.MoveTo(page.Point(figure.Start));
+ if (figure.Segments.Count == 0)
+ {
+ path.LineTo(page.Point(figure.Start)); // zero-length: a dot with round caps
+ return;
+ }
+ foreach (var segment in figure.Segments)
+ {
+ if (segment.IsCubic)
+ path.CubicTo(page.Point(segment.C1), page.Point(segment.C2), page.Point(segment.P));
+ else
+ path.LineTo(page.Point(segment.P));
+ }
+ if (figure.Closed || close)
+ path.Close();
+ }
+
+ /// <summary>The dash pattern in page units, or null to draw a continuous line.</summary>
+ private static float[]? PageDashes(double[]? dashes, PageLayout page)
+ {
+ if (dashes is null)
+ return null;
+ var scaled = dashes.Select(d => (float)(d * page.Scale)).ToArray();
+ var period = scaled.Sum(Math.Abs);
+ if (!float.IsFinite(period) || period < MinDashPatternMm * page.UnitsPerMm)
+ return null;
+ return scaled;
+ }
+
+ /// <summary>
+ /// Applies a dash pattern by cutting the path into pieces. Doing it here (not with a path effect) gives PDF,
+ /// SVG and bitmaps the same result. Returns null when the pattern would create too many pieces.
+ /// </summary>
+ private static SKPath? Dash(SKPath source, float[] pattern)
+ {
+ var period = pattern.Sum(Math.Abs);
+ var result = new SKPath();
+ using var measure = new SKPathMeasure(source, false, 1);
+ do
+ {
+ var length = measure.Length;
+ if (length <= 0)
+ continue;
+ if (length / period * pattern.Length > MaxDashesPerFigure)
+ {
+ result.Dispose();
+ return null;
+ }
+ var position = 0f;
+ var index = 0;
+ while (position < length)
+ {
+ var element = pattern[index];
+ if (element > 0)
+ {
+ measure.GetSegment(position, Math.Min(position + element, length), result, true);
+ }
+ else if (element == 0 && measure.GetPosition(position, out var dot))
+ {
+ result.MoveTo(dot);
+ result.LineTo(dot);
+ }
+ position += Math.Abs(element);
+ index = (index + 1) % pattern.Length;
+ }
+ }
+ while (measure.NextContour());
+ return result;
+ }
+
+ private static SKPaint Pen(SKColor color, float width, bool wide) => new()
+ {
+ Color = color,
+ Style = SKPaintStyle.Stroke,
+ StrokeWidth = width,
+ IsAntialias = true,
+ // Line weights plot with round ends; wide polylines have square ends and mitred corners like in AutoCAD.
+ StrokeCap = wide ? SKStrokeCap.Butt : SKStrokeCap.Round,
+ StrokeJoin = wide ? SKStrokeJoin.Miter : SKStrokeJoin.Round,
+ };
+
+ /// <summary>
+ /// Merges consecutive strokes with the same colour and width into one path (smaller PDF / SVG, faster), up to
+ /// a size that keeps viewers and the SVG writer responsive.
+ /// </summary>
+ private sealed class StrokeBatch(SKCanvas canvas) : IDisposable
+ {
+ private const int MaxPoints = 4096;
+
+ private readonly SKPath _path = new();
+ private SKColor _color;
+ private float _width;
+ private bool _wide;
+ private bool _empty = true;
+
+ public void Add(SKPath path, SKColor color, float width, bool wide)
+ {
+ if (!_empty && (color != _color || width != _width || wide != _wide || _path.PointCount > MaxPoints))
+ Flush();
+ _color = color;
+ _width = width;
+ _wide = wide;
+ _path.AddPath(path);
+ _empty = false;
+ }
+
+ public void Flush()
+ {
+ if (_empty)
+ return;
+ using var paint = Pen(_color, _width, _wide);
+ canvas.DrawPath(_path, paint);
+ _path.Reset();
+ _empty = true;
+ }
+
+ public void Dispose() => _path.Dispose();
+ }
+}
diff --git a/src/Filee.Engines/Cad/CadScene.cs b/src/Filee.Engines/Cad/CadScene.cs
new file mode 100644
index 00000000..4dba8c0d
--- /dev/null
+++ b/src/Filee.Engines/Cad/CadScene.cs
@@ -0,0 +1,98 @@
+// The display list the CAD renderer draws. The scene builder resolves layers, colours, line weights, line types and
+// block transforms once; the result is plain geometry in WCS, so one drawing routine serves PDF, SVG and PNG and
+// the page is fitted to what is actually drawn (not to the header's EXTMIN/EXTMAX).
+
+using SkiaSharp;
+
+namespace Filee.Engines.Cad;
+
+/// <summary>Something to draw, in a resolved colour.</summary>
+internal abstract class ScenePrimitive
+{
+ public SKColor Color { get; init; }
+}
+
+/// <summary>Stroked figures: lines, arcs, polylines, curves, text-less outlines.</summary>
+internal sealed class StrokePrimitive : ScenePrimitive
+{
+ public List<Figure> Figures { get; } = [];
+
+ /// <summary>Line weight on paper in millimetres.</summary>
+ public double WidthMm { get; init; }
+
+ /// <summary>
+ /// Width in drawing units for polylines with a constant width (drawn with butt caps); 0 for normal lines,
+ /// which use <see cref="WidthMm"/>.
+ /// </summary>
+ public double WorldWidth { get; init; }
+
+ /// <summary>Dash pattern in drawing units (&gt;0 dash, &lt;0 gap, 0 dot); null for continuous lines.</summary>
+ public double[]? Dashes { get; init; }
+}
+
+/// <summary>Filled areas: solid hatches, SOLID/TRACE, wide polyline segments. Loops use the even-odd rule.</summary>
+internal sealed class FillPrimitive : ScenePrimitive
+{
+ public List<Figure> Figures { get; } = [];
+
+ /// <summary>Second colour of a gradient hatch, drawn as a linear gradient along <see cref="GradientAngle"/>.</summary>
+ public SKColor? GradientColor { get; init; }
+
+ public double GradientAngle { get; init; }
+}
+
+/// <summary>Pattern hatch lines, clipped by the hatch boundary when drawn.</summary>
+internal sealed class HatchLinesPrimitive : ScenePrimitive
+{
+ public List<Figure> Boundary { get; } = [];
+ public List<(Vec2 A, Vec2 B)> Lines { get; } = [];
+ public double WidthMm { get; init; }
+}
+
+/// <summary>
+/// One run of text in one typeface. Glyph coordinates at font size 1 (Skia convention, y down) map to WCS as
+/// <c>Origin + gx·XAxis + gy·YAxis</c>, which covers rotation, width factor, oblique angle and mirrored blocks.
+/// </summary>
+internal sealed class TextPrimitive : ScenePrimitive
+{
+ public required string Text { get; init; }
+ public required SKTypeface Typeface { get; init; }
+ public Vec2 Origin { get; init; }
+ public Vec2 XAxis { get; init; }
+ public Vec2 YAxis { get; init; }
+}
+
+/// <summary>XLINE and RAY: clipped to the page when drawn.</summary>
+internal sealed class InfiniteLinePrimitive : ScenePrimitive
+{
+ public Vec2 Origin { get; init; }
+ public Vec2 Direction { get; init; }
+ public bool IsRay { get; init; }
+ public double WidthMm { get; init; }
+ public double[]? Dashes { get; init; }
+}
+
+/// <summary>A POINT, drawn as a dot of its line weight.</summary>
+internal sealed class PointPrimitive : ScenePrimitive
+{
+ public Vec2 Location { get; init; }
+ public double WidthMm { get; init; }
+}
+
+/// <summary>Everything to draw plus what was left out.</summary>
+internal sealed class CadScene
+{
+ public List<ScenePrimitive> Items { get; } = [];
+
+ /// <summary>Bounds of all finite primitives in WCS.</summary>
+ public Box2 Extents = Box2.Empty;
+
+ /// <summary>Entity types that were not drawn, with their count (for the log).</summary>
+ public SortedDictionary<string, int> Skipped { get; } = new(StringComparer.Ordinal);
+
+ /// <summary>True when a limit (primitive count, block nesting, array size) cut the drawing short.</summary>
+ public bool Truncated { get; set; }
+
+ /// <summary>Which space was drawn: "model" or the layout name.</summary>
+ public string Space { get; set; } = "model";
+}
diff --git a/src/Filee.Engines/Cad/CadSceneBuilder.Hatch.cs b/src/Filee.Engines/Cad/CadSceneBuilder.Hatch.cs
new file mode 100644
index 00000000..25db1e55
--- /dev/null
+++ b/src/Filee.Engines/Cad/CadSceneBuilder.Hatch.cs
@@ -0,0 +1,254 @@
+// HATCH for the CAD scene: boundary loops (lines, arcs, ellipses, splines, polylines) become even-odd filled paths;
+// pattern hatches draw their pattern lines clipped to the boundary, or a light fill when the pattern is too dense.
+
+using ACadSharp.Entities;
+using ACadSharp.Tables;
+using SkiaSharp;
+
+namespace Filee.Engines.Cad;
+
+internal sealed partial class CadSceneBuilder
+{
+ /// <summary>Pattern segments allowed for one hatch; denser patterns are shown as a light fill instead.</summary>
+ private const int MaxPatternSegmentsPerHatch = 20_000;
+
+ /// <summary>Pattern segments allowed for the whole drawing.</summary>
+ private const int MaxPatternSegments = 2_000_000;
+
+ private int _patternSegments;
+
+ private void DrawHatch(Hatch hatch, Layer layer, DrawContext context)
+ {
+ var loops = new List<Figure>();
+ foreach (var path in hatch.Paths)
+ if (Loop(path) is { } loop)
+ loops.Add(loop);
+ if (loops.Count == 0)
+ return;
+
+ var plane = context.Transform
+ .Multiply(Affine3.Ocs(hatch.Normal))
+ .Multiply(Affine3.Translation(new Vec3(0, 0, hatch.Elevation)));
+ var boundary = loops.Select(loop => Map(loop, plane)).ToList();
+ var color = ResolveColor(hatch, layer, context);
+
+ if (hatch.IsSolid)
+ {
+ var gradient = hatch.GradientColor;
+ SKColor? second = null;
+ if (gradient is { Enabled: true, Colors.Count: > 0 })
+ {
+ color = ResolveColor(gradient.Colors[0].Color, layer, context);
+ second = gradient.Colors.Count > 1 ? ResolveColor(gradient.Colors[1].Color, layer, context) : Blend(color, SKColors.White, 0.8);
+ }
+ var fill = new FillPrimitive { Color = color, GradientColor = second, GradientAngle = gradient?.Angle ?? 0 };
+ fill.Figures.AddRange(boundary);
+ AddFill(fill);
+ return;
+ }
+
+ var box = Box2.Empty;
+ foreach (var loop in loops)
+ loop.AddTo(ref box);
+ var lines = hatch.Pattern is { Lines.Count: > 0 } pattern && _patternSegments < MaxPatternSegments
+ ? PatternLines(pattern, box)
+ : null;
+ if (lines is null)
+ {
+ // Too dense (or no pattern data): a light tint of the hatch colour keeps the area recognisable.
+ var tint = new FillPrimitive { Color = Blend(color, SKColors.White, 0.75) };
+ tint.Figures.AddRange(boundary);
+ AddFill(tint);
+ return;
+ }
+
+ _patternSegments += lines.Count;
+ var primitive = new HatchLinesPrimitive { Color = color, WidthMm = Math.Min(ResolveWidth(hatch, layer, context), DefaultLineWeightMm) };
+ primitive.Boundary.AddRange(boundary);
+ primitive.Lines.AddRange(lines.Select(l => (plane.Point(l.A.X, l.A.Y), plane.Point(l.B.X, l.B.Y))));
+ if (Reserve())
+ {
+ foreach (var figure in boundary)
+ figure.AddTo(ref _scene.Extents);
+ _scene.Items.Add(primitive);
+ }
+ }
+
+ /// <summary>One boundary loop in the hatch's OCS plane.</summary>
+ private static Figure? Loop(Hatch.BoundaryPath path)
+ {
+ Figure? figure = null;
+ foreach (var edge in path.Edges)
+ {
+ switch (edge)
+ {
+ case Hatch.BoundaryPath.Line line:
+ MoveOrLine(new Vec2(line.Start.X, line.Start.Y));
+ figure!.LineTo(new Vec2(line.End.X, line.End.Y));
+ break;
+ case Hatch.BoundaryPath.Arc arc:
+ {
+ var r = arc.Radius;
+ EdgeArc(new Vec2(arc.Center.X, arc.Center.Y), new Vec2(r, 0), new Vec2(0, r), arc.StartAngle, arc.EndAngle, arc.CounterClockWise);
+ break;
+ }
+ case Hatch.BoundaryPath.Ellipse ellipse:
+ {
+ var major = new Vec2(ellipse.MajorAxisEndPoint.X, ellipse.MajorAxisEndPoint.Y);
+ EdgeArc(new Vec2(ellipse.Center.X, ellipse.Center.Y), major, major.Perp * ellipse.RadiusRatio,
+ ellipse.StartAngle, ellipse.EndAngle, ellipse.CounterClockWise);
+ break;
+ }
+ case Hatch.BoundaryPath.Spline spline:
+ {
+ // Rational spline edges keep each weight in the control point's Z.
+ var points = spline.ControlPoints.Count >= 2
+ ? CadCurves.SampleNurbs(spline.Degree, spline.ControlPoints.Select(c => new Vec3(c.X, c.Y, 0)).ToList(), spline.Knots,
+ spline.IsRational ? spline.ControlPoints.Select(c => c.Z).ToList() : null)
+ : CadCurves.ThroughPoints(spline.FitPoints.Select(p => new Vec3(p.X, p.Y, 0)).ToList(), closed: false);
+ foreach (var point in points)
+ MoveOrLine(new Vec2(point.X, point.Y));
+ break;
+ }
+ case Hatch.BoundaryPath.Polyline polyline:
+ {
+ var vertices = polyline.Vertices;
+ if (vertices.Count == 0)
+ break;
+ MoveOrLine(new Vec2(vertices[0].X, vertices[0].Y));
+ var count = polyline.IsClosed ? vertices.Count : vertices.Count - 1;
+ for (var i = 0; i < count; i++)
+ {
+ var a = vertices[i];
+ var b = vertices[(i + 1) % vertices.Count];
+ AppendSegment(figure!, Affine3.Identity, new PolyVertex(new Vec2(a.X, a.Y), a.Z, 0, 0), new PolyVertex(new Vec2(b.X, b.Y), b.Z, 0, 0));
+ }
+ break;
+ }
+ }
+ }
+ if (figure is null || figure.Segments.Count == 0)
+ return null;
+ figure.Closed = true;
+ return figure;
+
+ void MoveOrLine(Vec2 p)
+ {
+ if (figure is null)
+ figure = new Figure(p);
+ else if ((figure.End - p).Length > 1e-9)
+ figure.LineTo(p);
+ }
+
+ // Clockwise edges store their angles mirrored at the X axis: the arc runs from -start to -end.
+ void EdgeArc(Vec2 center, Vec2 u, Vec2 v, double start, double end, bool counterClockwise)
+ {
+ double t0, t1;
+ if (counterClockwise)
+ {
+ (t0, t1) = (start, end);
+ while (t1 <= t0)
+ t1 += 2 * Math.PI;
+ }
+ else
+ {
+ (t0, t1) = (-start, -end);
+ while (t1 >= t0)
+ t1 -= 2 * Math.PI;
+ }
+ MoveOrLine(center + u * Math.Cos(t0) + v * Math.Sin(t0));
+ figure!.ArcTo(center, u, v, t0, t1);
+ }
+ }
+
+ /// <summary>
+ /// The pattern's line families across the boundary's bounding box (in the hatch plane). Each family repeats
+ /// every <c>Offset</c>; dashes start at the family's base point. Returns null when the pattern is too dense.
+ /// </summary>
+ private static List<(Vec2 A, Vec2 B)>? PatternLines(HatchPattern pattern, Box2 box)
+ {
+ var result = new List<(Vec2 A, Vec2 B)>();
+ Vec2[] corners = [new(box.MinX, box.MinY), new(box.MaxX, box.MinY), new(box.MinX, box.MaxY), new(box.MaxX, box.MaxY)];
+ var size = Math.Max(Math.Max(box.Width, box.Height), 1e-9);
+
+ foreach (var line in pattern.Lines)
+ {
+ var d = new Vec2(Math.Cos(line.Angle), Math.Sin(line.Angle));
+ var n = d.Perp;
+ var basePoint = new Vec2(line.BasePoint.X, line.BasePoint.Y);
+ var offset = new Vec2(line.Offset.X, line.Offset.Y);
+ var spacing = Vec2.Dot(offset, n);
+ var c0 = Vec2.Dot(basePoint, n);
+ var low = corners.Min(c => Vec2.Dot(c, n));
+ var high = corners.Max(c => Vec2.Dot(c, n));
+
+ long first, last;
+ if (Math.Abs(spacing) < size * 1e-9)
+ {
+ if (c0 < low || c0 > high)
+ continue;
+ first = last = 0;
+ }
+ else
+ {
+ var k1 = (low - c0) / spacing;
+ var k2 = (high - c0) / spacing;
+ first = (long)Math.Floor(Math.Min(k1, k2));
+ last = (long)Math.Ceiling(Math.Max(k1, k2));
+ }
+ if (last - first > MaxPatternSegmentsPerHatch)
+ return null;
+
+ var dashes = line.DashLengths.Where(double.IsFinite).ToArray();
+ var period = dashes.Sum(Math.Abs);
+ for (var k = first; k <= last; k++)
+ {
+ var origin = basePoint + offset * k;
+ var tMin = corners.Min(c => Vec2.Dot(c - origin, d));
+ var tMax = corners.Max(c => Vec2.Dot(c - origin, d));
+ if (dashes.Length == 0 || period <= 0 || dashes.All(x => x > 0))
+ {
+ result.Add((origin + d * tMin, origin + d * tMax));
+ }
+ else
+ {
+ if ((tMax - tMin) / period * dashes.Length + result.Count > MaxPatternSegmentsPerHatch)
+ return null;
+ for (var t = Math.Floor(tMin / period) * period; t < tMax;)
+ {
+ foreach (var dash in dashes)
+ {
+ if (dash > 0 && t + dash > tMin && t < tMax)
+ result.Add((origin + d * Math.Max(t, tMin), origin + d * Math.Min(t + dash, tMax)));
+ else if (dash == 0 && t >= tMin && t <= tMax)
+ result.Add((origin + d * t, origin + d * t));
+ t += Math.Abs(dash);
+ }
+ }
+ }
+ if (result.Count > MaxPatternSegmentsPerHatch)
+ return null;
+ }
+ }
+ return result;
+ }
+
+ /// <summary>A figure built in a plane's own coordinates, mapped to WCS (exact for the Bézier arcs).</summary>
+ private static Figure Map(Figure local, Affine3 plane)
+ {
+ var mapped = new Figure(plane.Point(local.Start.X, local.Start.Y)) { Closed = local.Closed };
+ foreach (var s in local.Segments)
+ {
+ var p = plane.Point(s.P.X, s.P.Y);
+ mapped.Segments.Add(s.IsCubic
+ ? Segment.Cubic(plane.Point(s.C1.X, s.C1.Y), plane.Point(s.C2.X, s.C2.Y), p)
+ : Segment.Line(p));
+ }
+ return mapped;
+ }
+
+ private static SKColor Blend(SKColor color, SKColor toward, double amount) => new(
+ (byte)(color.Red + (toward.Red - color.Red) * amount),
+ (byte)(color.Green + (toward.Green - color.Green) * amount),
+ (byte)(color.Blue + (toward.Blue - color.Blue) * amount));
+}
diff --git a/src/Filee.Engines/Cad/CadSceneBuilder.Text.cs b/src/Filee.Engines/Cad/CadSceneBuilder.Text.cs
new file mode 100644
index 00000000..b5c1925d
--- /dev/null
+++ b/src/Filee.Engines/Cad/CadSceneBuilder.Text.cs
@@ -0,0 +1,312 @@
+// TEXT, ATTRIB and MTEXT for the CAD scene: justification, rotation, width factor, oblique angle, mirroring, and
+// MTEXT formatting codes with word wrap. Text is measured with the typeface it is drawn with (see CadFonts).
+
+using ACadSharp.Entities;
+using ACadSharp.Tables;
+using SkiaSharp;
+
+namespace Filee.Engines.Cad;
+
+internal sealed partial class CadSceneBuilder
+{
+ /// <summary>AutoCAD's MTEXT line pitch: 5/3 of the text height at line spacing factor 1.</summary>
+ private const double LinePitch = 5.0 / 3.0;
+
+ /// <summary>Top of the text box above the baseline for extents, in em (covers accents and CJK glyphs).</summary>
+ private const double AscentEm = 0.95;
+
+ private void DrawText(TextEntity text, string? value, Layer layer, DrawContext context)
+ {
+ var content = CadTextCodes.DecodeText(value);
+ if (content.Trim().Length == 0)
+ return;
+
+ var style = text.Style;
+ var height = text.Height > 0 ? text.Height : style?.Height > 0 ? style.Height : 2.5;
+ var typeface = TypefaceOf(style, null, false, false);
+ var (capHeight, descent) = CadFonts.Metrics(typeface);
+ var em = height / capHeight;
+ var widthFactor = text.WidthFactor > 0 ? text.WidthFactor : 1;
+ var runs = CadFonts.Layout(content, typeface);
+ var width = runs.Sum(r => r.Advance) * em * widthFactor;
+
+ // Justified text is positioned by its second alignment point; "aligned" and "fit" stretch between both.
+ var horizontal = text.HorizontalAlignment;
+ var vertical = text.VerticalAlignment;
+ var justified = horizontal != TextHorizontalAlignment.Left || vertical != TextVerticalAlignmentType.Baseline;
+ Vec3 anchor = justified ? text.AlignmentPoint : text.InsertPoint;
+ var rotation = text.Rotation;
+ if (horizontal is TextHorizontalAlignment.Aligned or TextHorizontalAlignment.Fit && width > 0)
+ {
+ Vec3 first = text.InsertPoint;
+ var span = (Vec3)text.AlignmentPoint - first;
+ var length = Math.Sqrt(span.X * span.X + span.Y * span.Y);
+ if (length > 1e-12)
+ {
+ anchor = first;
+ rotation = Math.Atan2(span.Y, span.X);
+ if (horizontal == TextHorizontalAlignment.Aligned)
+ {
+ em *= length / width;
+ height *= length / width;
+ }
+ else
+ {
+ widthFactor *= length / width;
+ }
+ width = length;
+ }
+ }
+
+ var x = horizontal switch
+ {
+ TextHorizontalAlignment.Center or TextHorizontalAlignment.Middle => -width / 2,
+ TextHorizontalAlignment.Right => -width,
+ _ => 0,
+ };
+ var y = horizontal == TextHorizontalAlignment.Middle ? -height / 2 : vertical switch
+ {
+ TextVerticalAlignmentType.Bottom => descent * em,
+ TextVerticalAlignmentType.Middle => -height / 2,
+ TextVerticalAlignmentType.Top => -height,
+ _ => 0.0,
+ };
+
+ // Mirrored text (MIRRTEXT, "backward" / "upside down" styles) flips the glyph axes around the anchor.
+ var flipX = text.Mirror.HasFlag(TextMirrorFlag.Backward) ? -1 : 1;
+ var flipY = text.Mirror.HasFlag(TextMirrorFlag.UpsideDown) ? -1 : 1;
+ var frame = context.Transform
+ .Multiply(Affine3.Ocs(text.Normal))
+ .Multiply(Affine3.Translation(anchor))
+ .Multiply(Affine3.RotationZ(rotation))
+ .Multiply(Affine3.Scale(flipX, flipY, 1));
+
+ var color = ResolveColor(text, layer, context);
+ EmitLine(runs, frame, x, y, em, widthFactor, text.ObliqueAngle, color);
+ }
+
+ private void DrawMText(MText mtext, Layer layer, DrawContext context)
+ {
+ var style = mtext.Style;
+ var height = mtext.Height > 0 ? mtext.Height : style?.Height > 0 ? style.Height : 2.5;
+ DrawMTextCore(mtext.Value, mtext.InsertPoint, mtext.AlignmentPoint, mtext.Normal, height, mtext.RectangleWidth,
+ mtext.AttachmentPoint, mtext.LineSpacing, style, ResolveColor(mtext, layer, context), context);
+ }
+
+ /// <summary>One placed piece of an MTEXT line.</summary>
+ private readonly record struct Piece(string Text, MTextFormat Format, double Width);
+
+ /// <summary>
+ /// Lays out MTEXT: paragraphs are word-wrapped at <paramref name="wrapWidth"/> (CJK text breaks between
+ /// characters), lines are stacked with AutoCAD's line pitch and the block is placed by its attachment point.
+ /// </summary>
+ private void DrawMTextCore(string? value, Vec3 insert, Vec3 direction, Vec3 normal, double height, double wrapWidth,
+ AttachmentPointType attachment, double lineSpacing, TextStyle? style, SKColor color, DrawContext context)
+ {
+ if (string.IsNullOrEmpty(value))
+ return;
+ var styleFlags = style?.TrueType ?? FontFlags.Regular;
+ var initial = new MTextFormat(
+ height,
+ ColorIndex: null,
+ TrueColor: null,
+ FontFamily: null,
+ Bold: styleFlags.HasFlag(FontFlags.Bold),
+ Italic: styleFlags.HasFlag(FontFlags.Italic),
+ WidthFactor: style?.Width > 0 ? style.Width : 1,
+ ObliqueDegrees: style is null ? 0 : style.ObliqueAngle * 180 / Math.PI);
+ var paragraphs = CadTextCodes.ParseMText(value, initial);
+
+ var limit = wrapWidth > 0 ? wrapWidth : double.PositiveInfinity;
+ var lines = new List<List<Piece>>();
+ foreach (var paragraph in paragraphs)
+ WrapParagraph(paragraph, limit, style, lines);
+ if (lines.All(line => line.All(p => p.Text.Trim().Length == 0)))
+ return;
+
+ // Baselines from the top: the first line's caps touch the top, then one pitch per line.
+ var baselines = new double[lines.Count];
+ var y = 0.0;
+ var spacing = lineSpacing > 0 ? lineSpacing : 1;
+ for (var i = 0; i < lines.Count; i++)
+ {
+ var lineHeight = lines[i].Count == 0 ? height : lines[i].Max(p => p.Format.Height);
+ y -= i == 0 ? lineHeight : lineHeight * LinePitch * spacing;
+ baselines[i] = y;
+ }
+ var totalHeight = -y;
+ var shiftY = attachment switch
+ {
+ AttachmentPointType.MiddleLeft or AttachmentPointType.MiddleCenter or AttachmentPointType.MiddleRight => totalHeight / 2,
+ AttachmentPointType.BottomLeft or AttachmentPointType.BottomCenter or AttachmentPointType.BottomRight => totalHeight,
+ _ => 0,
+ };
+
+ // MTEXT's direction vector is in WCS; a zero vector means the OCS X axis.
+ var ocs = Affine3.Ocs(normal);
+ var xAxis = direction.Length > 1e-12 ? direction.Normalized() : ocs.X;
+ var zAxis = ocs.Z;
+ var yAxis = Vec3.Cross(zAxis, xAxis).Normalized();
+ var frame = context.Transform.Multiply(new Affine3(xAxis, yAxis, zAxis, insert));
+
+ for (var i = 0; i < lines.Count; i++)
+ {
+ var line = TrimEnd(lines[i]);
+ var lineWidth = line.Sum(p => p.Width);
+ var x = attachment switch
+ {
+ AttachmentPointType.TopCenter or AttachmentPointType.MiddleCenter or AttachmentPointType.BottomCenter => -lineWidth / 2,
+ AttachmentPointType.TopRight or AttachmentPointType.MiddleRight or AttachmentPointType.BottomRight => -lineWidth,
+ _ => 0,
+ };
+ foreach (var piece in line)
+ {
+ var format = piece.Format;
+ var typeface = TypefaceOf(style, format.FontFamily, format.Bold, format.Italic);
+ var em = format.Height / CadFonts.Metrics(typeface).CapHeight;
+ var pieceColor = format.TrueColor is { } rgb
+ ? new SKColor((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb)
+ : format.ColorIndex is { } index and not 256
+ ? index == 0 ? context.BlockColor : ResolveColor(new ACadSharp.Color(index), Layer.Default, context)
+ : color;
+ EmitLine(CadFonts.Layout(piece.Text, typeface), frame, x, baselines[i] + shiftY, em, format.WidthFactor,
+ format.ObliqueDegrees * Math.PI / 180, pieceColor);
+ x += piece.Width;
+ }
+ }
+ }
+
+ /// <summary>Greedy word wrap of one paragraph into <paramref name="lines"/>.</summary>
+ private static void WrapParagraph(List<MTextRun> paragraph, double limit, TextStyle? style, List<List<Piece>> lines)
+ {
+ var line = new List<Piece>();
+ var width = 0.0;
+ foreach (var run in paragraph)
+ {
+ var typeface = TypefaceOf(style, run.Format.FontFamily, run.Format.Bold, run.Format.Italic);
+ var em = run.Format.Height / CadFonts.Metrics(typeface).CapHeight * run.Format.WidthFactor;
+ foreach (var word in Words(run.Text))
+ {
+ var wordWidth = CadFonts.Layout(word, typeface).Sum(r => r.Advance) * em;
+ var inkWidth = CadFonts.Layout(word.TrimEnd(), typeface).Sum(r => r.Advance) * em;
+ if (line.Count > 0 && width + inkWidth > limit)
+ {
+ lines.Add(line);
+ line = [];
+ width = 0;
+ if (word.Trim().Length == 0)
+ continue; // spaces at a line break disappear
+ }
+ line.Add(new Piece(word, run.Format, wordWidth));
+ width += wordWidth;
+ }
+ }
+ lines.Add(Merge(line));
+ }
+
+ /// <summary>Splits text into wrap units: words with their trailing spaces, and single CJK characters.</summary>
+ private static IEnumerable<string> Words(string text)
+ {
+ var start = 0;
+ for (var i = 0; i < text.Length; i++)
+ {
+ var ch = text[i];
+ if (IsCjk(ch))
+ {
+ if (i > start)
+ yield return text[start..i];
+ var end = i + 1;
+ while (end < text.Length && text[end] == ' ')
+ end++;
+ yield return text[i..end];
+ start = end;
+ i = end - 1;
+ }
+ else if (ch == ' ' && (i + 1 >= text.Length || text[i + 1] != ' '))
+ {
+ yield return text[start..(i + 1)];
+ start = i + 1;
+ }
+ }
+ if (start < text.Length)
+ yield return text[start..];
+ }
+
+ private static bool IsCjk(char ch) =>
+ ch is >= 'ᄀ' and <= 'ᇿ' or >= '⺀' and <= '鿿' or >= '가' and <= '힯' or >= '豈' and <= '﫿'
+ or >= '＀' and <= '￯';
+
+ /// <summary>Joins neighbouring pieces with the same format so each becomes one text run.</summary>
+ private static List<Piece> Merge(List<Piece> line)
+ {
+ var merged = new List<Piece>();
+ foreach (var piece in line)
+ {
+ if (merged.Count > 0 && merged[^1].Format == piece.Format)
+ merged[^1] = merged[^1] with { Text = merged[^1].Text + piece.Text, Width = merged[^1].Width + piece.Width };
+ else
+ merged.Add(piece);
+ }
+ return merged;
+ }
+
+ /// <summary>Drops trailing spaces so right and centre alignment use the visible width.</summary>
+ private static List<Piece> TrimEnd(List<Piece> line)
+ {
+ var result = Merge(line);
+ if (result.Count > 0)
+ {
+ var last = result[^1];
+ var trimmed = last.Text.TrimEnd();
+ if (trimmed.Length != last.Text.Length)
+ {
+ var ratio = last.Text.Length == 0 ? 0 : (double)trimmed.Length / last.Text.Length;
+ result[^1] = last with { Text = trimmed, Width = last.Width * ratio };
+ }
+ }
+ return result;
+ }
+
+ /// <summary>
+ /// Emits the runs of one text line with its baseline starting at (<paramref name="x"/>, <paramref name="y"/>)
+ /// in <paramref name="frame"/>'s XY plane.
+ /// </summary>
+ private void EmitLine(List<GlyphRun> runs, Affine3 frame, double x, double y, double em, double widthFactor, double oblique, SKColor color)
+ {
+ // Oblique angles are stored in [0, 2π): 345° leans left like -15°. Steeper than ±85° is not allowed.
+ var shear = Math.Tan(Math.Clamp(Math.IEEERemainder(oblique, 2 * Math.PI), -1.48, 1.48));
+ var xAxis = frame.Vector(em * widthFactor, 0);
+ var yAxis = frame.Vector(-em * shear, -em);
+ foreach (var run in runs)
+ {
+ var advance = run.Advance * em * widthFactor;
+ if (run.Text.Trim().Length > 0 && Reserve())
+ {
+ _scene.Items.Add(new TextPrimitive
+ {
+ Text = run.Text,
+ Typeface = run.Typeface,
+ Origin = frame.Point(x, y),
+ XAxis = xAxis,
+ YAxis = yAxis,
+ Color = color,
+ });
+ foreach (var rise in (ReadOnlySpan<double>)[-0.2 * em, AscentEm * em])
+ {
+ _scene.Extents.Add(frame.Point(x + rise * shear, y + rise));
+ _scene.Extents.Add(frame.Point(x + advance + rise * shear, y + rise));
+ }
+ }
+ x += advance;
+ }
+ }
+
+ /// <summary>The typeface of an MTEXT font code, else of the text style.</summary>
+ private static SKTypeface TypefaceOf(TextStyle? style, string? family, bool bold, bool italic)
+ {
+ if (family is not null)
+ return CadFonts.Resolve(family, bold, italic);
+ var flags = style?.TrueType ?? FontFlags.Regular;
+ return CadFonts.Resolve(style?.Filename, bold || flags.HasFlag(FontFlags.Bold), italic || flags.HasFlag(FontFlags.Italic));
+ }
+}
diff --git a/src/Filee.Engines/Cad/CadSceneBuilder.cs b/src/Filee.Engines/Cad/CadSceneBuilder.cs
new file mode 100644
index 00000000..57b440f4
--- /dev/null
+++ b/src/Filee.Engines/Cad/CadSceneBuilder.cs
@@ -0,0 +1,919 @@
+// Turns an ACadSharp document into a CadScene: walks model space (or the active layout when model space is
+// empty), resolves layers, colours, line weights and line types, expands block references and converts every
+// supported entity into geometry in WCS. Text and hatches live in the partial files next to this one.
+
+using ACadSharp;
+using ACadSharp.Entities;
+using ACadSharp.Tables;
+using SkiaSharp;
+using AcadColor = ACadSharp.Color;
+
+namespace Filee.Engines.Cad;
+
+/// <summary>Builds the display list of a drawing.</summary>
+internal sealed partial class CadSceneBuilder
+{
+ /// <summary>Primitive budget: beyond this a drawing is cut short rather than exhausting memory.</summary>
+ private const int MaxPrimitives = 1_000_000;
+
+ /// <summary>Deepest block nesting followed (also stops self-referencing blocks).</summary>
+ private const int MaxDepth = 16;
+
+ /// <summary>Largest MINSERT array expanded (rows × columns).</summary>
+ private const int MaxArrayItems = 10_000;
+
+ /// <summary>Line weight used for "Default" (AutoCAD's LWDEFAULT is 0.25 mm; a thinner line reads better on screen).</summary>
+ private const double DefaultLineWeightMm = 0.18;
+
+ /// <summary>Line weight 0 ("thinnest"), drawn as a fine line instead of a zero-width hairline.</summary>
+ private const double ThinnestLineWeightMm = 0.1;
+
+ private readonly CadScene _scene = new();
+ private readonly CancellationToken _cancellationToken;
+ private readonly double _lineTypeScale;
+ private readonly bool _pointsVisible;
+ private int _visited;
+
+ private CadSceneBuilder(CadDocument document, CancellationToken cancellationToken)
+ {
+ _cancellationToken = cancellationToken;
+ var header = document.Header;
+ _lineTypeScale = header is not null && header.LineTypeScale > 0 && double.IsFinite(header.LineTypeScale) ? header.LineTypeScale : 1;
+ _pointsVisible = header?.PointDisplayMode != 1;
+ }
+
+ /// <summary>
+ /// Builds the scene of <paramref name="document"/>: model space, or the active layout (paper space) when model
+ /// space has nothing visible. Viewports are not followed.
+ /// </summary>
+ public static CadScene Build(CadDocument document, CancellationToken cancellationToken)
+ {
+ var builder = new CadSceneBuilder(document, cancellationToken);
+ builder.DrawEntities(document.ModelSpace.Entities, DrawContext.Root);
+ if (builder._scene.Items.Count == 0 && TryGetPaperSpace(document) is { } paper)
+ {
+ builder._scene.Space = paper.Layout?.Name ?? paper.Name;
+ builder.DrawEntities(paper.Entities, DrawContext.Root);
+ }
+ return builder._scene;
+ }
+
+ private static BlockRecord? TryGetPaperSpace(CadDocument document) =>
+ document.BlockRecords.TryGetValue(BlockRecord.PaperSpaceName, out var paper) ? paper : null;
+
+ /// <summary>
+ /// What the entities inside a block reference inherit from it: the transform to WCS, the insert's layer
+ /// (entities on layer "0" take it over), and the colour, line weight and line type used by BYBLOCK.
+ /// </summary>
+ private readonly record struct DrawContext(
+ Affine3 Transform,
+ Layer? InsertLayer,
+ SKColor BlockColor,
+ double BlockWidthMm,
+ LineType? BlockLineType,
+ int Depth)
+ {
+ /// <summary>Model space: BYBLOCK entities outside blocks are drawn like colour 7 (black on paper).</summary>
+ public static DrawContext Root => new(Affine3.Identity, null, SKColors.Black, DefaultLineWeightMm, null, 0);
+ }
+
+ // ───────────────────────── Walking ─────────────────────────
+
+ private void DrawEntities(IEnumerable<Entity> entities, DrawContext context)
+ {
+ foreach (var entity in entities)
+ {
+ if ((++_visited & 1023) == 0)
+ _cancellationToken.ThrowIfCancellationRequested();
+ if (_scene.Truncated)
+ return;
+ if (entity.IsInvisible)
+ continue;
+
+ var layer = EffectiveLayer(entity, context);
+ try
+ {
+ if (entity is Insert insert)
+ {
+ DrawInsert(insert, layer, context);
+ continue;
+ }
+ if (!IsShown(layer))
+ continue;
+ DrawEntity(entity, layer, context);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ // One broken entity (missing references, degenerate data) must not lose the whole drawing.
+ Skip(entity.ObjectName + " (invalid)");
+ }
+ }
+ }
+
+ private void DrawEntity(Entity entity, Layer layer, DrawContext context)
+ {
+ switch (entity)
+ {
+ case Line line:
+ Stroke(entity, layer, context, Figure2(context.Transform.Point(line.StartPoint), context.Transform.Point(line.EndPoint)));
+ break;
+ case Arc arc:
+ DrawArc(arc, layer, context);
+ break;
+ case Circle circle:
+ DrawCircle(circle, layer, context);
+ break;
+ case Ellipse ellipse:
+ DrawEllipse(ellipse, layer, context);
+ break;
+ case LwPolyline polyline:
+ DrawLwPolyline(polyline, layer, context);
+ break;
+ case PolyfaceMesh mesh:
+ DrawPolyfaceMesh(mesh, layer, context);
+ break;
+ case PolygonMesh mesh:
+ DrawPolygonMesh(mesh, layer, context);
+ break;
+ case Polyline2D polyline:
+ DrawPolyline2D(polyline, layer, context);
+ break;
+ case Polyline3D polyline:
+ DrawPolyline3D(polyline, layer, context);
+ break;
+ case Spline spline:
+ DrawSpline(spline, layer, context);
+ break;
+ case AttributeDefinition definition:
+ // Inside blocks, definitions are replaced by the insert's attributes; alone they show their tag.
+ if (context.Depth == 0)
+ DrawText(definition, definition.Tag, layer, context);
+ break;
+ case TextEntity text:
+ if (text is not AttributeEntity attribute || !attribute.Flags.HasFlag(AttributeFlags.Hidden))
+ DrawText(text, text.Value, layer, context);
+ break;
+ case MText mtext:
+ DrawMText(mtext, layer, context);
+ break;
+ case Dimension dimension:
+ DrawDimension(dimension, layer, context);
+ break;
+ case Leader leader:
+ DrawLeader(leader, layer, context);
+ break;
+ case MultiLeader multiLeader:
+ DrawMultiLeader(multiLeader, layer, context);
+ break;
+ case Hatch hatch:
+ DrawHatch(hatch, layer, context);
+ break;
+ case Solid solid:
+ DrawSolid(solid, layer, context);
+ break;
+ case Face3D face:
+ DrawFace(face, layer, context);
+ break;
+ case Point point:
+ if (_pointsVisible)
+ Add(new PointPrimitive
+ {
+ Location = context.Transform.Point(point.Location),
+ Color = ResolveColor(entity, layer, context),
+ WidthMm = ResolveWidth(entity, layer, context),
+ }, context.Transform.Point(point.Location));
+ break;
+ case XLine xline:
+ DrawInfinite(entity, layer, context, xline.FirstPoint, xline.Direction, isRay: false);
+ break;
+ case Ray ray:
+ DrawInfinite(entity, layer, context, ray.StartPoint, ray.Direction, isRay: true);
+ break;
+ case MLine mline:
+ DrawMLine(mline, layer, context);
+ break;
+ case Mesh mesh:
+ DrawMesh(mesh, layer, context);
+ break;
+ case Viewport:
+ break; // layout viewports show model space through a view: not followed
+ case Seqend:
+ break; // end marker of old-style polylines and attributes, nothing to draw
+ default:
+ Skip(entity.ObjectName);
+ break;
+ }
+ }
+
+ // ───────────────────────── Blocks ─────────────────────────
+
+ private void DrawInsert(Insert insert, Layer layer, DrawContext context)
+ {
+ // A frozen layer hides the whole reference; an OFF (or non-plotting) layer only hides what inherits it,
+ // i.e. the block's entities on layer "0" (that is how AutoCAD shows it).
+ if (IsFrozen(layer))
+ return;
+ var block = insert.Block;
+ if (block is null)
+ {
+ Skip("INSERT (missing block)");
+ return;
+ }
+ if (context.Depth >= MaxDepth)
+ {
+ _scene.Truncated = true;
+ return;
+ }
+
+ var inherited = Inherit(insert, layer, context);
+ var basePoint = block.BlockEntity?.BasePoint ?? default;
+ var columns = Math.Max(1, (int)insert.ColumnCount);
+ var rows = Math.Max(1, (int)insert.RowCount);
+ if ((long)columns * rows > MaxArrayItems)
+ {
+ _scene.Truncated = true;
+ columns = Math.Min(columns, MaxArrayItems);
+ rows = Math.Max(1, Math.Min(rows, MaxArrayItems / columns));
+ }
+
+ var placement = context.Transform
+ .Multiply(Affine3.Ocs(insert.Normal))
+ .Multiply(Affine3.Translation(insert.InsertPoint))
+ .Multiply(Affine3.RotationZ(insert.Rotation));
+ var scale = Affine3.Scale(insert.XScale, insert.YScale, insert.ZScale)
+ .Multiply(Affine3.Translation(new Vec3(-basePoint.X, -basePoint.Y, -basePoint.Z)));
+
+ for (var row = 0; row < rows && !_scene.Truncated; row++)
+ {
+ for (var column = 0; column < columns && !_scene.Truncated; column++)
+ {
+ var cell = placement
+ .Multiply(Affine3.Translation(new Vec3(column * insert.ColumnSpacing, row * insert.RowSpacing, 0)))
+ .Multiply(scale);
+ DrawEntities(block.Entities, inherited with { Transform = cell });
+ }
+ }
+
+ // Attributes belong to the reference, not the block: they are positioned in the parent's coordinates, but
+ // like the block's contents they take over the insert's layer when on layer "0" and its BYBLOCK properties.
+ var attributeContext = inherited with { Transform = context.Transform, Depth = context.Depth };
+ foreach (var attribute in insert.Attributes)
+ {
+ var attributeLayer = EffectiveLayer(attribute, attributeContext);
+ if (!attribute.IsInvisible && IsShown(attributeLayer))
+ DrawEntity(attribute, attributeLayer, attributeContext);
+ }
+ }
+
+ /// <summary>The context for the contents of a block reference, dimension or multileader block.</summary>
+ private DrawContext Inherit(Entity reference, Layer layer, DrawContext context) => context with
+ {
+ InsertLayer = layer,
+ BlockColor = ResolveColor(reference, layer, context),
+ BlockWidthMm = ResolveWidth(reference, layer, context),
+ BlockLineType = ResolveLineType(reference, layer, context),
+ Depth = context.Depth + 1,
+ };
+
+ private void DrawDimension(Dimension dimension, Layer layer, DrawContext context)
+ {
+ var block = dimension.Block;
+ if (block is null || block.Entities.Count == 0)
+ {
+ // Some writers omit the dimension picture; let ACadSharp generate one from the definition points.
+ try
+ {
+ dimension.UpdateBlock();
+ block = dimension.Block;
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ block = null;
+ }
+ }
+ if (block is null || block.Entities.Count == 0)
+ {
+ Skip("DIMENSION (no block)");
+ return;
+ }
+ if (context.Depth >= MaxDepth)
+ return;
+
+ // The picture is stored in drawing coordinates (each entity carries its own extrusion), so it is drawn in
+ // place, like ezdxf does; only colour, layer and line properties come from the dimension (BYBLOCK).
+ DrawEntities(block.Entities, Inherit(dimension, layer, context));
+ }
+
+ // ───────────────────────── Curves ─────────────────────────
+
+ private void DrawArc(Arc arc, Layer layer, DrawContext context)
+ {
+ var m = context.Transform.Multiply(Affine3.Ocs(arc.Normal));
+ var start = arc.StartAngle;
+ var end = arc.EndAngle;
+ while (end <= start)
+ end += 2 * Math.PI;
+ var figure = ArcFigure(m, arc.Center, arc.Radius, arc.Radius, start, end);
+ Stroke(arc, layer, context, figure);
+ }
+
+ private void DrawCircle(Circle circle, Layer layer, DrawContext context)
+ {
+ var m = context.Transform.Multiply(Affine3.Ocs(circle.Normal));
+ var figure = ArcFigure(m, circle.Center, circle.Radius, circle.Radius, 0, 2 * Math.PI);
+ figure.Closed = true;
+ Stroke(circle, layer, context, figure);
+ }
+
+ private void DrawEllipse(Ellipse ellipse, Layer layer, DrawContext context)
+ {
+ // ELLIPSE is in WCS: the minor axis is the major axis turned by 90° around the normal.
+ Vec3 major = ellipse.MajorAxisEndPoint;
+ var minor = Vec3.Cross(((Vec3)ellipse.Normal).Normalized(), major) * ellipse.RadiusRatio;
+ var start = ellipse.StartParameter;
+ var end = ellipse.EndParameter;
+ while (end <= start)
+ end += 2 * Math.PI;
+ var m = context.Transform;
+ var center = m.Point(ellipse.Center);
+ var u = m.Vector(major);
+ var v = m.Vector(minor);
+ var figure = new Figure(center + u * Math.Cos(start) + v * Math.Sin(start));
+ figure.ArcTo(center, u, v, start, end);
+ figure.Closed = Math.Abs(end - start - 2 * Math.PI) < 1e-9;
+ Stroke(ellipse, layer, context, figure);
+ }
+
+ /// <summary>An arc of the circle/ellipse with radii <paramref name="rx"/>, <paramref name="ry"/> in <paramref name="m"/>'s plane.</summary>
+ private static Figure ArcFigure(Affine3 m, Vec3 center, double rx, double ry, double start, double end)
+ {
+ var c = m.Point(center);
+ var u = m.Vector(rx, 0);
+ var v = m.Vector(0, ry);
+ var figure = new Figure(c + u * Math.Cos(start) + v * Math.Sin(start));
+ figure.ArcTo(c, u, v, start, end);
+ return figure;
+ }
+
+ private void DrawSpline(Spline spline, Layer layer, DrawContext context)
+ {
+ List<Vec3> points;
+ if (spline.ControlPoints.Count >= 2)
+ {
+ var weights = spline.Weights.Count == spline.ControlPoints.Count ? spline.Weights : null;
+ points = CadCurves.SampleNurbs(spline.Degree, spline.ControlPoints.Select(p => (Vec3)p).ToList(), spline.Knots, weights);
+ }
+ else
+ {
+ points = CadCurves.ThroughPoints(spline.FitPoints.Select(p => (Vec3)p).ToList(), spline.Flags.HasFlag(SplineFlags.Closed));
+ }
+ if (points.Count >= 2)
+ Stroke(spline, layer, context, PolylineFigure(context.Transform, points, closed: false));
+ }
+
+ private static Figure PolylineFigure(Affine3 m, IReadOnlyList<Vec3> points, bool closed)
+ {
+ var figure = new Figure(m.Point(points[0]));
+ for (var i = 1; i < points.Count; i++)
+ figure.LineTo(m.Point(points[i]));
+ figure.Closed = closed;
+ return figure;
+ }
+
+ private static Figure Figure2(Vec2 a, Vec2 b)
+ {
+ var figure = new Figure(a);
+ figure.LineTo(b);
+ return figure;
+ }
+
+ // ───────────────────────── Polylines ─────────────────────────
+
+ /// <summary>A polyline vertex in the entity's OCS with the width at the start and end of the following segment.</summary>
+ private readonly record struct PolyVertex(Vec2 Location, double Bulge, double StartWidth, double EndWidth);
+
+ private void DrawLwPolyline(LwPolyline polyline, Layer layer, DrawContext context)
+ {
+ if (polyline.Vertices.Count == 0)
+ return;
+ var constant = polyline.ConstantWidth;
+ var vertices = polyline.Vertices.Select(v => new PolyVertex(
+ new Vec2(v.Location.X, v.Location.Y),
+ v.Bulge,
+ v.StartWidth > 0 || v.EndWidth > 0 ? v.StartWidth : constant,
+ v.StartWidth > 0 || v.EndWidth > 0 ? v.EndWidth : constant)).ToList();
+ var m = context.Transform.Multiply(Affine3.Ocs(polyline.Normal)).Multiply(Affine3.Translation(new Vec3(0, 0, polyline.Elevation)));
+ DrawPolyline(polyline, layer, context, m, vertices, polyline.IsClosed);
+ }
+
+ private void DrawPolyline2D(Polyline2D polyline, Layer layer, DrawContext context)
+ {
+ // R12 files can give meshes as plain polylines whose face records look like vertices at the origin.
+ if ((polyline.Flags & (PolylineFlags.PolyfaceMesh | PolylineFlags.PolygonMesh)) != 0)
+ {
+ Skip(polyline.ObjectName + " (mesh)");
+ return;
+ }
+ var smoothed = polyline.Flags.HasFlag(PolylineFlags.SplineFit);
+ var list = polyline.Vertices
+ // Spline-fit polylines keep their frame (control points) next to the fitted vertices: draw the fit.
+ .Where(v => !(smoothed && v.Flags.HasFlag(VertexFlags.SplineFrameControlPoint)))
+ .ToList();
+ if (list.Count == 0)
+ return;
+ var anyVertexWidth = list.Any(v => v.StartWidth > 0 || v.EndWidth > 0);
+ var vertices = list.Select(v => new PolyVertex(
+ new Vec2(v.Location.X, v.Location.Y),
+ smoothed ? 0 : v.Bulge,
+ anyVertexWidth ? v.StartWidth : polyline.StartWidth,
+ anyVertexWidth ? v.EndWidth : polyline.EndWidth)).ToList();
+ var m = context.Transform.Multiply(Affine3.Ocs(polyline.Normal)).Multiply(Affine3.Translation(new Vec3(0, 0, polyline.Elevation)));
+ DrawPolyline(polyline, layer, context, m, vertices, polyline.IsClosed);
+ }
+
+ private void DrawPolyline3D(Polyline3D polyline, Layer layer, DrawContext context)
+ {
+ if ((polyline.Flags & (PolylineFlags.PolyfaceMesh | PolylineFlags.PolygonMesh)) != 0)
+ {
+ Skip(polyline.ObjectName + " (mesh)");
+ return;
+ }
+ var smoothed = polyline.Flags.HasFlag(PolylineFlags.SplineFit);
+ var points = polyline.Vertices
+ .Where(v => !(smoothed && v.Flags.HasFlag(VertexFlags.SplineFrameControlPoint)))
+ .Select(v => (Vec3)v.Location)
+ .ToList();
+ if (points.Count == 0)
+ return;
+ if (points.Count == 1)
+ points.Add(points[0]);
+ Stroke(polyline, layer, context, PolylineFigure(context.Transform, points, polyline.IsClosed));
+ }
+
+ /// <summary>
+ /// Draws a 2D polyline in plane <paramref name="m"/>. Thin polylines become one stroked figure with bulge
+ /// arcs; a constant width becomes a wide stroke; varying widths (arrows, tapers) become filled bands.
+ /// </summary>
+ private void DrawPolyline(Entity entity, Layer layer, DrawContext context, Affine3 m, List<PolyVertex> vertices, bool closed)
+ {
+ var segmentCount = closed ? vertices.Count : vertices.Count - 1;
+ var figure = new Figure(m.Point(vertices[0].Location.X, vertices[0].Location.Y));
+ if (segmentCount <= 0)
+ {
+ figure.LineTo(figure.Start); // a single vertex shows as a dot
+ Stroke(entity, layer, context, figure);
+ return;
+ }
+
+ var widths = Enumerable.Range(0, segmentCount).Select(i => (vertices[i].StartWidth, vertices[i].EndWidth)).ToList();
+ var constant = widths[0].StartWidth;
+ var isConstant = widths.All(w => Math.Abs(w.StartWidth - constant) < 1e-12 && Math.Abs(w.EndWidth - constant) < 1e-12);
+
+ if (isConstant || widths.All(w => w.StartWidth <= 0 && w.EndWidth <= 0))
+ {
+ for (var i = 0; i < segmentCount; i++)
+ AppendSegment(figure, m, vertices[i], vertices[(i + 1) % vertices.Count]);
+ figure.Closed = closed;
+ Stroke(entity, layer, context, figure, constant > 0 ? constant * m.PlanScale : 0);
+ return;
+ }
+
+ // Varying widths: each wide segment is a filled band, zero-width segments stay thin lines.
+ var color = ResolveColor(entity, layer, context);
+ for (var i = 0; i < segmentCount; i++)
+ {
+ var a = vertices[i];
+ var b = vertices[(i + 1) % vertices.Count];
+ if (a.StartWidth <= 0 && a.EndWidth <= 0)
+ {
+ var thin = new Figure(m.Point(a.Location.X, a.Location.Y));
+ AppendSegment(thin, m, a, b);
+ Stroke(entity, layer, context, thin);
+ continue;
+ }
+ var band = new FillPrimitive { Color = color };
+ band.Figures.Add(Band(m, a, b));
+ AddFill(band);
+ }
+ }
+
+ private static void AppendSegment(Figure figure, Affine3 m, PolyVertex a, PolyVertex b)
+ {
+ var end = m.Point(b.Location.X, b.Location.Y);
+ if (Math.Abs(a.Bulge) < 1e-10 || (b.Location - a.Location).Length < 1e-12)
+ {
+ figure.LineTo(end);
+ return;
+ }
+ var (center, radius, start, sweep) = CadCurves.BulgeArc(a.Location, b.Location, a.Bulge);
+ figure.ArcTo(m.Point(center.X, center.Y), m.Vector(radius, 0), m.Vector(0, radius), start, start + sweep);
+ }
+
+ /// <summary>The outline of a wide polyline segment whose width changes linearly from start to end.</summary>
+ private static Figure Band(Affine3 m, PolyVertex a, PolyVertex b)
+ {
+ var left = new List<Vec2>();
+ var right = new List<Vec2>();
+ if (Math.Abs(a.Bulge) < 1e-10)
+ {
+ var normal = (b.Location - a.Location).Normalized().Perp;
+ left.Add(a.Location + normal * (a.StartWidth / 2));
+ left.Add(b.Location + normal * (a.EndWidth / 2));
+ right.Add(a.Location - normal * (a.StartWidth / 2));
+ right.Add(b.Location - normal * (a.EndWidth / 2));
+ }
+ else
+ {
+ var (center, radius, start, sweep) = CadCurves.BulgeArc(a.Location, b.Location, a.Bulge);
+ var steps = Math.Max(4, (int)Math.Ceiling(Math.Abs(sweep) / (Math.PI / 18)));
+ for (var s = 0; s <= steps; s++)
+ {
+ var f = (double)s / steps;
+ var angle = start + sweep * f;
+ var half = (a.StartWidth + (a.EndWidth - a.StartWidth) * f) / 2;
+ var direction = new Vec2(Math.Cos(angle), Math.Sin(angle));
+ left.Add(center + direction * (radius + half));
+ right.Add(center + direction * Math.Max(radius - half, 0));
+ }
+ }
+ var figure = new Figure(m.Point(left[0].X, left[0].Y));
+ foreach (var p in left.Skip(1))
+ figure.LineTo(m.Point(p.X, p.Y));
+ for (var i = right.Count - 1; i >= 0; i--)
+ figure.LineTo(m.Point(right[i].X, right[i].Y));
+ figure.Closed = true;
+ return figure;
+ }
+
+ private void DrawPolyfaceMesh(PolyfaceMesh mesh, Layer layer, DrawContext context)
+ {
+ var vertices = mesh.Vertices.Select(v => (Vec3)v.Location).ToList();
+ var edges = new StrokeCollector(this, mesh, layer, context);
+ foreach (var face in mesh.Faces)
+ {
+ var indices = new[] { face.Index1, face.Index2, face.Index3, face.Index4 }.Where(i => i != 0).ToList();
+ for (var i = 0; i < indices.Count; i++)
+ {
+ var from = indices[i];
+ var to = indices[(i + 1) % indices.Count];
+ // A negative index hides the edge that starts at that vertex.
+ if (from < 0 || Math.Abs(from) > vertices.Count || Math.Abs(to) > vertices.Count)
+ continue;
+ edges.Line(vertices[from - 1], vertices[Math.Abs(to) - 1]);
+ }
+ }
+ edges.Flush();
+ }
+
+ private void DrawPolygonMesh(PolygonMesh mesh, Layer layer, DrawContext context)
+ {
+ var vertices = mesh.Vertices.Select(v => (Vec3)v.Location).ToList();
+ int m = mesh.MVertexCount, n = mesh.NVertexCount;
+ if (m <= 0 || n <= 0 || (long)m * n > vertices.Count)
+ {
+ Skip(mesh.ObjectName);
+ return;
+ }
+ var edges = new StrokeCollector(this, mesh, layer, context);
+ for (var i = 0; i < m; i++)
+ for (var j = 0; j < n; j++)
+ {
+ if (j + 1 < n)
+ edges.Line(vertices[i * n + j], vertices[i * n + j + 1]);
+ if (i + 1 < m)
+ edges.Line(vertices[i * n + j], vertices[(i + 1) * n + j]);
+ }
+ edges.Flush();
+ }
+
+ private void DrawMesh(Mesh mesh, Layer layer, DrawContext context)
+ {
+ var vertices = mesh.Vertices.Select(v => (Vec3)v).ToList();
+ var edges = new StrokeCollector(this, mesh, layer, context);
+ foreach (var face in mesh.Faces)
+ for (var i = 0; i < face.Length; i++)
+ {
+ int a = face[i], b = face[(i + 1) % face.Length];
+ if (a >= 0 && b >= 0 && a < vertices.Count && b < vertices.Count)
+ edges.Line(vertices[a], vertices[b]);
+ }
+ edges.Flush();
+ }
+
+ private void DrawMLine(MLine mline, Layer layer, DrawContext context)
+ {
+ // Each element of the multiline style is a polyline through the vertices, offset along their miters.
+ var elements = mline.Vertices.Count == 0 ? 0 : mline.Vertices.Max(v => v.Segments.Count);
+ for (var element = 0; element < elements; element++)
+ {
+ var points = mline.Vertices
+ .Where(v => element < v.Segments.Count && v.Segments[element].Parameters.Count > 0)
+ .Select(v => (Vec3)v.Position + ((Vec3)v.Miter) * v.Segments[element].Parameters[0])
+ .ToList();
+ if (points.Count >= 2)
+ Stroke(mline, layer, context, PolylineFigure(context.Transform, points, mline.Flags.HasFlag(MLineFlags.Closed)));
+ }
+ }
+
+ // ───────────────────────── Other entities ─────────────────────────
+
+ private void DrawSolid(Solid solid, Layer layer, DrawContext context)
+ {
+ // SOLID / TRACE corners are ordered 1-2-4-3 around the outline; a triangle repeats its third corner.
+ var m = context.Transform.Multiply(Affine3.Ocs(solid.Normal));
+ var figure = new Figure(m.Point(solid.FirstCorner));
+ figure.LineTo(m.Point(solid.SecondCorner));
+ figure.LineTo(m.Point(solid.FourthCorner));
+ figure.LineTo(m.Point(solid.ThirdCorner));
+ figure.Closed = true;
+ var fill = new FillPrimitive { Color = ResolveColor(solid, layer, context) };
+ fill.Figures.Add(figure);
+ AddFill(fill);
+ }
+
+ private void DrawFace(Face3D face, Layer layer, DrawContext context)
+ {
+ var corners = new Vec3[] { face.FirstCorner, face.SecondCorner, face.ThirdCorner, face.FourthCorner };
+ var hidden = new[] { InvisibleEdgeFlags.First, InvisibleEdgeFlags.Second, InvisibleEdgeFlags.Third, InvisibleEdgeFlags.Fourth };
+ var edges = new StrokeCollector(this, face, layer, context);
+ for (var i = 0; i < 4; i++)
+ if (!face.Flags.HasFlag(hidden[i]))
+ edges.Line(corners[i], corners[(i + 1) % 4]);
+ edges.Flush();
+ }
+
+ private void DrawInfinite(Entity entity, Layer layer, DrawContext context, Vec3 origin, Vec3 direction, bool isRay)
+ {
+ var o = context.Transform.Point(origin);
+ var d = context.Transform.Vector(direction);
+ if (d.Length < 1e-12)
+ return;
+ Add(new InfiniteLinePrimitive
+ {
+ Origin = o,
+ Direction = d.Normalized(),
+ IsRay = isRay,
+ Color = ResolveColor(entity, layer, context),
+ WidthMm = ResolveWidth(entity, layer, context),
+ Dashes = ResolveDashes(entity, layer, context, context.Transform),
+ }, o);
+ }
+
+ private void DrawLeader(Leader leader, Layer layer, DrawContext context)
+ {
+ var points = leader.Vertices.Select(v => (Vec3)v).ToList();
+ if (points.Count < 2)
+ return;
+ var path = leader.PathType == LeaderPathType.Spline ? CadCurves.ThroughPoints(points, closed: false) : points;
+ Stroke(leader, layer, context, PolylineFigure(context.Transform, path, closed: false));
+ if (leader.ArrowHeadEnabled)
+ {
+ var style = leader.Style;
+ var size = style is null ? 0 : style.ArrowSize * (style.ScaleFactor > 0 ? style.ScaleFactor : 1);
+ Arrow(leader, layer, context, points[0], points[1], size);
+ }
+ }
+
+ private void DrawMultiLeader(MultiLeader leader, Layer layer, DrawContext context)
+ {
+ var data = leader.ContextData;
+ if (data is null)
+ {
+ Skip(leader.ObjectName);
+ return;
+ }
+
+ var lineContext = context with { BlockColor = ResolveColor(leader, layer, context) };
+ var lineColor = ResolveColor(leader.LineColor, layer, lineContext);
+ var arrowSize = data.ArrowheadSize > 0 ? data.ArrowheadSize : leader.ArrowheadSize * (leader.ScaleFactor > 0 ? leader.ScaleFactor : 1);
+ var width = ResolveWidth(leader, layer, context);
+ foreach (var root in data.LeaderRoots)
+ {
+ foreach (var line in root.Lines)
+ {
+ var points = line.Points.Select(p => (Vec3)p).ToList();
+ points.Add(root.ConnectionPoint);
+ if (points.Count < 2)
+ continue;
+ AddStroke(new StrokePrimitive { Color = lineColor, WidthMm = width }, PolylineFigure(context.Transform, points, closed: false));
+ if (arrowSize > 0)
+ ArrowPrimitive(lineColor, context, points[0], points[1], arrowSize);
+ }
+ if (leader.EnableLanding && root.LandingDistance > 0)
+ {
+ Vec3 start = root.ConnectionPoint;
+ var end = start + ((Vec3)root.Direction).Normalized() * root.LandingDistance;
+ AddStroke(new StrokePrimitive { Color = lineColor, WidthMm = width }, Figure2(context.Transform.Point(start), context.Transform.Point(end)));
+ }
+ }
+
+ if (data.HasTextContents && !string.IsNullOrEmpty(data.TextLabel))
+ {
+ var textColor = ResolveColor(data.TextColor, layer, lineContext);
+ var attachment = data.TextAttachmentPoint switch
+ {
+ TextAttachmentPointType.Center => AttachmentPointType.TopCenter,
+ TextAttachmentPointType.Right => AttachmentPointType.TopRight,
+ _ => AttachmentPointType.TopLeft,
+ };
+ var height = data.TextHeight > 0 ? data.TextHeight : 2.5;
+ DrawMTextCore(data.TextLabel, data.TextLocation, data.Direction, data.TextNormal, height, data.BoundaryWidth,
+ attachment, data.LineSpacingFactor, data.TextStyle ?? leader.TextStyle, textColor, context);
+ }
+ else if (data.HasContentsBlock && data.BlockContent is { } block && context.Depth < MaxDepth)
+ {
+ Vec3 scale = data.BlockContentScale;
+ var basePoint = block.BlockEntity?.BasePoint ?? default;
+ var transform = context.Transform
+ .Multiply(Affine3.Ocs(data.BlockContentNormal))
+ .Multiply(Affine3.Translation(data.BlockContentLocation))
+ .Multiply(Affine3.RotationZ(data.BlockContentRotation))
+ .Multiply(Affine3.Scale(scale.X == 0 ? 1 : scale.X, scale.Y == 0 ? 1 : scale.Y, scale.Z == 0 ? 1 : scale.Z))
+ .Multiply(Affine3.Translation(new Vec3(-basePoint.X, -basePoint.Y, -basePoint.Z)));
+ DrawEntities(block.Entities, Inherit(leader, layer, context) with { Transform = transform });
+ }
+ }
+
+ /// <summary>A filled closed arrowhead at <paramref name="tip"/> pointing away from <paramref name="from"/>.</summary>
+ private void Arrow(Entity entity, Layer layer, DrawContext context, Vec3 tip, Vec3 from, double size) =>
+ ArrowPrimitive(ResolveColor(entity, layer, context), context, tip, from, size);
+
+ private void ArrowPrimitive(SKColor color, DrawContext context, Vec3 tip, Vec3 from, double size)
+ {
+ var direction = tip - from;
+ var length = direction.Length;
+ if (size <= 0 || length < 1e-12)
+ return;
+ var d = direction * (1 / length);
+ var side = Vec3.Cross(new Vec3(0, 0, 1), d).Normalized() * (size / 6);
+ var back = tip - d * size;
+ var m = context.Transform;
+ var figure = new Figure(m.Point(tip));
+ figure.LineTo(m.Point(back + side));
+ figure.LineTo(m.Point(back - side));
+ figure.Closed = true;
+ var fill = new FillPrimitive { Color = color };
+ fill.Figures.Add(figure);
+ AddFill(fill);
+ }
+
+ // ───────────────────────── Properties ─────────────────────────
+
+ /// <summary>Entities on layer "0" inside a block take on the layer of the block reference.</summary>
+ private static Layer EffectiveLayer(Entity entity, DrawContext context)
+ {
+ var layer = entity.Layer;
+ if (context.InsertLayer is not null && (layer is null || layer.Name == Layer.DefaultName))
+ return context.InsertLayer;
+ return layer ?? context.InsertLayer ?? Layer.Default;
+ }
+
+ /// <summary>Visible on a plot: on, thawed and plottable (the Defpoints layer never plots).</summary>
+ private static bool IsShown(Layer layer) => layer.IsOn && !IsFrozen(layer) && layer.PlotFlag;
+
+ private static bool IsFrozen(Layer layer) => layer.Flags.HasFlag(LayerFlags.Frozen);
+
+ private static SKColor ResolveColor(Entity entity, Layer layer, DrawContext context) => ResolveColor(entity.Color, layer, context);
+
+ /// <summary>
+ /// BYLAYER / BYBLOCK resolution, ACI index or true colour to RGB. White and near-white (ACI 7 draws white on
+ /// AutoCAD's black screen) become black, because the page is white.
+ /// </summary>
+ private static SKColor ResolveColor(AcadColor color, Layer layer, DrawContext context)
+ {
+ if (color.IsByBlock)
+ return context.BlockColor;
+ if (color.IsByLayer)
+ color = layer.Color;
+ if (color.IsByLayer || color.IsByBlock || color.Index == 257)
+ return SKColors.Black;
+
+ var rgb = color.GetRgb();
+ if (rgb.Length < 3)
+ return SKColors.Black;
+ var (r, g, b) = (rgb[0], rgb[1], rgb[2]);
+ if (Math.Min(r, Math.Min(g, b)) >= 224)
+ return SKColors.Black;
+ return new SKColor(r, g, b);
+ }
+
+ private static double ResolveWidth(Entity entity, Layer layer, DrawContext context) =>
+ entity.LineWeight switch
+ {
+ LineWeightType.ByLayer => WidthOf(layer.LineWeight, context),
+ LineWeightType.ByBlock => context.BlockWidthMm,
+ var own => WidthOf(own, context),
+ };
+
+ private static double WidthOf(LineWeightType weight, DrawContext context) => weight switch
+ {
+ LineWeightType.ByBlock => context.BlockWidthMm,
+ LineWeightType.W0 => ThinnestLineWeightMm,
+ > 0 and <= LineWeightType.W211 => Math.Max((int)weight / 100.0, ThinnestLineWeightMm),
+ _ => DefaultLineWeightMm, // Default, ByLayer on a layer, ByDIPs
+ };
+
+ private static LineType? ResolveLineType(Entity entity, Layer layer, DrawContext context)
+ {
+ var type = entity.LineType;
+ if (type is null || type.Name.Equals(LineType.ByLayerName, StringComparison.OrdinalIgnoreCase))
+ return layer.LineType;
+ if (type.Name.Equals(LineType.ByBlockName, StringComparison.OrdinalIgnoreCase))
+ return context.BlockLineType;
+ return type;
+ }
+
+ /// <summary>
+ /// The entity's dash pattern in drawing units: line type segments × LTSCALE × the entity's scale × the block
+ /// scale. Shapes and text inside complex line types are left out (their space stays empty).
+ /// </summary>
+ private double[]? ResolveDashes(Entity entity, Layer layer, DrawContext context, Affine3 m)
+ {
+ var type = ResolveLineType(entity, layer, context);
+ if (type is null || !type.IsComplex)
+ return null;
+ var segments = type.Segments.Select(s => s.Length).ToArray();
+ if (segments.Length < 2 || segments.All(s => s >= 0) || segments.Any(s => !double.IsFinite(s)))
+ return null;
+ var entityScale = entity.LineTypeScale > 0 && double.IsFinite(entity.LineTypeScale) ? entity.LineTypeScale : 1;
+ var scale = _lineTypeScale * entityScale * m.PlanScale;
+ if (!(scale > 0) || segments.Sum(Math.Abs) * scale <= 0)
+ return null;
+ return [.. segments.Select(s => s * scale)];
+ }
+
+ // ───────────────────────── Output ─────────────────────────
+
+ private void Stroke(Entity entity, Layer layer, DrawContext context, Figure figure, double worldWidth = 0) =>
+ AddStroke(new StrokePrimitive
+ {
+ Color = ResolveColor(entity, layer, context),
+ WidthMm = ResolveWidth(entity, layer, context),
+ WorldWidth = worldWidth,
+ Dashes = ResolveDashes(entity, layer, context, context.Transform),
+ }, figure);
+
+ private void AddStroke(StrokePrimitive primitive, Figure figure)
+ {
+ primitive.Figures.Add(figure);
+ if (Reserve())
+ {
+ figure.AddTo(ref _scene.Extents);
+ _scene.Items.Add(primitive);
+ }
+ }
+
+ private void AddFill(FillPrimitive fill)
+ {
+ if (!Reserve())
+ return;
+ foreach (var figure in fill.Figures)
+ figure.AddTo(ref _scene.Extents);
+ _scene.Items.Add(fill);
+ }
+
+ private void Add(ScenePrimitive primitive, Vec2 extentPoint)
+ {
+ if (!Reserve())
+ return;
+ _scene.Extents.Add(extentPoint);
+ _scene.Items.Add(primitive);
+ }
+
+ private bool Reserve()
+ {
+ if (_scene.Items.Count < MaxPrimitives)
+ return true;
+ _scene.Truncated = true;
+ return false;
+ }
+
+ private void Skip(string type) =>
+ _scene.Skipped[type] = _scene.Skipped.TryGetValue(type, out var count) ? count + 1 : 1;
+
+ /// <summary>Collects the edges of a mesh or face into one stroke.</summary>
+ private sealed class StrokeCollector(CadSceneBuilder builder, Entity entity, Layer layer, DrawContext context)
+ {
+ private readonly List<Figure> _figures = [];
+
+ public void Line(Vec3 a, Vec3 b) => _figures.Add(Figure2(context.Transform.Point(a), context.Transform.Point(b)));
+
+ public void Flush()
+ {
+ if (_figures.Count == 0 || !builder.Reserve())
+ return;
+ var primitive = new StrokePrimitive
+ {
+ Color = ResolveColor(entity, layer, context),
+ WidthMm = ResolveWidth(entity, layer, context),
+ Dashes = builder.ResolveDashes(entity, layer, context, context.Transform),
+ };
+ foreach (var figure in _figures)
+ {
+ figure.AddTo(ref builder._scene.Extents);
+ primitive.Figures.Add(figure);
+ }
+ builder._scene.Items.Add(primitive);
+ }
+ }
+}
diff --git a/src/Filee.Engines/Cad/CadTextCodes.cs b/src/Filee.Engines/Cad/CadTextCodes.cs
new file mode 100644
index 00000000..ceb2b604
--- /dev/null
+++ b/src/Filee.Engines/Cad/CadTextCodes.cs
@@ -0,0 +1,300 @@
+// Decodes the control codes inside CAD text: %%d / %%c / %%p specials and \U+ / \M+ escapes in TEXT, and the MTEXT
+// formatting language (\P paragraphs, \H height, \C colour, \f font, \S stacked fractions, {} groups ...).
+
+using System.Globalization;
+using System.Text;
+
+namespace Filee.Engines.Cad;
+
+/// <summary>Formatting state of an MTEXT run. Values not set by codes come from the entity.</summary>
+internal readonly record struct MTextFormat(
+ double Height,
+ short? ColorIndex,
+ int? TrueColor,
+ string? FontFamily,
+ bool Bold,
+ bool Italic,
+ double WidthFactor,
+ double ObliqueDegrees);
+
+/// <summary>A piece of MTEXT with one format.</summary>
+internal readonly record struct MTextRun(string Text, MTextFormat Format);
+
+/// <summary>Parsers for text control codes.</summary>
+internal static class CadTextCodes
+{
+ /// <summary>Multi-byte code pages of <c>\M+n</c> escapes (AutoCAD's numbering).</summary>
+ private static readonly int[] MultiByteCodePages = [0, 932, 950, 949, 1361, 936];
+
+ static CadTextCodes() => Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+
+ /// <summary>
+ /// Decodes a single-line TEXT / ATTRIB value: <c>%%d</c> → °, <c>%%c</c> → Ø, <c>%%p</c> → ±, <c>%%nnn</c> → character
+ /// nnn, underline / overline toggles removed, <c>\U+XXXX</c> and <c>\M+nXXXX</c> escapes decoded.
+ /// </summary>
+ public static string DecodeText(string? value)
+ {
+ if (string.IsNullOrEmpty(value))
+ return "";
+ var sb = new StringBuilder(value.Length);
+ for (var i = 0; i < value.Length; i++)
+ {
+ if (TryEscape(value, ref i, sb) || TrySpecial(value, ref i, sb))
+ continue;
+ sb.Append(value[i] == '\t' ? ' ' : value[i]);
+ }
+ return sb.ToString();
+ }
+
+ /// <summary>
+ /// Parses an MTEXT value into paragraphs of formatted runs. Paragraph, line and column breaks start a new
+ /// paragraph; stacked text becomes an inline fraction ("1/2"); codes that only affect layout details
+ /// (tracking, paragraph indents, underline) are dropped.
+ /// </summary>
+ public static List<List<MTextRun>> ParseMText(string? value, MTextFormat initial)
+ {
+ var paragraphs = new List<List<MTextRun>> { new() };
+ if (string.IsNullOrEmpty(value))
+ return paragraphs;
+
+ var state = initial;
+ var stack = new Stack<MTextFormat>();
+ var text = new StringBuilder();
+
+ for (var i = 0; i < value.Length; i++)
+ {
+ var ch = value[i];
+ if (ch == '{')
+ {
+ Flush();
+ stack.Push(state);
+ continue;
+ }
+ if (ch == '}')
+ {
+ Flush();
+ if (stack.Count > 0)
+ state = stack.Pop();
+ continue;
+ }
+ if (ch is '\n' or '\r')
+ {
+ if (ch == '\r' && i + 1 < value.Length && value[i + 1] == '\n')
+ i++;
+ NewParagraph();
+ continue;
+ }
+ if (ch != '\\' || i + 1 >= value.Length)
+ {
+ if (!TrySpecial(value, ref i, text))
+ text.Append(ch == '\t' ? " " : ch);
+ continue;
+ }
+
+ var code = value[i + 1];
+ switch (code)
+ {
+ case '\\' or '{' or '}':
+ text.Append(code);
+ i++;
+ break;
+ case 'P' or 'N' or 'X':
+ i++;
+ NewParagraph();
+ break;
+ case '~':
+ text.Append(' ');
+ i++;
+ break;
+ case 'U' or 'M':
+ if (!TryEscape(value, ref i, text))
+ i++;
+ break;
+ case 'H' or 'W' or 'Q':
+ {
+ var argument = ReadArgument(value, ref i);
+ Flush();
+ state = ApplyNumeric(state, code, argument);
+ break;
+ }
+ case 'C' or 'c':
+ {
+ var argument = ReadArgument(value, ref i);
+ Flush();
+ if (int.TryParse(argument, NumberStyles.Integer, CultureInfo.InvariantCulture, out var number))
+ state = code == 'C'
+ ? state with { ColorIndex = (short)Math.Clamp(number, 0, 256), TrueColor = null }
+ : state with { TrueColor = number & 0xFFFFFF, ColorIndex = null };
+ break;
+ }
+ case 'f' or 'F':
+ {
+ var argument = ReadArgument(value, ref i);
+ Flush();
+ state = ApplyFont(state, argument);
+ break;
+ }
+ case 'S':
+ {
+ var argument = ReadArgument(value, ref i);
+ text.Append(Stacked(argument));
+ break;
+ }
+ case 'A' or 'T' or 'p' or 'q':
+ ReadArgument(value, ref i); // alignment, tracking, paragraph properties: layout details
+ break;
+ default:
+ // \L \l \O \o \K \k (underline, overline, strike-through) and unknown codes: drop the code.
+ i++;
+ break;
+ }
+ }
+ Flush();
+ return paragraphs;
+
+ void Flush()
+ {
+ if (text.Length == 0)
+ return;
+ paragraphs[^1].Add(new MTextRun(text.ToString(), state));
+ text.Clear();
+ }
+
+ void NewParagraph()
+ {
+ Flush();
+ paragraphs.Add([]);
+ }
+ }
+
+ /// <summary>Reads the argument of a code like <c>\H2.5;</c>, leaving <paramref name="i"/> on the ';'.</summary>
+ private static string ReadArgument(string value, ref int i)
+ {
+ var start = i + 2;
+ var end = start;
+ while (end < value.Length && value[end] != ';')
+ {
+ // Inside \S, "\;" is an escaped semicolon.
+ if (value[end] == '\\' && end + 1 < value.Length)
+ end++;
+ end++;
+ }
+ i = Math.Min(end, value.Length - 1);
+ return start < value.Length ? value[start..Math.Min(end, value.Length)] : "";
+ }
+
+ private static MTextFormat ApplyNumeric(MTextFormat state, char code, string argument)
+ {
+ var relative = argument.EndsWith('x') || argument.EndsWith('X');
+ if (!double.TryParse(relative ? argument[..^1] : argument, NumberStyles.Float, CultureInfo.InvariantCulture, out var number)
+ || !double.IsFinite(number))
+ return state;
+ return code switch
+ {
+ 'H' when number > 0 => state with { Height = relative ? state.Height * number : number },
+ 'W' when number > 0 => state with { WidthFactor = relative ? state.WidthFactor * number : number },
+ 'Q' => state with { ObliqueDegrees = Math.Clamp(number, -85, 85) },
+ _ => state,
+ };
+ }
+
+ /// <summary><c>\fArial|b1|i0|c0|p34;</c> (TrueType) or <c>\Ftxt.shx;</c> (SHX: rendered with the default font).</summary>
+ private static MTextFormat ApplyFont(MTextFormat state, string argument)
+ {
+ var parts = argument.Split('|');
+ var family = parts[0].Trim();
+ var bold = false;
+ var italic = false;
+ foreach (var part in parts.Skip(1))
+ {
+ if (part.Length >= 2 && part[0] is 'b')
+ bold = part[1] == '1';
+ else if (part.Length >= 2 && part[0] is 'i')
+ italic = part[1] == '1';
+ }
+ if (family.EndsWith(".shx", StringComparison.OrdinalIgnoreCase))
+ family = "";
+ return state with { FontFamily = family.Length == 0 ? null : family, Bold = bold, Italic = italic };
+ }
+
+ /// <summary>Stacked text <c>1/2</c>, <c>1#2</c> (diagonal) or <c>+0.1^-0.2</c> (tolerance) shown inline as "1/2".</summary>
+ private static string Stacked(string argument)
+ {
+ var unescaped = argument.Replace("\\;", ";", StringComparison.Ordinal);
+ var split = unescaped.IndexOfAny(['/', '#', '^']);
+ if (split < 0)
+ return DecodeText(unescaped);
+ var top = DecodeText(unescaped[..split]).Trim();
+ var bottom = DecodeText(unescaped[(split + 1)..]).Trim();
+ return top.Length == 0 ? bottom : bottom.Length == 0 ? top : $"{top}/{bottom}";
+ }
+
+ /// <summary>Decodes <c>\U+XXXX</c> (Unicode) and <c>\M+nXXXX</c> (a double-byte character in an Asian code page).</summary>
+ private static bool TryEscape(string value, ref int i, StringBuilder sb)
+ {
+ if (value[i] != '\\' || i + 2 >= value.Length || value[i + 2] != '+')
+ return false;
+ if (value[i + 1] is 'U' or 'u' && i + 7 <= value.Length
+ && int.TryParse(value.AsSpan(i + 3, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var code))
+ {
+ sb.Append((char)code);
+ i += 6;
+ return true;
+ }
+ if (value[i + 1] is 'M' or 'm' && i + 8 <= value.Length
+ && value[i + 3] is >= '1' and <= '5'
+ && int.TryParse(value.AsSpan(i + 4, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var bytes))
+ {
+ try
+ {
+ var encoding = Encoding.GetEncoding(MultiByteCodePages[value[i + 3] - '0']);
+ sb.Append(encoding.GetString([(byte)(bytes >> 8), (byte)bytes]));
+ i += 7;
+ return true;
+ }
+ catch (ArgumentException)
+ {
+ return false;
+ }
+ }
+ return false;
+ }
+
+ /// <summary>The <c>%%</c> specials of AutoCAD text.</summary>
+ private static bool TrySpecial(string value, ref int i, StringBuilder sb)
+ {
+ if (value[i] != '%' || i + 2 >= value.Length || value[i + 1] != '%')
+ return false;
+ var code = char.ToLowerInvariant(value[i + 2]);
+ switch (code)
+ {
+ case 'd':
+ sb.Append('°');
+ break;
+ case 'c':
+ sb.Append('Ø');
+ break;
+ case 'p':
+ sb.Append('±');
+ break;
+ case '%':
+ sb.Append('%');
+ break;
+ case 'u' or 'o' or 'k':
+ break; // underline / overline / strike-through toggles
+ case >= '0' and <= '9':
+ {
+ var end = i + 2;
+ while (end < value.Length && end < i + 5 && char.IsAsciiDigit(value[end]))
+ end++;
+ sb.Append((char)int.Parse(value.AsSpan(i + 2, end - i - 2), CultureInfo.InvariantCulture));
+ i = end - 1;
+ return true;
+ }
+ default:
+ return false;
+ }
+ i += 2;
+ return true;
+ }
+}
diff --git a/src/Filee.Engines/EngineRegistry.cs b/src/Filee.Engines/EngineRegistry.cs
index 31b45a74..d3c5f010 100644
--- a/src/Filee.Engines/EngineRegistry.cs
+++ b/src/Filee.Engines/EngineRegistry.cs
@@ -1,6 +1,7 @@
// THE place where conversion engines are registered. Adding an engine = one line in CreateAll.
using Filee.Core.Conversion;
+using Filee.Engines.Cad;
using Filee.Engines.Hwp;
using Filee.Engines.Hwp.Hwpx;
using Filee.Engines.Infrastructure;
@@ -29,6 +30,7 @@ public static class EngineRegistry
new MarkdownConverter(),
new SpreadsheetConverter(),
new HwpxConverter(),
+ new CadConverter(),
new PandocConverter(),
new LibreOfficeConverter(env),
];
diff --git a/src/Filee.Engines/Filee.Engines.csproj b/src/Filee.Engines/Filee.Engines.csproj
index af7d20a6..cd9d5d68 100644
--- a/src/Filee.Engines/Filee.Engines.csproj
+++ b/src/Filee.Engines/Filee.Engines.csproj
@@ -18,6 +18,7 @@
<PackageReference Include="Unhwp" />
<PackageReference Include="Markdig" />
<PackageReference Include="ExcelNumberFormat" />
+ <PackageReference Include="ACadSharp" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
</ItemGroup>
diff --git a/tests/Filee.Engines.Tests/CadBuilder.cs b/tests/Filee.Engines.Tests/CadBuilder.cs
new file mode 100644
index 00000000..c52df37d
--- /dev/null
+++ b/tests/Filee.Engines.Tests/CadBuilder.cs
@@ -0,0 +1,144 @@
+// Builds CAD drawings for the tests with ACadSharp, so no sample DWG/DXF files are needed.
+
+using ACadSharp;
+using ACadSharp.Entities;
+using ACadSharp.IO;
+using ACadSharp.Tables;
+using CSMath;
+
+namespace Filee.Engines.Tests;
+
+/// <summary>Test drawings: one with every commonly used entity, plus small special-purpose ones.</summary>
+internal static class CadBuilder
+{
+ /// <summary>ACI 5: everything that must be visible is blue.</summary>
+ public static readonly Color Visible = new(5);
+
+ /// <summary>ACI 1: everything on hidden layers is red, so a red pixel means a hidden layer was drawn.</summary>
+ public static readonly Color Hidden = new(1);
+
+ public const string KoreanText = "도면 제목 Filee";
+
+ /// <summary>
+ /// A drawing with lines, a circle, an arc, a polyline with a bulge, TEXT (Korean), MTEXT, a block with an
+ /// attribute inserted twice (rotated and scaled), a solid and a pattern hatch, a dashed line, a spline, a partial
+ /// ellipse, an aligned dimension, and entities on an OFF and a frozen layer.
+ /// </summary>
+ public static CadDocument Sample()
+ {
+ var doc = new CadDocument();
+ var drawing = new Layer("Drawing") { Color = Visible };
+ var off = new Layer("Off") { Color = Hidden, IsOn = false };
+ var frozen = new Layer("Frozen") { Color = Hidden, Flags = LayerFlags.Frozen };
+ doc.Layers.Add(drawing);
+ doc.Layers.Add(off);
+ doc.Layers.Add(frozen);
+
+ Add(doc, drawing, new Line(new XYZ(0, 0, 0), new XYZ(100, 0, 0)));
+ Add(doc, drawing, new Line(new XYZ(100, 0, 0), new XYZ(100, 60, 0)));
+ Add(doc, drawing, new Circle(new XYZ(30, 30, 0), 12));
+ Add(doc, drawing, new Arc(new XYZ(70, 30, 0), 10, 0, Math.PI));
+ Add(doc, drawing, new LwPolyline(
+ new LwPolyline.Vertex(0, 60) { Bulge = 0.5 },
+ new LwPolyline.Vertex(40, 60),
+ new LwPolyline.Vertex(40, 80)));
+ Add(doc, drawing, new TextEntity(KoreanText) { InsertPoint = new XYZ(5, 5, 0), Height = 5 });
+ Add(doc, drawing, new MText("{\\H1.5x;MTEXT}\\P두 번째 줄 \\S1/2;") { InsertPoint = new XYZ(50, 80, 0), Height = 3, RectangleWidth = 60 });
+
+ var block = new BlockRecord("BOLT");
+ block.Entities.Add(new Circle(new XYZ(0, 0, 0), 3));
+ block.Entities.Add(new Line(new XYZ(-5, 0, 0), new XYZ(5, 0, 0)));
+ block.Entities.Add(new AttributeDefinition { Tag = "ID", Value = "B?", InsertPoint = new XYZ(4, 4, 0), Height = 2 });
+ doc.BlockRecords.Add(block);
+ // A new Insert gets one attribute per definition (placed at the definition); set the values per reference.
+ var bolt1 = new Insert(block) { InsertPoint = new XYZ(80, 50, 0) };
+ bolt1.Attributes.Single().Value = "B1";
+ bolt1.Attributes.Single().InsertPoint = new XYZ(84, 54, 0);
+ Add(doc, drawing, bolt1);
+ var bolt2 = new Insert(block) { InsertPoint = new XYZ(80, 15, 0), XScale = 2, YScale = 2, Rotation = Math.PI / 6 };
+ bolt2.Attributes.Single().Value = "B2";
+ bolt2.Attributes.Single().InsertPoint = new XYZ(84, 19, 0);
+ Add(doc, drawing, bolt2);
+
+ var hatch = new Hatch { IsSolid = true };
+ hatch.Paths.Add(Rectangle(110, 0, 20, 20));
+ Add(doc, drawing, hatch);
+
+ // ANSI31-like pattern: 45° lines 2 units apart, stored as AutoCAD stores them (already scaled and rotated).
+ var pattern = new HatchPattern("ANSI31");
+ pattern.Lines.Add(new HatchPattern.Line { Angle = Math.PI / 4, BasePoint = XY.Zero, Offset = new XY(-Math.Sqrt(2), Math.Sqrt(2)) });
+ var patterned = new Hatch { IsSolid = false, Pattern = pattern };
+ patterned.Paths.Add(Rectangle(110, 30, 20, 20));
+ Add(doc, drawing, patterned);
+
+ var dashed = new LineType("DASHED");
+ dashed.AddSegment(new LineType.Segment { Length = 5 });
+ dashed.AddSegment(new LineType.Segment { Length = -2.5 });
+ doc.LineTypes.Add(dashed);
+ Add(doc, drawing, new Line(new XYZ(0, -5, 0), new XYZ(100, -5, 0)) { LineType = dashed });
+
+ var spline = new Spline { Degree = 3 };
+ spline.ControlPoints.AddRange([new XYZ(0, -20, 0), new XYZ(20, -10, 0), new XYZ(40, -30, 0), new XYZ(60, -20, 0)]);
+ spline.Knots.AddRange([0, 0, 0, 0, 1, 1, 1, 1]);
+ Add(doc, drawing, spline);
+ Add(doc, drawing, new Ellipse { Center = new XYZ(85, -20, 0), MajorAxisEndPoint = new XYZ(12, 0, 0), RadiusRatio = 0.5, StartParameter = 0, EndParameter = 1.5 * Math.PI });
+
+ // The default dimension style is sized for inches (0.18 text); this drawing is in millimetres.
+ var dimension = new DimensionAligned
+ {
+ FirstPoint = new XYZ(0, 60, 0),
+ SecondPoint = new XYZ(100, 60, 0),
+ Style = new DimensionStyle("Filee") { TextHeight = 2.5, ArrowSize = 2.5 },
+ };
+ dimension.Offset = 8;
+ Add(doc, drawing, dimension);
+ dimension.UpdateBlock();
+
+ Add(doc, off, new Line(new XYZ(0, 20, 0), new XYZ(100, 20, 0)));
+ Add(doc, off, new Circle(new XYZ(60, 60, 0), 8));
+ Add(doc, frozen, new Line(new XYZ(0, 40, 0), new XYZ(100, 40, 0)));
+ return doc;
+ }
+
+ /// <summary>A few lines around (1 000 000, 500 000) with header extents that point elsewhere.</summary>
+ public static CadDocument FarFromOrigin()
+ {
+ var doc = new CadDocument();
+ var layer = new Layer("Far") { Color = new Color(7) };
+ doc.Layers.Add(layer);
+ const double X = 1_000_000, Y = 500_000;
+ Add(doc, layer, new Line(new XYZ(X, Y, 0), new XYZ(X + 400, Y, 0)));
+ Add(doc, layer, new Line(new XYZ(X + 400, Y, 0), new XYZ(X + 400, Y + 200, 0)));
+ Add(doc, layer, new Line(new XYZ(X + 400, Y + 200, 0), new XYZ(X, Y + 200, 0)));
+ Add(doc, layer, new Line(new XYZ(X, Y + 200, 0), new XYZ(X, Y, 0)));
+ doc.Header.ModelSpaceExtMin = new XYZ(0, 0, 0);
+ doc.Header.ModelSpaceExtMax = new XYZ(10, 10, 0);
+ return doc;
+ }
+
+ public static Hatch.BoundaryPath Rectangle(double x, double y, double width, double height)
+ {
+ var path = new Hatch.BoundaryPath();
+ path.Edges.Add(new Hatch.BoundaryPath.Polyline(
+ [new XYZ(x, y, 0), new XYZ(x + width, y, 0), new XYZ(x + width, y + height, 0), new XYZ(x, y + height, 0)]));
+ return path;
+ }
+
+ public static T Add<T>(CadDocument doc, Layer layer, T entity) where T : Entity
+ {
+ entity.Layer = layer;
+ doc.Entities.Add(entity);
+ return entity;
+ }
+
+ public static string SaveDxf(CadDocument doc, string folder, string name, bool binary = false)
+ {
+ var path = Path.Combine(folder, name);
+ DxfWriter.Write(path, doc, binary);
+ return path;
+ }
+
+ /// <summary>Model space entity counts by DXF type name.</summary>
+ public static Dictionary<string, int> Census(CadDocument doc) =>
+ doc.Entities.GroupBy(e => e.ObjectName).ToDictionary(g => g.Key, g => g.Count());
+}
diff --git a/tests/Filee.Engines.Tests/CadTests.cs b/tests/Filee.Engines.Tests/CadTests.cs
new file mode 100644
index 00000000..0578c57a
--- /dev/null
+++ b/tests/Filee.Engines.Tests/CadTests.cs
@@ -0,0 +1,406 @@
+// DWG / DXF without AutoCAD: DXF ↔ DWG with ACadSharp and the built-in renderer (PDF, SVG, PNG). Drawings are
+// generated by CadBuilder; outputs are parsed back (DXF/DWG readers, SVG XML, PDFsharp, pixels).
+
+using System.Xml.Linq;
+using ACadSharp;
+using ACadSharp.Entities;
+using ACadSharp.IO;
+using ACadSharp.Tables;
+using CSMath;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Cad;
+using ImageMagick;
+using PdfSharp.Pdf.Content;
+using PdfSharp.Pdf.Content.Objects;
+using PdfSharp.Pdf.IO;
+using SkiaSharp;
+
+namespace Filee.Engines.Tests;
+
+public class CadTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private async Task<string> ConvertAsync(string input, string target, Preset? preset = null)
+ {
+ var job = await fx.ConvertAsync([input], preset ?? new Preset { TargetFormat = target });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ return job.Outputs.Single();
+ }
+
+ private string SampleDxf() => CadBuilder.SaveDxf(CadBuilder.Sample(), fx.NewFolder(), "도면.dxf");
+
+ // ───────────────────────── Routes ─────────────────────────
+
+ [Theory]
+ [InlineData("dwg", "png")]
+ [InlineData("dwg", "pdf")]
+ [InlineData("dwg", "svg")]
+ [InlineData("dwg", "dxf")]
+ [InlineData("dxf", "dwg")]
+ [InlineData("dxf", "jpg")]
+ [InlineData("dxf", "webp")]
+ public void Cad_formats_are_converted_by_the_cad_engine_in_one_step(string from, string to)
+ {
+ var route = fx.Catalog.CreatePlanner().Plan(from, to);
+ Assert.NotNull(route);
+ Assert.Equal("cad", Assert.Single(route.Steps).Converter.Id);
+ }
+
+ // ───────────────────────── DXF ↔ DWG ─────────────────────────
+
+ [Fact]
+ public async Task Dxf_to_dwg_and_back_keeps_every_entity()
+ {
+ var source = SampleDxf();
+ var expected = CadBuilder.Census(DxfReader.Read(source));
+
+ var dwg = await ConvertAsync(source, "dwg");
+ Assert.Equal("AC1032"u8.ToArray(), (await File.ReadAllBytesAsync(dwg, TestContext.Current.CancellationToken))[..6]);
+ var fromDwg = DwgReader.Read(dwg);
+ Assert.Equal(expected, CadBuilder.Census(fromDwg));
+
+ var dxf = await ConvertAsync(dwg, "dxf", new Preset { TargetFormat = "dxf", Output = { FileNamePattern = "{name}_back" } });
+ var back = DxfReader.Read(dxf);
+ Assert.Equal(ACadVersion.AC1032, back.Header.Version);
+ Assert.Equal(expected, CadBuilder.Census(back));
+
+ // Content survives, not just the count: Korean text (UTF-8 in 2018 DXF), blocks, attributes, layer states.
+ Assert.Contains(back.Entities.OfType<TextEntity>(), t => t.Value == CadBuilder.KoreanText);
+ var bolt = back.Entities.OfType<Insert>().First(i => i.Attributes.Count > 0);
+ Assert.Equal("BOLT", bolt.Block.Name);
+ Assert.Equal(2, bolt.Block.Entities.OfType<Circle>().Count() + bolt.Block.Entities.OfType<Line>().Count());
+ Assert.Equal(["ID=B1", "ID=B2"], fromDwg.Entities.OfType<Insert>().SelectMany(i => i.Attributes).Select(a => $"{a.Tag}={a.Value}"));
+ Assert.Equal(["ID=B1"], bolt.Attributes.Select(a => $"{a.Tag}={a.Value}"));
+ Assert.False(back.Layers["Off"].IsOn);
+ Assert.True(back.Layers["Frozen"].Flags.HasFlag(LayerFlags.Frozen));
+ }
+
+ [Fact]
+ public async Task Binary_dxf_is_read()
+ {
+ var binary = CadBuilder.SaveDxf(CadBuilder.Sample(), fx.NewFolder(), "binary.dxf", binary: true);
+ Assert.True(DxfReader.IsBinary(binary));
+
+ var dwg = await ConvertAsync(binary, "dwg");
+
+ Assert.Equal(CadBuilder.Census(DxfReader.Read(binary)), CadBuilder.Census(DwgReader.Read(dwg)));
+ }
+
+ [Fact]
+ public void Korean_text_in_pre_2007_files_is_decoded()
+ {
+ // Before AutoCAD 2007, text is stored in the drawing's code page (CP949 for Korean).
+ var doc = new CadDocument();
+ doc.Entities.Add(new TextEntity(CadBuilder.KoreanText) { Height = 2.5 });
+ doc.Header.Version = ACadVersion.AC1018;
+ doc.Header.CodePage = "kcs5601";
+ var dir = fx.NewFolder();
+
+ var dwg = Path.Combine(dir, "old.dwg");
+ DwgWriter.Write(dwg, doc);
+ Assert.Equal(CadBuilder.KoreanText, CadFile.Read(dwg, "dwg").Entities.OfType<TextEntity>().Single().Value);
+
+ // Korean AutoCAD names the code page ANSI_949 in DXF, which ACadSharp does not know by that name.
+ var dxf = CadBuilder.SaveDxf(doc, dir, "old.dxf");
+ var bytes = File.ReadAllBytes(dxf);
+ var header = System.Text.Encoding.ASCII.GetString(bytes);
+ var at = header.IndexOf("kcs5601", StringComparison.Ordinal);
+ Assert.True(at > 0);
+ File.WriteAllBytes(dxf, [.. bytes[..at], .. "ANSI_949"u8.ToArray(), .. bytes[(at + 7)..]]);
+ Assert.Contains("ANSI_949", File.ReadAllText(dxf, System.Text.Encoding.Latin1));
+
+ // ACadSharp alone garbles it; when this starts to pass, CadFile.OpenDxf's workaround can go.
+ Assert.NotEqual(CadBuilder.KoreanText, DxfReader.Read(dxf).Entities.OfType<TextEntity>().Single().Value);
+ Assert.Equal(CadBuilder.KoreanText, CadFile.Read(dxf, "dxf").Entities.OfType<TextEntity>().Single().Value);
+ }
+
+ [Theory]
+ [InlineData("broken.dwg", "not a DWG drawing")]
+ [InlineData("broken.dxf", "not a valid DXF drawing")]
+ public async Task Damaged_files_fail_with_a_clear_message(string name, string message)
+ {
+ var path = Path.Combine(fx.NewFolder(), name);
+ await File.WriteAllTextAsync(path, "This is not a drawing.\n0\nSECTION\n", TestContext.Current.CancellationToken);
+
+ var job = await fx.ConvertAsync([path], new Preset { TargetFormat = "pdf" });
+
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.Contains(message, job.Files.Single().ErrorDetail, StringComparison.OrdinalIgnoreCase);
+ }
+
+ // ───────────────────────── Rendering ─────────────────────────
+
+ [Fact]
+ public async Task Dxf_to_svg_has_paths_and_text()
+ {
+ var svg = XDocument.Load(await ConvertAsync(SampleDxf(), "svg"));
+ XNamespace ns = "http://www.w3.org/2000/svg";
+
+ var root = svg.Root!;
+ Assert.Equal(ns + "svg", root.Name);
+ var width = double.Parse(root.Attribute("width")!.Value, System.Globalization.CultureInfo.InvariantCulture);
+ var height = double.Parse(root.Attribute("height")!.Value, System.Globalization.CultureInfo.InvariantCulture);
+ Assert.InRange(width, 1500, 1600); // 420 mm at 96 dpi on the long edge
+ Assert.True(height < width, "a wide drawing gives a landscape page");
+
+ var paths = svg.Descendants(ns + "path").ToList();
+ Assert.True(paths.Count >= 5, $"{paths.Count} paths");
+ Assert.Contains(paths, p => p.Attribute("stroke")?.Value == "blue");
+ var text = string.Concat(svg.Descendants(ns + "text").Select(t => t.Value.Trim()));
+ Assert.Contains("MTEXT", text);
+ Assert.Contains("B1", text); // the block attribute
+ Assert.Contains("1/2", text); // stacked fraction
+ Assert.Contains(CadBuilder.KoreanText.Replace(" ", "", StringComparison.Ordinal), text.Replace(" ", "", StringComparison.Ordinal));
+ // Entities on the OFF and frozen layers are red: nothing red may appear.
+ Assert.DoesNotContain(svg.Descendants(), e => e.Attribute("stroke")?.Value == "red" || e.Attribute("fill")?.Value == "red");
+ }
+
+ [Fact]
+ public async Task Dxf_to_pdf_is_one_vector_page()
+ {
+ var pdf = await ConvertAsync(SampleDxf(), "pdf");
+
+ using var document = PdfReader.Open(pdf, PdfDocumentOpenMode.Import);
+ Assert.Equal(1, document.PageCount);
+ var page = document.Pages[0];
+ // A3 landscape: 420 × 297 mm.
+ Assert.Equal(420 / 25.4 * 72, page.Width.Point, 0.5);
+ Assert.Equal(297 / 25.4 * 72, page.Height.Point, 0.5);
+
+ var operators = Operators(ContentReader.ReadContent(page)).ToList();
+ Assert.Contains(OpCodeName.l, operators); // lines
+ Assert.Contains(OpCodeName.c, operators); // curves (circle, arc, bulge)
+ Assert.True(operators.Contains(OpCodeName.f) || operators.Contains(OpCodeName.fx), "the solid hatch is a filled path");
+ Assert.True(operators.Contains(OpCodeName.Tj) || operators.Contains(OpCodeName.TJ), "text is real text");
+ Assert.DoesNotContain(OpCodeName.BI, operators); // no inline raster images
+ }
+
+ [Fact]
+ public async Task Dxf_to_png_draws_the_visible_layers_only()
+ {
+ var png = await ConvertAsync(SampleDxf(), "png");
+
+ using var image = new MagickImage(png);
+ Assert.Equal(2480u, Math.Max(image.Width, image.Height)); // A3 long edge at 150 dpi
+ var (ink, blue, red, _) = CountPixels(image);
+ Assert.True(ink > 5000, $"{ink} drawn pixels");
+ Assert.True(blue > 1000, $"{blue} blue pixels");
+ Assert.Equal(0, red);
+ }
+
+ [Fact]
+ public async Task A_drawing_far_from_the_origin_still_fills_the_page()
+ {
+ // The header claims the drawing spans (0,0)-(10,10); the page must be fitted to the real entities.
+ var source = CadBuilder.SaveDxf(CadBuilder.FarFromOrigin(), fx.NewFolder(), "far.dxf");
+
+ var png = await ConvertAsync(source, "png", new Preset { TargetFormat = "png", Pdf = { RenderDpi = 50 } });
+
+ using var image = new MagickImage(png);
+ var (_, _, _, box) = CountPixels(image);
+ Assert.True(box.Width > image.Width * 0.9, $"drawing spans {box.Width} of {image.Width} px");
+ Assert.True(box.Height > image.Height * 0.8, $"drawing spans {box.Height} of {image.Height} px");
+ Assert.InRange(image.Width / (double)image.Height, 1.8, 2.2); // the page has the drawing's 2:1 aspect
+ }
+
+ [Fact]
+ public async Task Dxf_to_other_image_formats_applies_image_options()
+ {
+ var jpg = await ConvertAsync(SampleDxf(), "jpg", new Preset { TargetFormat = "jpg", Image = { Resize = ResizeMode.LongEdge, LongEdge = 800, Quality = 80 } });
+
+ using var image = new MagickImage(jpg);
+ Assert.Equal(MagickFormat.Jpeg, image.Format);
+ Assert.Equal(800u, Math.Max(image.Width, image.Height));
+ }
+
+ // ───────────────────────── Scene details ─────────────────────────
+
+ [Fact]
+ public void Layer_zero_in_a_block_follows_the_insert_layer()
+ {
+ // AutoCAD: an insert on an OFF layer hides the block's layer-0 entities, but entities on their own
+ // (visible) layer stay; an insert on a frozen layer hides everything.
+ var doc = new CadDocument();
+ var off = new Layer("Off") { IsOn = false };
+ var frozen = new Layer("Frozen") { Flags = LayerFlags.Frozen };
+ var own = new Layer("Own") { Color = CadBuilder.Visible };
+ doc.Layers.Add(off);
+ doc.Layers.Add(frozen);
+ doc.Layers.Add(own);
+ var block = new BlockRecord("B");
+ block.Entities.Add(new Line(new XYZ(0, 0, 0), new XYZ(10, 0, 0)));
+ block.Entities.Add(new Line(new XYZ(0, 5, 0), new XYZ(10, 5, 0)) { Layer = own });
+ doc.BlockRecords.Add(block);
+ CadBuilder.Add(doc, off, new Insert(block));
+ CadBuilder.Add(doc, frozen, new Insert(block) { InsertPoint = new XYZ(0, 100, 0) });
+
+ var scene = CadSceneBuilder.Build(doc, TestContext.Current.CancellationToken);
+
+ var stroke = Assert.IsType<StrokePrimitive>(Assert.Single(scene.Items));
+ Assert.Equal(new SKColor(0, 0, 255), stroke.Color);
+ Assert.Equal(5, stroke.Figures.Single().Start.Y, 9);
+ }
+
+ [Fact]
+ public void Inserts_apply_base_point_scale_rotation_and_arrays()
+ {
+ var doc = new CadDocument();
+ var block = new BlockRecord("Square");
+ block.BlockEntity.BasePoint = new XYZ(1, 1, 0);
+ var square = new LwPolyline(new LwPolyline.Vertex(1, 1), new LwPolyline.Vertex(2, 1), new LwPolyline.Vertex(2, 2), new LwPolyline.Vertex(1, 2)) { IsClosed = true };
+ block.Entities.Add(square);
+ doc.BlockRecords.Add(block);
+ // Base point (1,1) lands on (10,10); scaled ×2 and turned 90°, the unit square covers x 8..10, y 10..12 ...
+ doc.Entities.Add(new Insert(block) { InsertPoint = new XYZ(10, 10, 0), XScale = 2, YScale = 2, Rotation = Math.PI / 2 });
+ // ... and a 2 × 3 array (column spacing 10, row spacing 20) of the plain square from (100,0).
+ doc.Entities.Add(new Insert(block) { InsertPoint = new XYZ(100, 0, 0), ColumnCount = 3, RowCount = 2, ColumnSpacing = 10, RowSpacing = 20 });
+
+ var scene = CadSceneBuilder.Build(doc, TestContext.Current.CancellationToken);
+
+ Assert.Equal(7, scene.Items.Count);
+ var first = Bounds(scene.Items[0]);
+ Assert.Equal((8.0, 10.0, 10.0, 12.0), (Math.Round(first.MinX, 9), Math.Round(first.MinY, 9), Math.Round(first.MaxX, 9), Math.Round(first.MaxY, 9)));
+ Assert.Equal(8, scene.Extents.MinX, 9);
+ Assert.Equal(121, scene.Extents.MaxX, 9); // last column at 100 + 2·10, one unit wide
+ Assert.Equal(21, scene.Extents.MaxY, 9); // second row at 20
+ }
+
+ [Fact]
+ public void Dimensions_draw_their_block_with_the_measurement()
+ {
+ var scene = CadSceneBuilder.Build(CadBuilder.Sample(), TestContext.Current.CancellationToken);
+
+ var texts = scene.Items.OfType<TextPrimitive>().Select(t => t.Text).ToList();
+ Assert.Contains(texts, t => t.Contains("100", StringComparison.Ordinal)); // the aligned dimension's value
+ Assert.True(scene.Items.OfType<FillPrimitive>().Count() >= 3, "the solid hatch and two arrowheads");
+ Assert.Empty(scene.Skipped);
+ Assert.False(scene.Truncated);
+ }
+
+ [Fact]
+ public void Line_types_and_pattern_hatches_are_drawn()
+ {
+ var scene = CadSceneBuilder.Build(CadBuilder.Sample(), TestContext.Current.CancellationToken);
+
+ var dashed = Assert.Single(scene.Items.OfType<StrokePrimitive>(), s => s.Dashes is not null);
+ Assert.Equal([5.0, -2.5], dashed.Dashes!);
+
+ // 45° lines 2 units apart across a 20 × 20 square (28.3 units across its diagonal): about 15 lines,
+ // generated over the bounding box and clipped to the boundary when drawn.
+ var hatch = Assert.Single(scene.Items.OfType<HatchLinesPrimitive>());
+ Assert.InRange(hatch.Lines.Count, 14, 18);
+ Assert.Single(hatch.Boundary);
+
+ // The clamped spline runs from its first to its last control point and stays inside their hull
+ // (lowest point of this Bézier at y ≈ -22.89); the ellipse arc runs three quarters from its major axis end.
+ var figures = scene.Items.OfType<StrokePrimitive>().SelectMany(s => s.Figures).ToList();
+ var spline = Assert.Single(figures, f => f.Start == new Vec2(0, -20));
+ Assert.Equal(60, spline.End.X, 9);
+ Assert.Equal(-20, spline.End.Y, 9);
+ var splineBox = Box2.Empty;
+ spline.AddTo(ref splineBox);
+ Assert.InRange(splineBox.MinY, -22.89, -22.85);
+ var ellipse = Assert.Single(figures, f => f.Start == new Vec2(97, -20));
+ Assert.Equal(85, ellipse.End.X, 9);
+ Assert.Equal(-26, ellipse.End.Y, 9);
+ }
+
+ [Fact]
+ public void Mtext_formatting_codes_are_decoded()
+ {
+ var format = new MTextFormat(2, null, null, null, false, false, 1, 0);
+
+ var paragraphs = CadTextCodes.ParseMText("{\\fArial|b1|i0;Bold} \\H3x;Big\\Pline \\S1/2; %%d \\U+AC00\\~end", format);
+
+ Assert.Equal(2, paragraphs.Count);
+ Assert.Equal("Bold", paragraphs[0][0].Text);
+ Assert.True(paragraphs[0][0].Format.Bold);
+ Assert.Equal("Arial", paragraphs[0][0].Format.FontFamily);
+ Assert.Equal(6, paragraphs[0][^1].Format.Height); // \H3x of 2
+ Assert.Equal("line 1/2 ° 가\u00A0end", string.Concat(paragraphs[1].Select(r => r.Text)));
+ Assert.Equal("Ø25 ±0.1 45°", CadTextCodes.DecodeText("%%c25 %%p0.1 45%%d"));
+ }
+
+ [Fact]
+ public void Rational_spline_reproduces_a_circle()
+ {
+ // A quarter circle as a rational quadratic B-spline (weights 1, √2/2, 1).
+ var points = CadCurves.SampleNurbs(2, [new Vec3(1, 0, 0), new Vec3(1, 1, 0), new Vec3(0, 1, 0)], [0, 0, 0, 1, 1, 1], [1, Math.Sqrt(0.5), 1]);
+
+ Assert.True(points.Count > 5);
+ Assert.All(points, p => Assert.Equal(1, Math.Sqrt(p.X * p.X + p.Y * p.Y), 9));
+ Assert.Equal(new Vec3(0, 1, 0), points[^1]);
+ }
+
+ [Fact]
+ public void Bulge_arcs_follow_the_autocad_convention()
+ {
+ // Bulge 1 = counter-clockwise half circle; the centre lies halfway.
+ var (center, radius, start, sweep) = CadCurves.BulgeArc(new Vec2(0, 0), new Vec2(10, 0), 1);
+
+ Assert.Equal(5, center.X, 9);
+ Assert.Equal(0, center.Y, 9);
+ Assert.Equal(5, radius, 9);
+ Assert.Equal(Math.PI, Math.Abs(start), 9);
+ Assert.Equal(Math.PI, sweep, 9);
+ }
+
+ [Fact]
+ public void Korean_text_uses_a_font_with_hangul()
+ {
+ var primary = CadFonts.Resolve(null, false, false);
+ var runs = CadFonts.Layout("도면 ABC", primary);
+ var hangul = runs.First(r => r.Text.Contains('도'));
+ Assert.SkipUnless(hangul.Typeface.ContainsGlyph('도'), "no font with Hangul on this machine");
+
+ Assert.True(hangul.Advance > 0);
+ Assert.Contains(runs, r => r.Text.Contains('A') && r.Typeface.ContainsGlyph('A'));
+ }
+
+ // ───────────────────────── Helpers ─────────────────────────
+
+ private static IEnumerable<OpCodeName> Operators(CSequence sequence)
+ {
+ foreach (var item in sequence)
+ {
+ if (item is COperator op)
+ yield return op.OpCode.OpCodeName;
+ else if (item is CSequence inner)
+ foreach (var nested in Operators(inner))
+ yield return nested;
+ }
+ }
+
+ private static Box2 Bounds(ScenePrimitive primitive)
+ {
+ var box = Box2.Empty;
+ foreach (var figure in ((StrokePrimitive)primitive).Figures)
+ figure.AddTo(ref box);
+ return box;
+ }
+
+ /// <summary>Drawn (not white), blue and red pixels plus the bounding box of everything drawn.</summary>
+ private static (int Ink, int Blue, int Red, (int Width, int Height) Box) CountPixels(MagickImage image)
+ {
+ using var pixels = image.GetPixels();
+ var bytes = pixels.ToByteArray(PixelMapping.RGB)!;
+ int ink = 0, blue = 0, red = 0;
+ int minX = int.MaxValue, minY = int.MaxValue, maxX = -1, maxY = -1;
+ var width = (int)image.Width;
+ for (var i = 0; i < bytes.Length; i += 3)
+ {
+ int r = bytes[i], g = bytes[i + 1], b = bytes[i + 2];
+ if (r > 240 && g > 240 && b > 240)
+ continue;
+ var x = i / 3 % width;
+ var y = i / 3 / width;
+ (minX, minY, maxX, maxY) = (Math.Min(minX, x), Math.Min(minY, y), Math.Max(maxX, x), Math.Max(maxY, y));
+ ink++;
+ if (b > 150 && r < 100 && g < 100)
+ blue++;
+ if (r > 150 && g < 100 && b < 100)
+ red++;
+ }
+ return (ink, blue, red, maxX < 0 ? (0, 0) : (maxX - minX + 1, maxY - minY + 1));
+ }
+}