From c751ea4460d25de0c9e419a90010cd9e952d1bcb Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 02:07:33 +0300 Subject: [PATCH 01/19] Add the DwgIO.Scene adapter and the dwgio scene command Turn a drawing into a neutral IOScene scene document, the shared scene model of the IOExtend tools, the way RvtIO.Scene and NwcIO.Scene do: - DwgSceneReader converts a DwgDocument: one element per decoded entity with the handle as SourceId, LINE and POINT as line and point geometries, CIRCLE and ARC tessellated with shared line indices, ACI colours on the placements and the read diagnostics forwarded. - DwgSceneOptions scales coordinates to metres by a caller-chosen unit (a DWG names no unit); DwgSceneResult carries the scene, the counters and the conversion report. - dwgio scene writes the scene document with --unit mm|cm|m|ft|in. - The scene passes the IOScene structural validation and round-trips through the IOScene JSON format; tests cover all of it. --- CHANGELOG.md | 8 + Directory.Packages.props | 5 + DwgIO.slnx | 1 + README.md | 24 +- docs/getting-started.md | 12 + docs/public-api.md | 22 ++ src/DwgIO.Cli/DwgIO.Cli.csproj | 1 + src/DwgIO.Cli/Program.cs | 64 +++++- src/DwgIO.Scene/DwgAciPalette.cs | 51 +++++ src/DwgIO.Scene/DwgIO.Scene.csproj | 35 +++ src/DwgIO.Scene/DwgSceneOptions.cs | 21 ++ src/DwgIO.Scene/DwgSceneReader.cs | 274 +++++++++++++++++++++++ src/DwgIO.Scene/DwgSceneResult.cs | 34 +++ tests/DwgIO.Tests/DwgIO.Tests.csproj | 1 + tests/DwgIO.Tests/DwgSceneReaderTests.cs | 223 ++++++++++++++++++ 15 files changed, 773 insertions(+), 3 deletions(-) create mode 100644 src/DwgIO.Scene/DwgAciPalette.cs create mode 100644 src/DwgIO.Scene/DwgIO.Scene.csproj create mode 100644 src/DwgIO.Scene/DwgSceneOptions.cs create mode 100644 src/DwgIO.Scene/DwgSceneReader.cs create mode 100644 src/DwgIO.Scene/DwgSceneResult.cs create mode 100644 tests/DwgIO.Tests/DwgSceneReaderTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index d950a3a..bdcb187 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,14 @@ API between minor releases. ## [Unreleased] +### Added +- `DwgIO.Scene` package: converts a drawing into a neutral [IOScene](https://www.nuget.org/packages/IOScene) scene + document, the shared scene model of the IOExtend tools. One element per decoded entity with the handle as + `SourceId`, line and point geometries scaled to metres (`DwgSceneOptions.LengthUnit`), ACI colours on the + placements and a conversion report (`DwgSceneResult`). The scene passes the IOScene structural validation and + round-trips through the IOScene JSON format. +- `dwgio scene [--unit mm|cm|m|ft|in]` writes the scene document. + ### Fixed - Packed 16-bit and 32-bit integers in their full-width form are read little-endian. They were read with their bytes reversed, so entity records that store a colour, extended data size or reactor count in that form were decoded from diff --git a/Directory.Packages.props b/Directory.Packages.props index e6746b9..daf5c72 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -9,6 +9,11 @@ + + + + + diff --git a/DwgIO.slnx b/DwgIO.slnx index 5835494..5cd14c6 100644 --- a/DwgIO.slnx +++ b/DwgIO.slnx @@ -1,5 +1,6 @@ + diff --git a/README.md b/README.md index 5f79c84..b877fb3 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ DwgIO is a .NET library and command line tool that reads Autodesk AutoCAD drawin - Parses drawing metadata: summary information with custom properties and dates, application information, file dependencies and the embedded thumbnail preview. - Lists the objects of a drawing through its handle map and decodes the geometry of LINE, CIRCLE, ARC and POINT entities. - Writes a JSON export of the metadata, the section catalog and the decoded entities. +- Converts a drawing into a neutral [IOScene](https://www.nuget.org/packages/IOScene) scene document (`DwgIO.Scene` package): geometry in metres, ACI entity colours, one element per entity with its handle. ## Install @@ -21,13 +22,14 @@ Install the command line tool: dotnet tool install --global DwgIO.Cli ``` -and add the library to a .NET project: +and add the libraries to a .NET project: ```sh dotnet add package DwgIO +dotnet add package DwgIO.Scene ``` -The library targets .NET 8 and .NET 10. It uses managed code without native dependencies or Windows-only APIs and supports Windows, Linux and macOS. Tests currently run on Windows. +The libraries target .NET 8 and .NET 10. They use managed code without native dependencies or Windows-only APIs and support Windows, Linux and macOS. Tests currently run on Windows. ## Command line @@ -55,6 +57,12 @@ Save the embedded thumbnail preview. Without an extension, `.png`, `.wmf` or `.b dwgio preview drawing.dwg thumbnail ``` +Export a neutral IOScene scene document (geometry in metres, ACI colours, one element per decoded entity). `--unit` names the drawing unit the coordinates are scaled from — one of `mm`, `cm`, `m` (default), `ft`, `in`: + +```sh +dwgio scene drawing.dwg drawing.scene.json --unit mm +``` + Errors go to standard error. ### Exit codes @@ -96,6 +104,17 @@ foreach (var entity in doc.Entities) The JSON export is `DwgJsonExporter` in the `DwgIO.Json` namespace. See [Getting started](docs/getting-started.md) and [Public API](docs/public-api.md) for the supported types. +The scene export is `DwgSceneReader` in the `DwgIO.Scene` package. It converts a drawing into an `IOScene.SceneDocument` — the neutral scene model of the IOExtend tools, shared with RvtIO and NwcIO: + +```csharp +using DwgIO.Scene; + +var scene = DwgSceneReader.Read("drawing.dwg", new DwgSceneOptions { LengthUnit = "mm" }); +IOScene.SceneJson.Save(scene.Document, "drawing.scene.json"); +``` + +Every coordinate is scaled to metres by `LengthUnit` (a DWG stores plain numbers, so the unit is a caller decision and `UnitAssumed` records it), each entity becomes an element with its handle as `SourceId`, and LINE, CIRCLE, ARC and POINT become line and point geometries with their ACI colour. + The documentation site with the API reference is at . [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/IOExtend/DwgIO) offers an automatically generated overview of the repository. ## Status @@ -111,6 +130,7 @@ The documentation site with the API reference is at + diff --git a/src/DwgIO.Cli/Program.cs b/src/DwgIO.Cli/Program.cs index f2e48aa..6be8a9b 100644 --- a/src/DwgIO.Cli/Program.cs +++ b/src/DwgIO.Cli/Program.cs @@ -1,6 +1,8 @@ using DwgIO; using DwgIO.Json; using DwgIO.Model; +using DwgIO.Scene; +using IOScene; namespace DwgIO.Cli; @@ -27,6 +29,7 @@ private static int Main(string[] args) "inspect" => Inspect(args), "extract" => Extract(args), "preview" => Preview(args), + "scene" => Scene(args), _ => Export(args), }; } @@ -59,9 +62,11 @@ private static void PrintUsage() Usage: dwgio inspect Print version + section table - dwgio Export metadata + section catalog to JSON + dwgio Export metadata, section catalog and decoded entities to JSON dwgio extract
Write a named section's decompressed bytes dwgio preview Write the embedded thumbnail image + dwgio scene [--unit u] Export a neutral IOScene scene document + (u: mm, cm, m (default), ft or in) Sections are named as stored, e.g. AcDb:Header, AcDb:Classes, AcDb:SummaryInfo. """); @@ -188,6 +193,63 @@ private static int Extract(string[] args) return ExitOk; } + private static int Scene(string[] args) + { + string? unit = null; + var positional = new List(3); + for (int i = 1; i < args.Length; i++) + { + if (args[i] == "--unit") + { + if (i + 1 >= args.Length) + { + Console.Error.WriteLine("error: --unit needs a value (mm, cm, m, ft or in)."); + return ExitUsage; + } + + unit = args[++i]; + } + else + { + positional.Add(args[i]); + } + } + + if (positional.Count != 2) + { + PrintUsage(); + return ExitUsage; + } + + var options = new DwgSceneOptions(); + if (unit is not null) + { + if (!DwgSceneReader.IsSupportedUnit(unit)) + { + Console.Error.WriteLine($"error: unknown length unit '{unit}'. Use mm, cm, m, ft or in."); + return ExitUsage; + } + + options.LengthUnit = unit; + } + + var result = DwgSceneReader.Read(positional[0], options); + SceneJson.Save(result.Document, positional[1]); + Console.WriteLine( + $"{result.Document.Title}: {result.ElementCount} elements ({result.ElementsWithGeometry} with geometry) -> {positional[1]}"); + foreach (var diagnostic in result.Diagnostics.Take(5)) + { + Console.WriteLine($" {diagnostic.Severity.ToString().ToLowerInvariant()}: {diagnostic.Message}"); + } + + if (result.Diagnostics.Count > 5) + { + Console.WriteLine($" ... and {result.Diagnostics.Count - 5} more"); + } + + return ExitOk; + } + private static int Preview(string[] args) { if (args.Length != 3) diff --git a/src/DwgIO.Scene/DwgAciPalette.cs b/src/DwgIO.Scene/DwgAciPalette.cs new file mode 100644 index 0000000..f0204b0 --- /dev/null +++ b/src/DwgIO.Scene/DwgAciPalette.cs @@ -0,0 +1,51 @@ +namespace DwgIO.Scene; + +/// +/// The AutoCAD Color Index palette (DXF 62): the fixed RGB values of indexes 1-255, as AutoCAD shows them. +/// Position in the table is the index. Index 0 (BYBLOCK) and 256 (BYLAYER) are not in the table: they name a +/// colour source, not a colour; the scene reader leaves the colour to the consumer until layers and blocks are +/// decoded. +/// +/// +/// Values from the published AutoCAD palette: fixed values for 1-9, 24 hue rows of 10 shades for 10-249 and the +/// 250-255 grays; duplicated pairs (1 and 10, 2 and 50, 7 and 255, ...) share their RGB. +/// +internal static class DwgAciPalette +{ + private static readonly int[] Rgb = + [ + 0x000000, 0xFF0000, 0xFFFF00, 0x00FF00, 0x00FFFF, 0x0000FF, 0xFF00FF, 0xFFFFFF, 0x808080, 0xC0C0C0, // 0 = placeholder; 1-9 = base colours + 0xFF0000, 0xFF8080, 0xA60000, 0xA65353, 0x800000, 0x804040, 0x4D0000, 0x4D2626, 0x260000, 0x261313, // 10-19 + 0xFF4000, 0xFF9F80, 0xA62900, 0xA66853, 0x802000, 0x805040, 0x4D1300, 0x4D3026, 0x260A00, 0x261813, // 20-29 + 0xFF8000, 0xFFBF80, 0xA65300, 0xA67C53, 0x804000, 0x806040, 0x4D2600, 0x4D3926, 0x261300, 0x261D13, // 30-39 + 0xFFBF00, 0xFFDF80, 0xA67C00, 0xA69153, 0x806000, 0x807040, 0x4D3900, 0x4D4326, 0x261D00, 0x262113, // 40-49 + 0xFFFF00, 0xFFFF80, 0xA6A600, 0xA6A653, 0x808000, 0x808040, 0x4D4D00, 0x4D4D26, 0x262600, 0x262613, // 50-59 + 0xBFFF00, 0xDFFF80, 0x7CA600, 0x91A653, 0x608000, 0x708040, 0x394D00, 0x434D26, 0x1D2600, 0x212613, // 60-69 + 0x80FF00, 0xBFFF80, 0x53A600, 0x7CA653, 0x408000, 0x608040, 0x264D00, 0x394D26, 0x132600, 0x1D2613, // 70-79 + 0x40FF00, 0x9FFF80, 0x29A600, 0x68A653, 0x208000, 0x508040, 0x134D00, 0x304D26, 0x0A2600, 0x182613, // 80-89 + 0x00FF00, 0x80FF80, 0x00A600, 0x53A653, 0x008000, 0x408040, 0x004D00, 0x264D26, 0x002600, 0x132613, // 90-99 + 0x00FF40, 0x80FF9F, 0x00A629, 0x53A668, 0x008020, 0x408050, 0x004D13, 0x264D30, 0x00260A, 0x132618, // 100-109 + 0x00FF80, 0x80FFBF, 0x00A653, 0x53A67C, 0x008040, 0x408060, 0x004D26, 0x264D39, 0x002613, 0x13261D, // 110-119 + 0x00FFBF, 0x80FFDF, 0x00A67C, 0x53A691, 0x008060, 0x408070, 0x004D39, 0x264D43, 0x00261D, 0x132621, // 120-129 + 0x00FFFF, 0x80FFFF, 0x00A6A6, 0x53A6A6, 0x008080, 0x408080, 0x004D4D, 0x264D4D, 0x002626, 0x132626, // 130-139 + 0x00BFFF, 0x80DFFF, 0x007CA6, 0x5391A6, 0x006080, 0x407080, 0x00394D, 0x26434D, 0x001D26, 0x132126, // 140-149 + 0x0080FF, 0x80BFFF, 0x0053A6, 0x537CA6, 0x004080, 0x406080, 0x00264D, 0x26394D, 0x001326, 0x131D26, // 150-159 + 0x0040FF, 0x809FFF, 0x0029A6, 0x5368A6, 0x002080, 0x405080, 0x00134D, 0x26304D, 0x000A26, 0x131826, // 160-169 + 0x0000FF, 0x8080FF, 0x0000A6, 0x5353A6, 0x000080, 0x404080, 0x00004D, 0x26264D, 0x000026, 0x131326, // 170-179 + 0x4000FF, 0x9F80FF, 0x2900A6, 0x6853A6, 0x200080, 0x504080, 0x13004D, 0x30264D, 0x0A0026, 0x181326, // 180-189 + 0x8000FF, 0xBF80FF, 0x5300A6, 0x7C53A6, 0x400080, 0x604080, 0x26004D, 0x39264D, 0x130026, 0x1D1326, // 190-199 + 0xBF00FF, 0xDF80FF, 0x7C00A6, 0x9153A6, 0x600080, 0x704080, 0x39004D, 0x43264D, 0x1D0026, 0x211326, // 200-209 + 0xFF00FF, 0xFF80FF, 0xA600A6, 0xA653A6, 0x800080, 0x804080, 0x4D004D, 0x4D264D, 0x260026, 0x261326, // 210-219 + 0xFF00BF, 0xFF80DF, 0xA6007C, 0xA65391, 0x800060, 0x804070, 0x4D0039, 0x4D2643, 0x26001D, 0x261321, // 220-229 + 0xFF0080, 0xFF80BF, 0xA60053, 0xA6537C, 0x800040, 0x804060, 0x4D0026, 0x4D2639, 0x260013, 0x26131D, // 230-239 + 0xFF0040, 0xFF809F, 0xA60029, 0xA65368, 0x800020, 0x804050, 0x4D0013, 0x4D2630, 0x26000A, 0x261318, // 240-249 + 0x545454, 0x767676, 0x989898, 0xBBBBBB, 0xDDDDDD, 0xFFFFFF, // 250-255 = grays + ]; + + /// RGB of an AutoCAD Color Index; index 0 and 256 resolve to white (index 7). + public static (byte R, byte G, byte B) RgbOf(int index) + { + int stored = Rgb[index is > 0 and < 256 ? index : 7]; + return ((byte)(stored >> 16 & 0xFF), (byte)(stored >> 8 & 0xFF), (byte)(stored & 0xFF)); + } +} diff --git a/src/DwgIO.Scene/DwgIO.Scene.csproj b/src/DwgIO.Scene/DwgIO.Scene.csproj new file mode 100644 index 0000000..0520f69 --- /dev/null +++ b/src/DwgIO.Scene/DwgIO.Scene.csproj @@ -0,0 +1,35 @@ + + + + Turns an AutoCAD drawing read by DwgIO into an IOScene scene document: decoded model-space geometry as lines and points, drawing-unit scale, ACI entity colours and producer metadata. + dwg;autocad;autodesk;cad;ioscene;scene;bim + true + + $(NoWarn);NU5104 + + + + + + + + + + + + + + + + + + + + + <_Pinned Include="@(_ProjectReferencesWithVersions)">[%(_ProjectReferencesWithVersions.ProjectVersion)] + <_ProjectReferencesWithVersions Remove="@(_ProjectReferencesWithVersions)" /> + <_ProjectReferencesWithVersions Include="@(_Pinned)" /> + + + + diff --git a/src/DwgIO.Scene/DwgSceneOptions.cs b/src/DwgIO.Scene/DwgSceneOptions.cs new file mode 100644 index 0000000..9a00f22 --- /dev/null +++ b/src/DwgIO.Scene/DwgSceneOptions.cs @@ -0,0 +1,21 @@ +namespace DwgIO.Scene; + +/// Options of the DWG → scene conversion. +public sealed class DwgSceneOptions +{ + /// + /// Length unit of the drawing's coordinates and the scale the conversion applies, as one value: + /// mm, cm, m (the default, one drawing unit = one metre), ft or in. + /// A DWG stores plain numbers without a unit; the header variable that names the unit is not decoded yet, + /// so the unit is a caller decision. The scene records the choice in + /// and reports it in . + /// + public string LengthUnit { get; set; } = "m"; + + /// + /// Key of the scene model: stable, unique and non-empty, written to . The + /// default is the source file name without directory. A key must be given when a document converted from memory + /// is read, which has no file name. + /// + public string? ModelKey { get; set; } +} diff --git a/src/DwgIO.Scene/DwgSceneReader.cs b/src/DwgIO.Scene/DwgSceneReader.cs new file mode 100644 index 0000000..9a14ec3 --- /dev/null +++ b/src/DwgIO.Scene/DwgSceneReader.cs @@ -0,0 +1,274 @@ +using System.Globalization; +using System.Reflection; +using DwgIO.Model; +using IOScene; +using Vector3d = IOScene.Vector3d; +using RgbaColor = IOScene.RgbaColor; + +namespace DwgIO.Scene; + +/// Converts an AutoCAD drawing, or a read by DwgIO, into a . +/// +/// The scene has one : Key and Name are , +/// else the file name; SourceFormat is dwg; Application is the producer from +/// AcDb:AppInfo; CreatedAt is the summary-info creation time in UTC. The drawing's entities become +/// flat scene elements with the handle as ; LINE, CIRCLE, ARC and POINT become +/// line and point geometries, tessellated for the round kinds. Every coordinate is scaled to metres by +/// ; the drawing itself names no unit, so the scene records the choice. +/// +public static class DwgSceneReader +{ + private static readonly string Producer = "DwgIO.Scene " + + typeof(DwgSceneReader).Assembly.GetCustomAttribute()!.InformationalVersion.Split('+')[0]; + + // A full circle tessellated into 64 segments (5.6 degrees); an arc gets one segment per 5 degrees, at least 8. + private const int CircleSegments = 64; + private const double ArcRadiansPerSegment = 5.0 * Math.PI / 180.0; + private const int MinArcSegments = 8; + + /// Reads the drawing at with and converts it. + /// The drawing file. + /// Conversion options; null uses the defaults. + /// The scene with a report of the conversion. + /// is empty. + public static DwgSceneResult Read(string path, DwgSceneOptions? options = null) + { + ArgumentException.ThrowIfNullOrEmpty(path); + return Convert(DwgDocument.Open(path), options?.ModelKey ?? Path.GetFileName(path), path, options ?? new DwgSceneOptions()); + } + + /// + /// Converts , which has no file name, so is + /// required. Give a document opened with the default ; a document read with + /// off has no entities, and the scene holds the drawing without geometry. + /// + /// The document. + /// Conversion options with . + /// The scene with a report of the conversion. + /// is null or empty. + public static DwgSceneResult Read(DwgDocument document, DwgSceneOptions options) + { + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(options); + if (string.IsNullOrEmpty(options.ModelKey)) + { + throw new ArgumentException("DwgSceneOptions.ModelKey must not be empty; a document converted from memory has no file name.", nameof(options)); + } + + return Convert(document, options.ModelKey, null, options); + } + + private static DwgSceneResult Convert(DwgDocument document, string key, string? path, DwgSceneOptions options) + { + double metresPerUnit = MetresPerUnit(options.LengthUnit); + var scene = new SceneDocument { Title = key }; + var diagnostics = new List(); + + scene.Models.Add(new SceneModel + { + Id = 1, + Key = key, + Name = key, + Path = path, + SourceFormat = "dwg", + Producer = Producer, + SourceLengthUnit = options.LengthUnit, + Application = document.AppInfo is { Name.Length: > 0 } appInfo ? appInfo.Name : null, + CreatedAt = document.SummaryInfo?.CreatedUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture), + }); + + foreach (string message in document.Diagnostics) + { + // Findings from the read: the scene is usable but something in the drawing was skipped. + diagnostics.Add(new SceneDiagnostic(SceneSeverity.Warning, "document", $"{key}: {message}")); + } + + int elementCount = 0; + int elementsWithGeometry = 0; + var withoutGeometry = new SortedDictionary(StringComparer.Ordinal); + int nonFinite = 0; + int geometryId = 0; + + foreach (var entity in document.Entities) + { + elementCount++; + var element = new SceneElement + { + Id = elementCount, + ModelId = 1, + SourceId = entity.Handle.ToString("X", CultureInfo.InvariantCulture), + Name = $"{entity.TypeName} {entity.Handle:X}", + Category = entity.TypeName, + TypeName = entity.TypeName, + }; + scene.Elements.Add(element); + + Vector3d[]? vertices = entity.Kind switch + { + DwgEntityKind.Line when entity.Geometry is { Length: 6 } g => LineVertices(g, metresPerUnit), + DwgEntityKind.Circle when entity.Geometry is { Length: 4 } g => CircleVertices(g, metresPerUnit), + DwgEntityKind.Arc when entity.Geometry is { Length: 6 } g => ArcVertices(g, metresPerUnit), + DwgEntityKind.Point when entity.Geometry is { Length: 3 } g => PointVertices(g, metresPerUnit), + _ => null, + }; + if (vertices is null) + { + if (entity.Kind == DwgEntityKind.Unknown || entity.Geometry is null) + { + withoutGeometry[entity.TypeName] = withoutGeometry.TryGetValue(entity.TypeName, out int n) ? n + 1 : 1; + } + + continue; + } + + if (!vertices.All(IsFinite)) + { + // The IOScene contract forbids non-finite coordinates; the core JSON export writes them as null, + // the scene drops the geometry and reports it. + nonFinite++; + continue; + } + + elementsWithGeometry++; + geometryId++; + bool isPoint = entity.Kind == DwgEntityKind.Point; + // The contract wants whole pairs for non-indexed lines; polylines share their joints through indices. + IReadOnlyList indices = entity.Kind switch + { + DwgEntityKind.Circle => SharedIndices(CircleSegments, closed: true), + DwgEntityKind.Arc => SharedIndices(vertices!.Length, closed: false), + _ => [], + }; + var geometry = new SceneGeometry + { + Id = geometryId, + Topology = isPoint ? SceneTopology.Points : SceneTopology.Lines, + Vertices = vertices!, + Indices = indices, + }; + scene.Geometries.Add(geometry); + scene.Instances.Add(new SceneInstance + { + ElementId = element.Id, + GeometryId = geometry.Id, + Color = ColourOf(entity.ColorIndex), + }); + } + + if (withoutGeometry.Count > 0) + { + string kinds = string.Join(", ", withoutGeometry.Select(kvp => $"{kvp.Key} {kvp.Value}")); + diagnostics.Add(new SceneDiagnostic(SceneSeverity.Info, "entities-without-geometry", + $"{withoutGeometry.Values.Sum()} entities have no geometry the scene places yet ({kinds}).")); + } + + if (nonFinite > 0) + { + diagnostics.Add(new SceneDiagnostic(SceneSeverity.Warning, "non-finite-geometry", + $"{nonFinite} entities had non-finite coordinates and are placed without geometry.")); + } + + return new DwgSceneResult + { + Document = scene, + Diagnostics = diagnostics, + ElementCount = elementCount, + ElementsWithGeometry = elementsWithGeometry, + EntitiesWithoutGeometry = withoutGeometry.Values.Sum(), + LengthUnit = options.LengthUnit, + MetresPerUnit = metresPerUnit, + UnitAssumed = true, + }; + } + + /// Tells whether accepts . + public static bool IsSupportedUnit(string unit) => unit is "mm" or "cm" or "m" or "ft" or "in"; + + private static double MetresPerUnit(string unit) => unit switch + { + "mm" => 0.001, + "cm" => 0.01, + "m" => 1.0, + "ft" => 0.3048, + "in" => 0.0254, + _ => throw new ArgumentException($"DwgSceneOptions.LengthUnit '{unit}' is not supported; use mm, cm, m, ft or in.", nameof(unit)), + }; + + private static RgbaColor? ColourOf(int colorIndex) + { + if (colorIndex is <= 0 or >= 256) + { + // BYBLOCK (0) and BYLAYER (256) have no colour of their own; the scene leaves the choice to the + // consumer until layers and blocks are decoded. + return null; + } + + (byte r, byte g, byte b) = DwgAciPalette.RgbOf(colorIndex); + return new RgbaColor(r, g, b); + } + + private static Vector3d[] LineVertices(double[] g, double scale) => + [ + new(g[0] * scale, g[1] * scale, g[2] * scale), + new(g[3] * scale, g[4] * scale, g[5] * scale), + ]; + + private static Vector3d[] CircleVertices(double[] g, double scale) + { + double cx = g[0] * scale, cy = g[1] * scale, cz = g[2] * scale; + double radius = g[3] * scale; + var vertices = new Vector3d[CircleSegments]; + for (int i = 0; i < CircleSegments; i++) + { + double angle = 2.0 * Math.PI * i / CircleSegments; + vertices[i] = new Vector3d(cx + radius * Math.Cos(angle), cy + radius * Math.Sin(angle), cz); + } + + return vertices; + } + + private static Vector3d[] ArcVertices(double[] g, double scale) + { + double cx = g[0] * scale, cy = g[1] * scale, cz = g[2] * scale; + double radius = g[3] * scale; + double start = g[4]; + double span = g[5] - g[4]; + while (span <= 0) + { + span += 2.0 * Math.PI; + } + + int segments = Math.Clamp((int)Math.Ceiling(span / ArcRadiansPerSegment), MinArcSegments, CircleSegments * 4); + var vertices = new Vector3d[segments + 1]; + for (int i = 0; i <= segments; i++) + { + double angle = start + span * i / segments; + vertices[i] = new Vector3d(cx + radius * Math.Cos(angle), cy + radius * Math.Sin(angle), cz); + } + + return vertices; + } + + private static Vector3d[] PointVertices(double[] g, double scale) => [new(g[0] * scale, g[1] * scale, g[2] * scale)]; + + /// Line indices of a tessellated circle (closed ring) or arc (open chain), sharing the joints. + private static List SharedIndices(int vertexCount, bool closed) + { + var indices = new List((vertexCount - (closed ? 0 : 1)) * 2); + for (int i = 0; i < vertexCount - 1; i++) + { + indices.Add(i); + indices.Add(i + 1); + } + + if (closed) + { + indices.Add(vertexCount - 1); + indices.Add(0); + } + + return indices; + } + + private static bool IsFinite(Vector3d v) => double.IsFinite(v.X) && double.IsFinite(v.Y) && double.IsFinite(v.Z); +} diff --git a/src/DwgIO.Scene/DwgSceneResult.cs b/src/DwgIO.Scene/DwgSceneResult.cs new file mode 100644 index 0000000..c0e4e97 --- /dev/null +++ b/src/DwgIO.Scene/DwgSceneResult.cs @@ -0,0 +1,34 @@ +using IOScene; + +namespace DwgIO.Scene; + +/// +/// The scene of a drawing and the report of the conversion: what was converted, what was left out and why. +/// +public sealed class DwgSceneResult +{ + /// The scene document, with one model per drawing. + public required SceneDocument Document { get; init; } + + /// Findings of the conversion, in the order they were made. + public IReadOnlyList Diagnostics { get; init; } = []; + + /// Number of elements the scene holds. + public int ElementCount { get; init; } + + /// Number of elements that carry at least one geometry. + public int ElementsWithGeometry { get; init; } + + /// Number of entities the drawing decoded but the scene left out, because the record had no usable + /// geometry or a kind the conversion does not place yet. + public int EntitiesWithoutGeometry { get; init; } + + /// The length unit the conversion used, e.g. m. + public string? LengthUnit { get; init; } + + /// Metres per drawing unit the conversion used, or null when unknown. + public double? MetresPerUnit { get; init; } + + /// True when the unit came from the default instead of the drawing, which never names its unit. + public bool UnitAssumed { get; init; } +} diff --git a/tests/DwgIO.Tests/DwgIO.Tests.csproj b/tests/DwgIO.Tests/DwgIO.Tests.csproj index 328f3a5..4d037cc 100644 --- a/tests/DwgIO.Tests/DwgIO.Tests.csproj +++ b/tests/DwgIO.Tests/DwgIO.Tests.csproj @@ -19,6 +19,7 @@ + diff --git a/tests/DwgIO.Tests/DwgSceneReaderTests.cs b/tests/DwgIO.Tests/DwgSceneReaderTests.cs new file mode 100644 index 0000000..2b1ff88 --- /dev/null +++ b/tests/DwgIO.Tests/DwgSceneReaderTests.cs @@ -0,0 +1,223 @@ +using DwgIO.Model; +using DwgIO.Scene; +using IOScene; +using Xunit; +using Vector3d = IOScene.Vector3d; + +namespace DwgIO.Tests; + +public class DwgSceneReaderTests +{ + private static DwgDocument CreateDocument(params DwgEntity[] entities) => + new( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + entities); + + private static DwgEntity Entity(ulong handle, DwgEntityKind kind, string typeName, double[] geometry, int colorIndex = 256) => + new() + { + Handle = handle, + TypeCode = 0x13, + TypeName = typeName, + Kind = kind, + Geometry = geometry, + ColorIndex = colorIndex, + }; + + [Fact] + public void Read_ConvertsLineAndPointToSceneGeometries() + { + var document = CreateDocument( + Entity(0x2A, DwgEntityKind.Line, "LINE", [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), + Entity(0x2B, DwgEntityKind.Point, "POINT", [7.0, 8.0, 9.0])); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic" }); + + var scene = result.Document; + var model = Assert.Single(scene.Models); + Assert.Equal("synthetic", model.Key); + Assert.Equal("dwg", model.SourceFormat); + Assert.Equal("m", model.SourceLengthUnit); + Assert.Equal(2, result.ElementCount); + Assert.Equal(2, result.ElementsWithGeometry); + + var line = scene.Elements[0]; + Assert.Equal("2A", line.SourceId); + Assert.Equal("LINE 2A", line.Name); + Assert.Equal("LINE", line.Category); + Assert.Equal(SceneNodeKind.Element, line.Kind); + + var lineInstance = Assert.Single(scene.Instances, i => i.ElementId == line.Id); + var lineGeometry = scene.Geometries.Single(g => g.Id == lineInstance.GeometryId); + Assert.Equal(SceneTopology.Lines, lineGeometry.Topology); + Assert.Equal(2, lineGeometry.Vertices.Count); + Assert.Equal(new Vector3d(1.0, 2.0, 3.0), lineGeometry.Vertices[0]); + Assert.Equal(new Vector3d(4.0, 5.0, 6.0), lineGeometry.Vertices[1]); + + var point = scene.Elements[1]; + var pointInstance = Assert.Single(scene.Instances, i => i.ElementId == point.Id); + var pointGeometry = scene.Geometries.Single(g => g.Id == pointInstance.GeometryId); + Assert.Equal(SceneTopology.Points, pointGeometry.Topology); + Assert.Equal(new Vector3d(7.0, 8.0, 9.0), Assert.Single(pointGeometry.Vertices)); + } + + [Fact] + public void Read_TessellatesCircleAndArc() + { + var document = CreateDocument( + Entity(0x31, DwgEntityKind.Circle, "CIRCLE", [10.0, 20.0, 0.0, 5.0]), + Entity(0x32, DwgEntityKind.Arc, "ARC", [10.0, 20.0, 0.0, 5.0, 0.0, Math.PI])); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic" }); + + var circleGeometry = result.Document.Geometries[0]; + Assert.Equal(SceneTopology.Lines, circleGeometry.Topology); + Assert.Equal(64, circleGeometry.Vertices.Count); + // Vertex 0 sits at angle 0, so one radius to the right of the centre. + Assert.Equal(15.0, circleGeometry.Vertices[0].X, 9); + Assert.Equal(20.0, circleGeometry.Vertices[0].Y, 9); + + var arcGeometry = result.Document.Geometries[1]; + Assert.True(arcGeometry.Vertices.Count >= 9); + Assert.Equal(15.0, arcGeometry.Vertices[0].X, 9); + var last = arcGeometry.Vertices[^1]; + Assert.Equal(5.0, last.X, 9); // centre - radius at PI + Assert.Equal(20.0, last.Y, 9); + } + + [Fact] + public void Read_MapsAciColourOntoInstances() + { + var document = CreateDocument( + Entity(0x2A, DwgEntityKind.Line, "LINE", [0, 0, 0, 1, 0, 0], colorIndex: 1), + Entity(0x2B, DwgEntityKind.Line, "LINE", [0, 0, 0, 1, 0, 0], colorIndex: 256), + Entity(0x2C, DwgEntityKind.Line, "LINE", [0, 0, 0, 1, 0, 0], colorIndex: 0)); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic" }); + + Assert.Equal(new RgbaColor(255, 0, 0), result.Document.Instances[0].Color); + // BYLAYER (256) and BYBLOCK (0) have no colour of their own until layers are decoded. + Assert.Null(result.Document.Instances[1].Color); + Assert.Null(result.Document.Instances[2].Color); + } + + [Fact] + public void Read_UnitOptionScalesCoordinates() + { + var document = CreateDocument(Entity(0x2A, DwgEntityKind.Line, "LINE", [1000.0, 0.0, 0.0, 2000.0, 0.0, 0.0])); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic", LengthUnit = "mm" }); + + Assert.Equal("mm", result.LengthUnit); + Assert.Equal(0.001, result.MetresPerUnit); + Assert.Equal(1.0, result.Document.Geometries[0].Vertices[0].X, 9); + Assert.Equal(2.0, result.Document.Geometries[0].Vertices[1].X, 9); + } + + [Fact] + public void Read_UnknownUnit_Throws() + { + var document = CreateDocument(); + + Assert.Throws(() => DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic", LengthUnit = "parsec" })); + Assert.False(DwgSceneReader.IsSupportedUnit("parsec")); + } + + [Fact] + public void Read_MemoryDocumentWithoutModelKey_Throws() + { + var document = CreateDocument(); + + Assert.Throws(() => DwgSceneReader.Read(document, new DwgSceneOptions())); + } + + [Fact] + public void Read_ForwardsDocumentDiagnostics() + { + var document = CreateDocument(); + document.ReportDiagnostic("AcDb:Handles: unexpected end"); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic" }); + + var diagnostic = Assert.Single(result.Diagnostics); + Assert.Equal(SceneSeverity.Warning, diagnostic.Severity); + Assert.Equal("document", diagnostic.Code); + Assert.Contains("AcDb:Handles", diagnostic.Message); + } + + [Fact] + public void Read_EntityWithoutGeometry_CountsAndDiagnoses() + { + var document = CreateDocument( + Entity(0x2A, DwgEntityKind.Unknown, "TEXT", []), + Entity(0x2B, DwgEntityKind.Unknown, "TEXT", []), + Entity(0x2C, DwgEntityKind.Unknown, "INSERT", [])); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic" }); + + Assert.Equal(3, result.ElementCount); + Assert.Equal(0, result.ElementsWithGeometry); + Assert.Equal(3, result.EntitiesWithoutGeometry); + var diagnostic = Assert.Single(result.Diagnostics, d => d.Code == "entities-without-geometry"); + Assert.Contains("TEXT 2", diagnostic.Message); + } + + [Fact] + public void Read_NonFiniteGeometry_DropsGeometryAndReports() + { + var document = CreateDocument(Entity(0x2A, DwgEntityKind.Line, "LINE", [0.0, 0.0, 0.0, double.NaN, 0.0, 0.0])); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic" }); + + Assert.Empty(result.Document.Geometries); + Assert.Empty(result.Document.Instances); + Assert.Equal(1, result.ElementCount); + Assert.Equal(0, result.ElementsWithGeometry); + var diagnostic = Assert.Single(result.Diagnostics, d => d.Code == "non-finite-geometry"); + Assert.Equal(SceneSeverity.Warning, diagnostic.Severity); + } + + [Fact] + public void Read_ScenePassesTheIosceneContract() + { + var document = CreateDocument( + Entity(0x2A, DwgEntityKind.Line, "LINE", [1, 2, 3, 4, 5, 6], colorIndex: 1), + Entity(0x2B, DwgEntityKind.Arc, "ARC", [0, 0, 0, 2, 0.5, 1.5], colorIndex: 40), + Entity(0x2C, DwgEntityKind.Point, "POINT", [0, 0, 0])); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic" }); + + Assert.DoesNotContain(result.Diagnostics, d => d.Severity == SceneSeverity.Error); + Assert.DoesNotContain(result.Document.Validate(), d => d.Severity == SceneSeverity.Error); + } + + [Fact] + public void Read_SerializedScene_IsAnIosceneDocument() + { + var document = CreateDocument(Entity(0x2A, DwgEntityKind.Line, "LINE", [1, 2, 3, 4, 5, 6])); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic" }); + string json = SceneJson.Write(result.Document); + + using var parsed = System.Text.Json.JsonDocument.Parse(json); + Assert.Equal("ioscene", parsed.RootElement.GetProperty("Kind").GetString()); + Assert.Equal(1, parsed.RootElement.GetProperty("Format").GetInt32()); + + var roundTrip = SceneJson.Read(json); + Assert.Equal(result.Document.Models[0].Key, roundTrip.Models[0].Key); + Assert.Equal(result.Document.Instances.Count, roundTrip.Instances.Count); + } +} From 8b7ed944cd208df2a8fcf58ff5056a6960673f34 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 02:14:15 +0300 Subject: [PATCH 02/19] Export drawings to OBJ and GLB through the scene DwgSceneExport writes the IOScene scene of a drawing to Wavefront OBJ with an adjacent MTL colour library (both files written as a pair and moved in atomically) and to binary glTF, through the IOScene.Formats writers. The plain export command dispatches on the output extension, so dwgio drawing.dwg out.obj and out.glb work like out.json. IOScene.Formats ships as a preview and needs IOScene 0.1.1 or later, so the IOScene floor moves from 0.1.0 to 0.1.1. --- CHANGELOG.md | 3 + Directory.Packages.props | 6 +- README.md | 11 ++ docs/public-api.md | 4 +- src/DwgIO.Cli/Program.cs | 22 ++- src/DwgIO.Scene/DwgIO.Scene.csproj | 1 + src/DwgIO.Scene/DwgSceneExport.cs | 114 ++++++++++++++++ tests/DwgIO.Tests/DwgSceneExportTests.cs | 164 +++++++++++++++++++++++ 8 files changed, 319 insertions(+), 6 deletions(-) create mode 100644 src/DwgIO.Scene/DwgSceneExport.cs create mode 100644 tests/DwgIO.Tests/DwgSceneExportTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index bdcb187..e3694cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,9 @@ API between minor releases. placements and a conversion report (`DwgSceneResult`). The scene passes the IOScene structural validation and round-trips through the IOScene JSON format. - `dwgio scene [--unit mm|cm|m|ft|in]` writes the scene document. +- `DwgSceneExport.SaveObj`/`SaveGlb` write a drawing to Wavefront OBJ (with an adjacent MTL colour library, + written as a pair) and binary glTF (GLB) through the IOScene writers; `dwgio drawing.dwg out.obj` and + `dwgio drawing.dwg out.glb` dispatch by extension. ### Fixed - Packed 16-bit and 32-bit integers in their full-width form are read little-endian. They were read with their bytes diff --git a/Directory.Packages.props b/Directory.Packages.props index daf5c72..847b947 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -10,8 +10,10 @@ - - + + + diff --git a/README.md b/README.md index b877fb3..19cc1ff 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ DwgIO is a .NET library and command line tool that reads Autodesk AutoCAD drawin - Lists the objects of a drawing through its handle map and decodes the geometry of LINE, CIRCLE, ARC and POINT entities. - Writes a JSON export of the metadata, the section catalog and the decoded entities. - Converts a drawing into a neutral [IOScene](https://www.nuget.org/packages/IOScene) scene document (`DwgIO.Scene` package): geometry in metres, ACI entity colours, one element per entity with its handle. +- Exports the scene to Wavefront OBJ (with an MTL colour library) and binary glTF (GLB). ## Install @@ -63,6 +64,13 @@ Export a neutral IOScene scene document (geometry in metres, ACI colours, one el dwgio scene drawing.dwg drawing.scene.json --unit mm ``` +The plain export command writes OBJ and GLB by output extension, through the same scene: + +```sh +dwgio drawing.dwg drawing.obj # Wavefront OBJ + drawing.mtl with the ACI colours +dwgio drawing.dwg drawing.glb # binary glTF for viewers and web scenes +``` + Errors go to standard error. ### Exit codes @@ -115,6 +123,8 @@ IOScene.SceneJson.Save(scene.Document, "drawing.scene.json"); Every coordinate is scaled to metres by `LengthUnit` (a DWG stores plain numbers, so the unit is a caller decision and `UnitAssumed` records it), each entity becomes an element with its handle as `SourceId`, and LINE, CIRCLE, ARC and POINT become line and point geometries with their ACI colour. +`DwgSceneExport` writes that scene out in the exchange formats: `SaveObj(document, "drawing.obj", options)` produces an OBJ with an adjacent MTL colour library (written as a pair, atomically), `SaveGlb(document, "drawing.glb", options)` produces binary glTF. Both return the same `DwgSceneResult` report. + The documentation site with the API reference is at . [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/IOExtend/DwgIO) offers an automatically generated overview of the repository. ## Status @@ -131,6 +141,7 @@ The documentation site with the API reference is at Print version + section table - dwgio Export metadata, section catalog and decoded entities to JSON + dwgio Export metadata, section catalog and entities to JSON, + or the scene to OBJ (.obj) or GLB (.glb) dwgio extract
Write a named section's decompressed bytes dwgio preview Write the embedded thumbnail image dwgio scene [--unit u] Export a neutral IOScene scene document @@ -173,8 +174,23 @@ private static int Export(string[] args) } var doc = DwgDocument.Open(args[0]); - DwgJsonExporter.WriteFile(doc, args[1], DwgJsonExportOptions.Default); - Console.WriteLine($"{doc.Version} sections={doc.Sections.Count} -> {args[1]}"); + string output = args[1]; + if (Path.GetExtension(output).Equals(".obj", StringComparison.OrdinalIgnoreCase)) + { + var objResult = DwgSceneExport.SaveObj(doc, output); + Console.WriteLine($"{doc.Version} elements={objResult.ElementCount} ({objResult.ElementsWithGeometry} with geometry) -> {output}"); + } + else if (Path.GetExtension(output).Equals(".glb", StringComparison.OrdinalIgnoreCase)) + { + var glbResult = DwgSceneExport.SaveGlb(doc, output); + Console.WriteLine($"{doc.Version} elements={glbResult.ElementCount} ({glbResult.ElementsWithGeometry} with geometry) -> {output}"); + } + else + { + DwgJsonExporter.WriteFile(doc, output, DwgJsonExportOptions.Default); + Console.WriteLine($"{doc.Version} sections={doc.Sections.Count} -> {output}"); + } + return ExitOk; } diff --git a/src/DwgIO.Scene/DwgIO.Scene.csproj b/src/DwgIO.Scene/DwgIO.Scene.csproj index 0520f69..33967db 100644 --- a/src/DwgIO.Scene/DwgIO.Scene.csproj +++ b/src/DwgIO.Scene/DwgIO.Scene.csproj @@ -11,6 +11,7 @@ + diff --git a/src/DwgIO.Scene/DwgSceneExport.cs b/src/DwgIO.Scene/DwgSceneExport.cs new file mode 100644 index 0000000..56da831 --- /dev/null +++ b/src/DwgIO.Scene/DwgSceneExport.cs @@ -0,0 +1,114 @@ +using IOScene; +using IOScene.Formats; + +namespace DwgIO.Scene; + +/// +/// Exports a drawing to the mesh and viewer formats the IOScene toolchain writes: Wavefront OBJ with an +/// adjacent MTL library and binary glTF (GLB). Both go through the IOScene scene document, so colors, line +/// and point topologies and instancing behave exactly as in the scene JSON export. +/// +public static class DwgSceneExport +{ + /// Converts the drawing and writes it to a Wavefront OBJ file with an adjacent MTL library + /// (<objPath> with .mtl instead of its extension). + /// The drawing, for example from . + /// Path to the OBJ file; the MTL library is written beside it. + /// Conversion options; null uses the defaults. + /// The conversion report. is the intermediate scene. + public static DwgSceneResult SaveObj(DwgDocument document, string objPath, DwgSceneOptions? options = null) + { + var result = DwgSceneReader.Read(document, OptionsFor(document, objPath, options)); + WriteObj(result.Document, objPath); + return result; + } + + /// Writes a scene to a Wavefront OBJ file with an adjacent MTL library + /// (<objPath> with .mtl instead of its extension). + /// The scene to export. + /// Path to the OBJ file. + public static void WriteObj(SceneDocument scene, string objPath) + { + ArgumentNullException.ThrowIfNull(scene); + ArgumentException.ThrowIfNullOrEmpty(objPath); + string fullPath = Path.GetFullPath(objPath); + string directory = Path.GetDirectoryName(fullPath) ?? Directory.GetCurrentDirectory(); + string mtlName = Path.ChangeExtension(Path.GetFileName(fullPath), ".mtl"); + string mtlPath = Path.Combine(directory, mtlName); + string objTemp = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.obj"); + string mtlTemp = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.mtl"); + try + { + // OBJ and MTL are written as a pair: both temporary files are written first, then moved in, so a + // failure leaves the previous pair in place. + using (var objStream = new FileStream(objTemp, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + using (var objWriter = new StreamWriter(objStream, new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false))) + using (var mtlStream = new FileStream(mtlTemp, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + using (var mtlWriter = new StreamWriter(mtlStream, new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false))) + { + ObjSceneWriter.Write(scene, objWriter, mtlWriter, mtlName); + } + + File.Move(mtlTemp, mtlPath, overwrite: true); + File.Move(objTemp, fullPath, overwrite: true); + } + catch + { + TryDelete(objTemp); + TryDelete(mtlTemp); + throw; + } + } + + /// Converts the drawing and writes it to a binary glTF (GLB) file. + /// The drawing, for example from . + /// Path to the GLB file. + /// Conversion options; null uses the defaults. + /// The conversion report. is the intermediate scene. + public static DwgSceneResult SaveGlb(DwgDocument document, string glbPath, DwgSceneOptions? options = null) + { + var result = DwgSceneReader.Read(document, OptionsFor(document, glbPath, options)); + GlbSceneWriter.Save(result.Document, glbPath); + return result; + } + + /// Writes a scene to a binary glTF (GLB) file. + /// The scene to export. + /// Path to the GLB file. + public static void WriteGlb(SceneDocument scene, string glbPath) + { + ArgumentNullException.ThrowIfNull(scene); + GlbSceneWriter.Save(scene, glbPath); + } + + private static DwgSceneOptions OptionsFor(DwgDocument document, string path, DwgSceneOptions? options) + { + if (options?.ModelKey is { Length: > 0 }) + { + return options; + } + + // The file name doubles as the model key; a document from memory falls back to the export file name. + return new DwgSceneOptions + { + LengthUnit = options?.LengthUnit ?? "m", + ModelKey = Path.GetFileName(path), + }; + } + + private static void TryDelete(string path) + { + try + { + File.Delete(path); + } + catch (IOException) + { + // Best-effort cleanup: the original export failure is the error worth reporting. + } + catch (UnauthorizedAccessException) + { + // Best-effort cleanup: the original export failure is the error worth reporting. + } + } +} diff --git a/tests/DwgIO.Tests/DwgSceneExportTests.cs b/tests/DwgIO.Tests/DwgSceneExportTests.cs new file mode 100644 index 0000000..b0e044a --- /dev/null +++ b/tests/DwgIO.Tests/DwgSceneExportTests.cs @@ -0,0 +1,164 @@ +using DwgIO.Model; +using DwgIO.Scene; +using IOScene.Formats; +using Xunit; +using Vector3d = IOScene.Vector3d; + +namespace DwgIO.Tests; + +public class DwgSceneExportTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "dwgio-tests-" + Guid.NewGuid().ToString("N")); + + public DwgSceneExportTests() + { + Directory.CreateDirectory(_directory); + } + + public void Dispose() + { + GC.SuppressFinalize(this); + try + { + Directory.Delete(_directory, recursive: true); + } + catch (DirectoryNotFoundException) + { + } + } + + private static DwgDocument CreateDocument(params DwgEntity[] entities) => + new( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + entities); + + private static DwgDocument SampleDrawing() => CreateDocument( + new DwgEntity + { + Handle = 0x2A, + TypeCode = 0x13, + TypeName = "LINE", + Kind = DwgEntityKind.Line, + Geometry = [1.0, 2.0, 0.0, 11.0, 2.0, 0.0], + ColorIndex = 1, + }, + new DwgEntity + { + Handle = 0x2B, + TypeCode = 0x12, + TypeName = "CIRCLE", + Kind = DwgEntityKind.Circle, + Geometry = [6.0, 2.0, 0.0, 5.0], + ColorIndex = 40, + }, + new DwgEntity + { + Handle = 0x2C, + TypeCode = 0x1B, + TypeName = "POINT", + Kind = DwgEntityKind.Point, + Geometry = [20.0, 2.0, 0.0], + }); + + [Fact] + public void SaveObj_WritesObjWithMtlLibrary() + { + string objPath = Path.Combine(_directory, "drawing.obj"); + + var result = DwgSceneExport.SaveObj(SampleDrawing(), objPath); + + Assert.Equal(3, result.ElementCount); + Assert.True(File.Exists(objPath)); + Assert.True(File.Exists(Path.Combine(_directory, "drawing.mtl"))); + string obj = File.ReadAllText(objPath); + Assert.Contains("mtllib drawing.mtl", obj, StringComparison.Ordinal); + Assert.Contains("usemtl material_1", obj, StringComparison.Ordinal); + Assert.Contains("v 1 2 0", obj, StringComparison.Ordinal); + Assert.Contains("l ", obj, StringComparison.Ordinal); + Assert.Contains("p ", obj, StringComparison.Ordinal); + string mtl = File.ReadAllText(Path.Combine(_directory, "drawing.mtl")); + Assert.Contains("newmtl material_1", mtl, StringComparison.Ordinal); + } + + [Fact] + public void SaveObj_WritesLineAndPointRecords() + { + string objPath = Path.Combine(_directory, "drawing.obj"); + + DwgSceneExport.SaveObj(SampleDrawing(), objPath); + + // The OBJ preview reader of IOScene.Formats reads faces only, so the line and point records are asserted + // on the text: one segment for the LINE, 64 for the tessellated CIRCLE, one point for the POINT. + string[] objLines = File.ReadAllLines(objPath); + Assert.Equal(65, objLines.Count(l => l.StartsWith("l ", StringComparison.Ordinal))); + Assert.Equal(1, objLines.Count(l => l.StartsWith("p ", StringComparison.Ordinal))); + Assert.Contains(objLines, l => l == "v 1 2 0"); + Assert.Contains(objLines, l => l == "v 20 2 0"); + } + + [Fact] + public void SaveObj_ReplacesExistingFiles() + { + string objPath = Path.Combine(_directory, "drawing.obj"); + File.WriteAllText(objPath, "stale"); + string mtlPath = Path.Combine(_directory, "drawing.mtl"); + File.WriteAllText(mtlPath, "stale"); + + DwgSceneExport.SaveObj(SampleDrawing(), objPath); + + Assert.DoesNotContain("stale", File.ReadAllText(objPath), StringComparison.Ordinal); + Assert.DoesNotContain("stale", File.ReadAllText(mtlPath), StringComparison.Ordinal); + Assert.Empty(Directory.EnumerateFiles(_directory, ".dwgio-*")); + } + + [Fact] + public void SaveGlb_RoundTripsThroughGlbSceneReader() + { + string glbPath = Path.Combine(_directory, "drawing.glb"); + + var result = DwgSceneExport.SaveGlb(SampleDrawing(), glbPath); + + Assert.Equal(3, result.ElementCount); + var loaded = GlbSceneReader.Load(glbPath); + Assert.Equal(3, loaded.Elements.Count); + Assert.Equal(3, loaded.Instances.Count); + // The GLB reader turns instance colours into materials: red for the LINE (ACI 1), gold for the CIRCLE (ACI 40). + Assert.Contains(loaded.Materials, m => m.Color.R == 255 && m.Color.G == 0 && m.Color.B == 0); + Assert.Contains(loaded.Materials, m => m.Color.R == 255 && m.Color.G == 191 && m.Color.B == 0); + var lineInstance = Assert.Single(loaded.Instances, i => loaded.Geometries.Single(g => g.Id == i.GeometryId).Topology == IOScene.SceneTopology.Lines && loaded.Geometries.Single(g => g.Id == i.GeometryId).Vertices.Count == 2); + Assert.NotNull(lineInstance); + } + + [Fact] + public void SaveGlb_ScalesByLengthUnit() + { + string glbPath = Path.Combine(_directory, "drawing.glb"); + var document = CreateDocument(new DwgEntity + { + Handle = 0x2A, + TypeCode = 0x13, + TypeName = "LINE", + Kind = DwgEntityKind.Line, + Geometry = [1000.0, 0.0, 0.0, 2000.0, 0.0, 0.0], + }); + + DwgSceneExport.SaveGlb(document, glbPath, new DwgSceneOptions { LengthUnit = "mm" }); + + var loaded = GlbSceneReader.Load(glbPath); + var geometry = Assert.Single(loaded.Geometries); + Assert.Equal(new Vector3d(1.0, 0.0, 0.0), geometry.Vertices[0]); + } +} From d3d1adab300d7eb407bfc7bb5dd75a0bdf20b844 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 02:22:10 +0300 Subject: [PATCH 03/19] Draw model space to SVG DwgSvgExporter writes the decoded entities (LINE, CIRCLE, ARC and POINT) of a drawing as SVG, the first step of #32: the top view with the drawing's X to the right and Y up, entities in their ACI colours (BYBLOCK, BYLAYER and 7 render black on the light background), arcs as SVG arc paths with correct sweep under the y flip, and a viewBox that covers every drawn entity including the cardinal extremes of an arc. Skipped non-finite entities are reported in Diagnostics; the file is written through a temporary file and moved in atomically. dwgio svg [--scale n] drives it; --scale sets pixels per drawing unit, and the stroke width and point markers stay fixed in pixels while the drawing zooms. --- CHANGELOG.md | 3 + README.md | 8 + docs/public-api.md | 1 + src/DwgIO.Cli/Program.cs | 36 +++ src/DwgIO.Scene/DwgSvgExporter.cs | 328 +++++++++++++++++++++++ src/DwgIO.Scene/DwgSvgOptions.cs | 19 ++ src/DwgIO/DwgIO.csproj | 1 + tests/DwgIO.Tests/DwgSvgExporterTests.cs | 189 +++++++++++++ 8 files changed, 585 insertions(+) create mode 100644 src/DwgIO.Scene/DwgSvgExporter.cs create mode 100644 src/DwgIO.Scene/DwgSvgOptions.cs create mode 100644 tests/DwgIO.Tests/DwgSvgExporterTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index e3694cd..0b2bacc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,9 @@ API between minor releases. - `DwgSceneExport.SaveObj`/`SaveGlb` write a drawing to Wavefront OBJ (with an adjacent MTL colour library, written as a pair) and binary glTF (GLB) through the IOScene writers; `dwgio drawing.dwg out.obj` and `dwgio drawing.dwg out.glb` dispatch by extension. +- `DwgSvgExporter` and `dwgio svg [--scale n]` draw model space to SVG (#32): LINE, + CIRCLE, ARC and POINT in the top view with the y axis up, in their ACI colours, inside a view box that + contains every exported entity. Polylines, curves and text follow as the core decodes them. ### Fixed - Packed 16-bit and 32-bit integers in their full-width form are read little-endian. They were read with their bytes diff --git a/README.md b/README.md index 19cc1ff..4e9493c 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ DwgIO is a .NET library and command line tool that reads Autodesk AutoCAD drawin - Writes a JSON export of the metadata, the section catalog and the decoded entities. - Converts a drawing into a neutral [IOScene](https://www.nuget.org/packages/IOScene) scene document (`DwgIO.Scene` package): geometry in metres, ACI entity colours, one element per entity with its handle. - Exports the scene to Wavefront OBJ (with an MTL colour library) and binary glTF (GLB). +- Draws model space to SVG (`dwgio svg`): LINE, CIRCLE, ARC and POINT in the top view, in their ACI colours. ## Install @@ -71,6 +72,12 @@ dwgio drawing.dwg drawing.obj # Wavefront OBJ + drawing.mtl with the ACI colou dwgio drawing.dwg drawing.glb # binary glTF for viewers and web scenes ``` +Draw model space to SVG (X to the right, Y up, ACI colours; `--scale` sets pixels per drawing unit): + +```sh +dwgio svg drawing.dwg drawing.svg --scale 2 +``` + Errors go to standard error. ### Exit codes @@ -142,6 +149,7 @@ The documentation site with the API reference is at Extract(args), "preview" => Preview(args), "scene" => Scene(args), + "svg" => Svg(args), _ => Export(args), }; } @@ -68,6 +69,7 @@ dwgio extract
Write a named section's decompressed by dwgio preview Write the embedded thumbnail image dwgio scene [--unit u] Export a neutral IOScene scene document (u: mm, cm, m (default), ft or in) + dwgio svg [--scale s] Draw model space to SVG (s: px per unit, default 1) Sections are named as stored, e.g. AcDb:Header, AcDb:Classes, AcDb:SummaryInfo. """); @@ -209,6 +211,40 @@ private static int Extract(string[] args) return ExitOk; } + private static int Svg(string[] args) + { + double scale = 1.0; + var positional = new List(2); + for (int i = 1; i < args.Length; i++) + { + if (args[i] == "--scale") + { + if (i + 1 >= args.Length || !double.TryParse(args[i + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out scale) || scale <= 0) + { + Console.Error.WriteLine("error: --scale needs a positive number of pixels per drawing unit."); + return ExitUsage; + } + + i++; + } + else + { + positional.Add(args[i]); + } + } + + if (positional.Count != 2) + { + PrintUsage(); + return ExitUsage; + } + + var doc = DwgDocument.Open(positional[0]); + DwgSvgExporter.WriteFile(doc, positional[1], new DwgSvgOptions { Scale = scale }); + Console.WriteLine($"{doc.Version} entities={doc.Entities.Count} -> {positional[1]}"); + return ExitOk; + } + private static int Scene(string[] args) { string? unit = null; diff --git a/src/DwgIO.Scene/DwgSvgExporter.cs b/src/DwgIO.Scene/DwgSvgExporter.cs new file mode 100644 index 0000000..94499b7 --- /dev/null +++ b/src/DwgIO.Scene/DwgSvgExporter.cs @@ -0,0 +1,328 @@ +using System.Globalization; +using System.Xml; +using DwgIO.Model; + +namespace DwgIO.Scene; + +/// +/// Draws the model space of a drawing as SVG: LINE, CIRCLE, ARC and POINT entities in the top view, with the +/// drawing's X to the right and Y up, in the entities' ACI colours. The viewBox is the bounding box of +/// everything drawn plus a margin, in drawing units with y flipped, so the output contains every exported entity. +/// +/// +/// This is the first step of issue #32: polylines, curves and text join as the core decodes them. SVG is a 2D +/// format; the drawing's Z is dropped, so entities off the XY plane are drawn flattened onto it. +/// +public static class DwgSvgExporter +{ + /// Writes the model space of to a new SVG file at . + public static void WriteFile(DwgDocument document, string path, DwgSvgOptions? options = null) + { + var fullPath = Path.GetFullPath(path); + var directory = Path.GetDirectoryName(fullPath) ?? Directory.GetCurrentDirectory(); + var tempPath = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.svg"); + try + { + using (var stream = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + Write(document, stream, options); + } + + File.Move(tempPath, fullPath, overwrite: true); + } + catch + { + try + { + File.Delete(tempPath); + } + catch (IOException) + { + // Best-effort cleanup: the original export failure is the error worth reporting. + } + catch (UnauthorizedAccessException) + { + // Best-effort cleanup: the original export failure is the error worth reporting. + } + + throw; + } + } + + /// Writes the model space of to a stream. The stream stays open. + public static void Write(DwgDocument document, Stream output, DwgSvgOptions? options = null) + { + ArgumentNullException.ThrowIfNull(output); + using var writer = XmlWriter.Create(output, new XmlWriterSettings + { + Indent = true, + Encoding = new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false), + }); + Write(document, writer, options); + } + + /// Writes the model space of to an XML writer. + public static void Write(DwgDocument document, XmlWriter writer, DwgSvgOptions? options = null) + { + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(writer); + options ??= new DwgSvgOptions(); + if (options.Scale <= 0) + { + throw new ArgumentException("DwgSvgOptions.Scale must be positive.", nameof(options)); + } + + var shapes = Collect(document, options.Scale); + (double minX, double minY, double width, double height) = ViewBox(shapes); + // Margins and markers are pixel values: they stay fixed while the scale zooms the drawing. + double margin = Math.Max(0.02 * Math.Max(width, height), 8.0); + double markerRadius = Math.Max(0.015 * Math.Max(width, height), 3.0); + + writer.WriteStartDocument(); + writer.WriteStartElement("svg", "http://www.w3.org/2000/svg"); + writer.WriteAttributeString("viewBox", $"{Num(minX - margin)} {Num(minY - margin)} {Num(width + 2 * margin)} {Num(height + 2 * margin)}"); + writer.WriteAttributeString("width", Num(width + 2 * margin)); + writer.WriteAttributeString("height", Num(height + 2 * margin)); + + writer.WriteStartElement("rect"); + writer.WriteAttributeString("x", Num(minX - margin)); + writer.WriteAttributeString("y", Num(minY - margin)); + writer.WriteAttributeString("width", Num(width + 2 * margin)); + writer.WriteAttributeString("height", Num(height + 2 * margin)); + writer.WriteAttributeString("fill", options.Background); + writer.WriteEndElement(); + + writer.WriteStartElement("g"); + writer.WriteAttributeString("fill", "none"); + writer.WriteAttributeString("stroke", "#000000"); + writer.WriteAttributeString("stroke-width", Num(options.StrokeWidth)); + writer.WriteAttributeString("stroke-linecap", "round"); + + foreach (var shape in shapes) + { + string stroke = ColourOf(shape.ColorIndex); + switch (shape) + { + case SvgLine line: + writer.WriteStartElement("line"); + writer.WriteAttributeString("x1", Num(line.X1)); + writer.WriteAttributeString("y1", Num(line.Y1)); + writer.WriteAttributeString("x2", Num(line.X2)); + writer.WriteAttributeString("y2", Num(line.Y2)); + writer.WriteAttributeString("stroke", stroke); + writer.WriteEndElement(); + break; + case SvgCircle circle: + writer.WriteStartElement("circle"); + writer.WriteAttributeString("cx", Num(circle.Cx)); + writer.WriteAttributeString("cy", Num(circle.Cy)); + writer.WriteAttributeString("r", Num(circle.Radius)); + writer.WriteAttributeString("stroke", stroke); + writer.WriteEndElement(); + break; + case SvgArc arc: + (double x1, double y1, double x2, double y2) = ArcEndpoints(arc); + // The drawing's CCW arc becomes a CW trace in SVG's y-down space, hence sweep 0; the y flip + // is baked into the endpoints already. + writer.WriteStartElement("path"); + writer.WriteAttributeString( + "d", + FormattableString.Invariant( + $"M {Num(x1)} {Num(y1)} A {Num(arc.Radius)} {Num(arc.Radius)} 0 {(arc.Span > Math.PI ? 1 : 0):D} 0 {Num(x2)} {Num(y2)}")); + writer.WriteAttributeString("stroke", stroke); + writer.WriteEndElement(); + break; + case SvgPoint: + writer.WriteStartElement("circle"); + writer.WriteAttributeString("cx", Num(((SvgPoint)shape).X)); + writer.WriteAttributeString("cy", Num(((SvgPoint)shape).Y)); + writer.WriteAttributeString("r", Num(markerRadius)); + writer.WriteAttributeString("fill", stroke); + writer.WriteAttributeString("stroke", "none"); + writer.WriteEndElement(); + break; + } + } + + writer.WriteEndElement(); + writer.WriteEndElement(); + writer.WriteEndDocument(); + } + + private abstract record SvgShape(int ColorIndex); + + private sealed record SvgLine(double X1, double Y1, double X2, double Y2, int ColorIndex) : SvgShape(ColorIndex); + + private sealed record SvgCircle(double Cx, double Cy, double Radius, int ColorIndex) : SvgShape(ColorIndex); + + // Start and span are normalised (span > 0); the endpoints follow in SVG coordinates. + private sealed record SvgArc(double Cx, double Cy, double Radius, double Start, double Span, int ColorIndex) + : SvgShape(ColorIndex); + + private sealed record SvgPoint(double X, double Y, int ColorIndex) : SvgShape(ColorIndex); + + private static List Collect(DwgDocument document, double scale) + { + var shapes = new List(); + foreach (var entity in document.Entities) + { + switch (entity.Kind, entity.Geometry) + { + case (DwgEntityKind.Line, [var x1, var y1, var z1, var x2, var y2, var z2]): + if (IsUsable(x1, y1, x2, y2)) + { + shapes.Add(new SvgLine(x1 * scale, -y1 * scale, x2 * scale, -y2 * scale, entity.ColorIndex)); + } + else + { + Skip(document, entity, "non-finite coordinates"); + } + + break; + case (DwgEntityKind.Circle, [var cx, var cy, var cz, var r]): + if (IsUsable(cx, cy) && IsUsable(r) && r > 0) + { + shapes.Add(new SvgCircle(cx * scale, -cy * scale, r * scale, entity.ColorIndex)); + } + else + { + Skip(document, entity, "non-finite or non-positive radius"); + } + + break; + case (DwgEntityKind.Arc, [var cx, var cy, _, var r, var start, var end]): + if (IsUsable(cx, cy) && IsUsable(r, start, end) && r > 0) + { + shapes.Add(ArcShape(cx * scale, -cy * scale, r * scale, start, end, entity.ColorIndex)); + } + else + { + Skip(document, entity, "non-finite or non-positive radius"); + } + + break; + case (DwgEntityKind.Point, [var x, var y, _]): + if (IsUsable(x, y)) + { + shapes.Add(new SvgPoint(x * scale, -y * scale, entity.ColorIndex)); + } + else + { + Skip(document, entity, "non-finite coordinates"); + } + + break; + } + } + + return shapes; + } + + private static void Skip(DwgDocument document, DwgEntity entity, string reason) => + document.ReportDiagnostic($"svg: entity {entity.Handle:X} ({entity.TypeName}) skipped: {reason}"); + + private static bool IsUsable(params double[] values) => values.All(double.IsFinite); + + private static SvgArc ArcShape(double cx, double cy, double radius, double start, double end, int colorIndex) + { + double span = end - start; + while (span <= 0) + { + // AutoCAD draws an arc with equal start and end angles as a full circle. + span += 2.0 * Math.PI; + } + + return new SvgArc(cx, cy, radius, start, span, colorIndex); + } + + private static (double X1, double Y1, double X2, double Y2) ArcEndpoints(SvgArc arc) => + ( + arc.Cx + arc.Radius * Math.Cos(arc.Start), + arc.Cy - arc.Radius * Math.Sin(arc.Start), + arc.Cx + arc.Radius * Math.Cos(arc.Start + arc.Span), + arc.Cy - arc.Radius * Math.Sin(arc.Start + arc.Span) + ); + + private static (double MinX, double MinY, double Width, double Height) ViewBox(List shapes) + { + double minX = double.PositiveInfinity, minY = double.PositiveInfinity; + double maxX = double.NegativeInfinity, maxY = double.NegativeInfinity; + foreach (var shape in shapes) + { + switch (shape) + { + case SvgLine line: + Expand(line.X1, line.Y1); + Expand(line.X2, line.Y2); + break; + case SvgCircle circle: + Expand(circle.Cx - circle.Radius, circle.Cy - circle.Radius); + Expand(circle.Cx + circle.Radius, circle.Cy + circle.Radius); + break; + case SvgArc arc: + (double x1, double y1, double x2, double y2) = ArcEndpoints(arc); + Expand(x1, y1); + Expand(x2, y2); + // The extremes of the four cardinal directions lie inside the arc when their angle falls + // within its span; without them the view box could cut through the drawn curve. + for (int k = 0; k < 4; k++) + { + double angle = k * Math.PI / 2.0; + while (angle < arc.Start) + { + angle += 2.0 * Math.PI; + } + + if (angle <= arc.Start + arc.Span) + { + Expand(arc.Cx + arc.Radius * Math.Cos(angle), -Math.Sin(angle) * arc.Radius + arc.Cy); + } + } + + break; + case SvgPoint point: + Expand(point.X, point.Y); + break; + } + } + + if (minX > maxX) + { + return (0, 0, 0, 0); + } + + return (minX, minY, maxX - minX, maxY - minY); + + void Expand(double x, double y) + { + minX = Math.Min(minX, x); + minY = Math.Min(minY, y); + maxX = Math.Max(maxX, x); + maxY = Math.Max(maxY, y); + } + } + + private static string ColourOf(int colorIndex) + { + // BYBLOCK (0) and BYLAYER (256) resolve to the default layer colour, which is 7; on a light background + // AutoCAD renders 7 (white) as black. + int resolved = colorIndex is > 0 and < 256 ? colorIndex : 7; + if (resolved == 7) + { + return "#000000"; + } + + (byte r, byte g, byte b) = DwgAciPalette.RgbOf(resolved); + return FormattableString.Invariant($"#{r:X2}{g:X2}{b:X2}"); + } + + private static string Num(double value) + { + if (value == 0.0) + { + value = 0.0; // normalise -0 + } + + return value.ToString("0.######", CultureInfo.InvariantCulture); + } +} diff --git a/src/DwgIO.Scene/DwgSvgOptions.cs b/src/DwgIO.Scene/DwgSvgOptions.cs new file mode 100644 index 0000000..ce403ce --- /dev/null +++ b/src/DwgIO.Scene/DwgSvgOptions.cs @@ -0,0 +1,19 @@ +namespace DwgIO.Scene; + +/// Options of the SVG export of model space. +public sealed class DwgSvgOptions +{ + /// + /// Pixels per drawing unit. The geometry is scaled by it, so the viewBox, width and + /// height grow together: the drawing keeps its aspect at every scale, and one viewBox unit is + /// one pixel. + /// + public double Scale { get; set; } = 1.0; + + /// Stroke width of the drawn entities, in pixels; it stays fixed while the scale zooms the drawing. + public double StrokeWidth { get; set; } = 1.0; + + /// Background colour, as CSS. AutoCAD renders on a dark background, but SVG files are usually + /// viewed on light ones, so the default is white and colour 7 (white/black) renders black. + public string Background { get; set; } = "white"; +} diff --git a/src/DwgIO/DwgIO.csproj b/src/DwgIO/DwgIO.csproj index 74dacaf..4aea63d 100644 --- a/src/DwgIO/DwgIO.csproj +++ b/src/DwgIO/DwgIO.csproj @@ -8,6 +8,7 @@ + diff --git a/tests/DwgIO.Tests/DwgSvgExporterTests.cs b/tests/DwgIO.Tests/DwgSvgExporterTests.cs new file mode 100644 index 0000000..871483e --- /dev/null +++ b/tests/DwgIO.Tests/DwgSvgExporterTests.cs @@ -0,0 +1,189 @@ +using System.Text; +using System.Xml; +using DwgIO.Model; +using DwgIO.Scene; +using Xunit; + +namespace DwgIO.Tests; + +public class DwgSvgExporterTests +{ + private static DwgDocument CreateDocument(params DwgEntity[] entities) => + new( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + entities); + + private static DwgEntity Entity(ulong handle, DwgEntityKind kind, string typeName, double[] geometry, int colorIndex = 256) => + new() + { + Handle = handle, + TypeCode = 0x13, + TypeName = typeName, + Kind = kind, + Geometry = geometry, + ColorIndex = colorIndex, + }; + + private static string WriteToString(DwgDocument document, DwgSvgOptions? options = null) + { + using var stream = new MemoryStream(); + DwgSvgExporter.Write(document, stream, options); + return Encoding.UTF8.GetString(stream.ToArray()); + } + + private static string SingleLineSvg() => WriteToString(CreateDocument( + Entity(0x2A, DwgEntityKind.Line, "LINE", [10.0, 20.0, 0.0, 30.0, 20.0, 0.0], colorIndex: 1))); + + [Fact] + public void Write_DrawsLineWithFlippedYAndAciColour() + { + string svg = SingleLineSvg(); + + // The Y flip puts the line at y = -20, and ACI 1 is pure red. + Assert.Contains("", svg, StringComparison.Ordinal); + } + + [Fact] + public void Write_ViewBoxContainsEveryEntity() + { + var document = CreateDocument( + Entity(0x2A, DwgEntityKind.Line, "LINE", [10.0, 20.0, 0.0, 30.0, 20.0, 0.0]), + Entity(0x2B, DwgEntityKind.Circle, "CIRCLE", [-50.0, 0.0, 0.0, 5.0]), + Entity(0x2C, DwgEntityKind.Arc, "ARC", [0.0, 0.0, 0.0, 40.0, 0.1, 1.7]), + Entity(0x2D, DwgEntityKind.Point, "POINT", [100.0, -60.0, 0.0])); + + string svg = WriteToString(document); + + string viewBox = Between(svg, "viewBox=\"", "\""); + string[] parts = viewBox.Split(' '); + double minX = Parse(parts[0]); + double minY = Parse(parts[1]); + double width = Parse(parts[2]); + double height = Parse(parts[3]); + // Every coordinate the entities occupy after the y flip: the circle's left edge (-55), the arc's top + // extreme at angle 90° (y -40), the point at x 100 (flipped to y 60). + Assert.True(minX <= -55); + Assert.True(minY <= -40); + Assert.True(minX + width >= 100); + Assert.True(minY + height >= 60); + } + + [Fact] + public void Write_ArcPathIsWellFormedAndContinuous() + { + // An arc through the top cardinal: from 10° to 170° around (0,0) with r 40 passes (0, 40). + var document = CreateDocument(Entity(0x2A, DwgEntityKind.Arc, "ARC", [0.0, 0.0, 0.0, 40.0, 10.0 * Math.PI / 180.0, 170.0 * Math.PI / 180.0])); + + string svg = WriteToString(document); + + string path = Between(svg, "", svg, StringComparison.Ordinal); + Assert.Contains("stroke=\"#545454\" />", svg, StringComparison.Ordinal); + Assert.Equal(3, svg.Split("stroke=\"#000000\" />").Length - 1); + } + + [Fact] + public void Write_ScaleMultipliesWidthAndHeight() + { + string svg = WriteToString(CreateDocument(Entity(0x2A, DwgEntityKind.Line, "LINE", [0.0, 0.0, 0.0, 10.0, 0.0, 0.0])), new DwgSvgOptions { Scale = 2.5 }); + + // 10 units × 2.5 px/unit = 25 px, plus the 8 px margin on every side. + Assert.Equal("41", Between(svg, "width=\"", "\"")); + } + + [Fact] + public void WriteFile_IsAtomicAndLeavesNoTemporaryFile() + { + string directory = Path.Combine(Path.GetTempPath(), "dwgio-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try + { + string path = Path.Combine(directory, "drawing.svg"); + DwgSvgExporter.WriteFile(SingleLineSvgDocument(), path, null); + + Assert.Contains(" CreateDocument( + Entity(0x2A, DwgEntityKind.Line, "LINE", [0.0, 0.0, 0.0, 10.0, 0.0, 0.0])); + + private static System.Xml.Linq.XName XName(string local) => System.Xml.Linq.XName.Get(local, "http://www.w3.org/2000/svg"); + + private static string Between(string text, string start, string end) + { + int from = text.IndexOf(start, StringComparison.Ordinal) + start.Length; + int to = text.IndexOf(end, from, StringComparison.Ordinal); + return text[from..to]; + } + + private static double Parse(string value) => + double.Parse(value, System.Globalization.CultureInfo.InvariantCulture); +} From 946d20cba3fea6bee0df2b546f8ee6c3b008f346 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 02:26:07 +0300 Subject: [PATCH 04/19] Write a standalone HTML viewer of the drawing DwgViewerExport.SaveViewer converts the drawing to an IOScene scene and embeds it with the IOViewer WebGL runtime into one interactive HTML file (no server, no external scripts); the default viewer title follows the scene. dwgio drawing.dwg out.html drives it through the output extension, next to OBJ, GLB and JSON. --- CHANGELOG.md | 2 + Directory.Packages.props | 2 + README.md | 8 ++ docs/public-api.md | 1 + src/DwgIO.Cli/Program.cs | 8 +- src/DwgIO.Scene/DwgIO.Scene.csproj | 1 + src/DwgIO.Scene/DwgViewerExport.cs | 67 ++++++++++++++++ tests/DwgIO.Tests/DwgViewerExportTests.cs | 97 +++++++++++++++++++++++ 8 files changed, 185 insertions(+), 1 deletion(-) create mode 100644 src/DwgIO.Scene/DwgViewerExport.cs create mode 100644 tests/DwgIO.Tests/DwgViewerExportTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b2bacc..87ae920 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,8 @@ API between minor releases. - `DwgSvgExporter` and `dwgio svg [--scale n]` draw model space to SVG (#32): LINE, CIRCLE, ARC and POINT in the top view with the y axis up, in their ACI colours, inside a view box that contains every exported entity. Polylines, curves and text follow as the core decodes them. +- `DwgViewerExport.SaveViewer` and `dwgio drawing.dwg out.html` write a standalone interactive 3D HTML viewer + (the IOViewer WebGL runtime embedded with the IOScene scene document; no server, no external scripts). ### Fixed - Packed 16-bit and 32-bit integers in their full-width form are read little-endian. They were read with their bytes diff --git a/Directory.Packages.props b/Directory.Packages.props index 847b947..adb5083 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -14,6 +14,8 @@ IOScene.Formats (GLB and OBJ writers) ships as a preview and needs IOScene 0.1.1 or later. --> + + diff --git a/README.md b/README.md index 4e9493c..72f49e4 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ DwgIO is a .NET library and command line tool that reads Autodesk AutoCAD drawin - Converts a drawing into a neutral [IOScene](https://www.nuget.org/packages/IOScene) scene document (`DwgIO.Scene` package): geometry in metres, ACI entity colours, one element per entity with its handle. - Exports the scene to Wavefront OBJ (with an MTL colour library) and binary glTF (GLB). - Draws model space to SVG (`dwgio svg`): LINE, CIRCLE, ARC and POINT in the top view, in their ACI colours. +- Writes a standalone interactive 3D HTML viewer (`.html`): the WebGL viewer of [IOViewer](https://github.com/IOExtend/IOViewer) embedded with the scene, no server or external scripts. ## Install @@ -78,6 +79,12 @@ Draw model space to SVG (X to the right, Y up, ACI colours; `--scale` sets pixel dwgio svg drawing.dwg drawing.svg --scale 2 ``` +Open the drawing in a standalone interactive 3D HTML viewer: + +```sh +dwgio drawing.dwg drawing.html +``` + Errors go to standard error. ### Exit codes @@ -150,6 +157,7 @@ The documentation site with the API reference is at Print version + section table dwgio Export metadata, section catalog and entities to JSON, - or the scene to OBJ (.obj) or GLB (.glb) + or the scene to OBJ (.obj), GLB (.glb) or a standalone + interactive 3D HTML viewer (.html) dwgio extract
Write a named section's decompressed bytes dwgio preview Write the embedded thumbnail image dwgio scene [--unit u] Export a neutral IOScene scene document @@ -187,6 +188,11 @@ private static int Export(string[] args) var glbResult = DwgSceneExport.SaveGlb(doc, output); Console.WriteLine($"{doc.Version} elements={glbResult.ElementCount} ({glbResult.ElementsWithGeometry} with geometry) -> {output}"); } + else if (Path.GetExtension(output).Equals(".html", StringComparison.OrdinalIgnoreCase)) + { + var htmlResult = DwgViewerExport.SaveViewer(doc, output); + Console.WriteLine($"{doc.Version} elements={htmlResult.ElementCount} ({htmlResult.ElementsWithGeometry} with geometry) -> {output}"); + } else { DwgJsonExporter.WriteFile(doc, output, DwgJsonExportOptions.Default); diff --git a/src/DwgIO.Scene/DwgIO.Scene.csproj b/src/DwgIO.Scene/DwgIO.Scene.csproj index 33967db..c333a16 100644 --- a/src/DwgIO.Scene/DwgIO.Scene.csproj +++ b/src/DwgIO.Scene/DwgIO.Scene.csproj @@ -12,6 +12,7 @@ + diff --git a/src/DwgIO.Scene/DwgViewerExport.cs b/src/DwgIO.Scene/DwgViewerExport.cs new file mode 100644 index 0000000..aa86662 --- /dev/null +++ b/src/DwgIO.Scene/DwgViewerExport.cs @@ -0,0 +1,67 @@ +using IOViewer.Exporters; +using IOScene; + +namespace DwgIO.Scene; + +/// +/// Exports a drawing as a standalone interactive 3D HTML viewer: one self-contained file with the scene and the +/// WebGL viewer runtime embedded, no server and no external scripts. The viewer is generated by +/// IOViewer from the IOScene scene document, so the +/// drawing shows exactly what the scene JSON and the OBJ/GLB exports describe. +/// +public static class DwgViewerExport +{ + /// Converts the drawing and writes it to a standalone interactive HTML viewer file. + /// The drawing, for example from . + /// Path to the HTML file. + /// Scene conversion options; null uses the defaults. + /// Viewer options (title, initial mode, vertex budget); null uses the defaults. + /// The conversion report. is the scene the viewer embeds. + public static DwgSceneResult SaveViewer( + DwgDocument document, + string htmlPath, + DwgSceneOptions? options = null, + HtmlViewerOptions? viewerOptions = null) + { + var result = DwgSceneReader.Read(document, ViewerOptionsFor(document, htmlPath, options)); + WriteViewer(result.Document, htmlPath, viewerOptions); + return result; + } + + /// Writes a scene to a standalone interactive HTML viewer file. + /// The scene to embed. + /// Path to the HTML file. + /// Viewer options; null uses the defaults. + public static void WriteViewer(SceneDocument scene, string htmlPath, HtmlViewerOptions? viewerOptions = null) + { + ArgumentNullException.ThrowIfNull(scene); + ArgumentException.ThrowIfNullOrEmpty(htmlPath); + if (viewerOptions is null) + { + // Default options take their title from the scene; a caller's options are respected as given, + // with an empty title filled from the scene. + viewerOptions = new HtmlViewerOptions { Title = scene.Title }; + } + else if (string.IsNullOrEmpty(viewerOptions.Title)) + { + viewerOptions.Title = scene.Title; + } + + HtmlViewerExporter.Save(scene, htmlPath, viewerOptions); + } + + private static DwgSceneOptions ViewerOptionsFor(DwgDocument document, string path, DwgSceneOptions? options) + { + if (options?.ModelKey is { Length: > 0 }) + { + return options; + } + + // The export file name doubles as the model key; a document from memory falls back to it. + return new DwgSceneOptions + { + LengthUnit = options?.LengthUnit ?? "m", + ModelKey = Path.GetFileName(path), + }; + } +} diff --git a/tests/DwgIO.Tests/DwgViewerExportTests.cs b/tests/DwgIO.Tests/DwgViewerExportTests.cs new file mode 100644 index 0000000..9ae16b6 --- /dev/null +++ b/tests/DwgIO.Tests/DwgViewerExportTests.cs @@ -0,0 +1,97 @@ +using DwgIO.Model; +using DwgIO.Scene; +using Xunit; + +namespace DwgIO.Tests; + +public class DwgViewerExportTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "dwgio-tests-" + Guid.NewGuid().ToString("N")); + + public DwgViewerExportTests() + { + Directory.CreateDirectory(_directory); + } + + public void Dispose() + { + GC.SuppressFinalize(this); + try + { + Directory.Delete(_directory, recursive: true); + } + catch (DirectoryNotFoundException) + { + } + } + + private static DwgDocument CreateDocument(params DwgEntity[] entities) => + new( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + entities); + + private static DwgDocument SampleDrawing() => CreateDocument( + new DwgEntity + { + Handle = 0x2A, + TypeCode = 0x13, + TypeName = "LINE", + Kind = DwgEntityKind.Line, + Geometry = [0.0, 0.0, 0.0, 10.0, 0.0, 0.0], + ColorIndex = 1, + }, + new DwgEntity + { + Handle = 0x2B, + TypeCode = 0x12, + TypeName = "CIRCLE", + Kind = DwgEntityKind.Circle, + Geometry = [5.0, 0.0, 0.0, 5.0], + ColorIndex = 40, + }); + + [Fact] + public void SaveViewer_WritesSelfContainedHtml() + { + string htmlPath = Environment.GetEnvironmentVariable("DWGIO_VIEWER_DEBUG_PATH") is { Length: > 0 } debug + ? debug + : Path.Combine(_directory, "drawing.html"); + + var result = DwgViewerExport.SaveViewer(SampleDrawing(), htmlPath); + + Assert.Equal(2, result.ElementCount); + string html = File.ReadAllText(htmlPath); + // A standalone viewer: the WebGL runtime is embedded, no external script or stylesheet is referenced. + Assert.Contains("", html, StringComparison.OrdinalIgnoreCase); + Assert.Contains("canvas", html, StringComparison.Ordinal); + Assert.DoesNotContain("", metaStart, StringComparison.Ordinal); + using var metadata = JsonDocument.Parse(html[metaStart..metaEnd]); + Assert.Equal(3, metadata.RootElement.GetProperty("geometries").GetArrayLength()); Assert.Contains("id=\"ioviewer-bin\"", html, StringComparison.Ordinal); } diff --git a/tests/DwgIO.Tests/EncryptedSectionTests.cs b/tests/DwgIO.Tests/EncryptedSectionTests.cs index 04ceb06..8dba824 100644 --- a/tests/DwgIO.Tests/EncryptedSectionTests.cs +++ b/tests/DwgIO.Tests/EncryptedSectionTests.cs @@ -7,7 +7,9 @@ namespace DwgIO.Tests; /// A section map with an encrypted entry: the section is skipped with a diagnostic, not silently (#38). public class EncryptedSectionTests { - private static DwgDocument CreateDocument(params SectionEntry[] entries) + private static DwgDocument CreateDocument(params SectionEntry[] entries) => CreateDocument(readMetadata: false, entries); + + private static DwgDocument CreateDocument(bool readMetadata, params SectionEntry[] entries) { var container = new R2004Container { @@ -52,7 +54,7 @@ private static DwgDocument CreateDocument(params SectionEntry[] entries) PreviewOffset = 0, Codepage = 30, }, - new DwgReaderOptions { ReadSummaryInfo = false, ReadMetadata = false, ReadObjects = false }); + new DwgReaderOptions { ReadSummaryInfo = false, ReadMetadata = readMetadata, ReadObjects = false }); return document; } @@ -69,6 +71,20 @@ private static DwgDocument CreateDocument(params SectionEntry[] entries) }; + [Theory] + [InlineData(0u)] + [InlineData(1u)] + public void PreviewCommand_WhenSectionCannotBeRead_ReturnsParseError(uint encryption) + { + var document = CreateDocument(readMetadata: true, Section("AcDb:Preview", encryption)); + using var output = new StringWriter(); + using var error = new StringWriter(); + + Assert.Equal(4, Cli.Program.PreviewDocument(document, "unused", output, error)); + Assert.Contains("AcDb:Preview:", error.ToString(), StringComparison.Ordinal); + Assert.Empty(output.ToString()); + } + [Fact] public void TryGetReadableSection_EncryptedEntry_IsSkippedWithADiagnostic() { diff --git a/tests/DwgIO.Tests/EntityTypeTests.cs b/tests/DwgIO.Tests/EntityTypeTests.cs index e1142e4..69931f5 100644 --- a/tests/DwgIO.Tests/EntityTypeTests.cs +++ b/tests/DwgIO.Tests/EntityTypeTests.cs @@ -25,6 +25,7 @@ public void DrawableFixedCodes_AreEntities(ushort typeCode) [Theory] [InlineData(0x00)] // UNUSED + [InlineData(0x09)] // reserved in the supported versions [InlineData(0x30)] // BLOCK CONTROL OBJ public void ObjectsAndOutOfRangeCodes_AreNotEntities(ushort typeCode) { diff --git a/tests/DwgIO.Tests/HistorySectionsTests.cs b/tests/DwgIO.Tests/HistorySectionsTests.cs index 8a63859..7c938ba 100644 --- a/tests/DwgIO.Tests/HistorySectionsTests.cs +++ b/tests/DwgIO.Tests/HistorySectionsTests.cs @@ -93,10 +93,9 @@ public void AuxHeader_ParsesTheFixedLayout() Assert.Equal(0x2Bul, aux.Handseed); Assert.Equal(2460311u, aux.CreatedRaw.JulianDay); Assert.Equal(43200000u, aux.CreatedRaw.Milliseconds); - Assert.NotNull(aux.CreatedUtc); - Assert.InRange(aux.CreatedUtc!.Value.Year, 2020, 2030); - Assert.NotNull(aux.ModifiedUtc); - Assert.InRange(aux.ModifiedUtc!.Value.Year, 2020, 2030); + var midnight = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.Equal(midnight.AddHours(12), aux.CreatedUtc); + Assert.Equal(midnight.AddDays(1).AddMilliseconds(-1), aux.ModifiedUtc); } [Fact] @@ -126,53 +125,6 @@ public void AuxHeader_Truncated_Throws() Assert.Throws(() => AuxHeaderParser.Parse(new byte[50])); } - // ------------------------------------------------------------------ AppInfoHistory - - [Fact] - public void AppInfoHistory_WalksTheRecordSequence() - { - var data = new List(); - WriteAnsiAppInfo(data, "AppInfoDataList", "1.0", "First"); - WriteAnsiAppInfo(data, "AppInfoDataList", "2.0", "Second"); - - var diagnostics = new List(); - var records = AppInfoHistoryParser.Parse([.. data], 30, diagnostics.Add); - - Assert.Equal(2, records.Count); - Assert.Equal("1.0", records[0].Version); - Assert.Equal("2.0", records[1].Version); - Assert.Empty(diagnostics); - } - - [Fact] - public void AppInfoHistory_TruncatedTail_IsReported() - { - var data = new List(); - WriteAnsiAppInfo(data, "AppInfoDataList", "1.0", "First"); - data.AddRange([0x00, 0x00]); // two trailing bytes: too small for a record - - var diagnostics = new List(); - var records = AppInfoHistoryParser.Parse([.. data], 30, diagnostics.Add); - - Assert.Single(records); - Assert.Contains(diagnostics, d => d.Contains("too small for a record", StringComparison.Ordinal)); - } - - [Fact] - public void AppInfoHistory_BrokenRecord_IsReported() - { - var data = new List(); - WriteAnsiAppInfo(data, "AppInfoDataList", "1.0", "First"); - // A record whose string runs past the payload. - data.AddRange([0x20, 0x00, (byte)'x', (byte)'y']); - - var diagnostics = new List(); - var records = AppInfoHistoryParser.Parse([.. data], 30, diagnostics.Add); - - Assert.Single(records); - Assert.Contains(diagnostics, d => d.Contains("does not decode", StringComparison.Ordinal)); - } - private static void WriteAnsiString16(List data, string text) { var bytes = System.Text.Encoding.ASCII.GetBytes(text); @@ -180,13 +132,4 @@ private static void WriteAnsiString16(List data, string text) data.AddRange(bytes); data.Add(0); } - - private static void WriteAnsiAppInfo(List data, string name, string version, string product) - { - WriteAnsiString16(data, name); - data.AddRange([0x00, 0x00, 0x00, 0x00]); // u32 marker/unknown word - WriteAnsiString16(data, string.Empty); - WriteAnsiString16(data, $""); - WriteAnsiString16(data, version); - } } diff --git a/tests/DwgIO.Tests/JsonExporterTests.cs b/tests/DwgIO.Tests/JsonExporterTests.cs index 7ab59d9..11afcaa 100644 --- a/tests/DwgIO.Tests/JsonExporterTests.cs +++ b/tests/DwgIO.Tests/JsonExporterTests.cs @@ -35,6 +35,29 @@ private static DwgEntity CreateEntity(double[] geometry) => Geometry = geometry, }; + [Fact] + public void Write_LeavesObjectTypeCodesAndAddsNames() + { + var header = new DwgFileHeader + { + Version = DwgVersionInfo.FromMagic("AC1032"u8.ToArray()), + Codepage = 30, MaintenanceVersion = 0, PreviewOffset = 0, + }; + var item = new DwgObjectInfo + { + TypeCode = 0x13, Handle = 1, StreamHandle = new DwgHandle(0, 1, 1), + StreamOffset = 4, SizeBytes = 2, BitsStart = 6, BitsLength = 16, + }; + var document = new DwgDocument("synthetic.dwg", header, [], objects: [item]); + using var buffer = new MemoryStream(); + DwgJsonExporter.Write(document, buffer, DwgJsonExportOptions.Default); + using var json = JsonDocument.Parse(buffer.ToArray()); + var objects = json.RootElement.GetProperty("objects"); + + Assert.Equal(1, objects.GetProperty("byType").GetProperty("13").GetInt32()); + Assert.Equal(1, objects.GetProperty("byTypeName").GetProperty("LINE").GetInt32()); + } + [Fact] public void Write_NonFiniteGeometry_WritesNullAndRecordsDiagnostic() { diff --git a/tests/DwgIO.Tests/MetadataParserTests.cs b/tests/DwgIO.Tests/MetadataParserTests.cs index c7dc503..c957281 100644 --- a/tests/DwgIO.Tests/MetadataParserTests.cs +++ b/tests/DwgIO.Tests/MetadataParserTests.cs @@ -156,6 +156,18 @@ public void AppInfo_Product_ComesFromTheXmlNameAttribute() Assert.Equal("AutoCAD", appInfo.Product); } + [Theory] + [InlineData("", "AutoCAD")] + [InlineData("", "AutoCAD LT")] + [InlineData("", "A & B")] + [InlineData("", "Writer")] + public void AppInfo_Product_HandlesXmlAttributeForms(string xml, string expected) + { + var data = BuildUnicodeAppInfo("AppInfoDataList", (ProductXmlEntryId, xml)); + + Assert.Equal(expected, AppInfoParser.Parse(data, 30).Product); + } + [Fact] public void AppInfo_Product_IsEmptyWithoutANameAttribute() { diff --git a/tests/DwgIO.Tests/ObjectStreamGapTests.cs b/tests/DwgIO.Tests/ObjectStreamGapTests.cs index e9e1840..cde7768 100644 --- a/tests/DwgIO.Tests/ObjectStreamGapTests.cs +++ b/tests/DwgIO.Tests/ObjectStreamGapTests.cs @@ -70,6 +70,21 @@ public void Walk_ZeroGapWithoutMap_EndsCleanly() Assert.Empty(diagnostics); } + [Fact] + public void CountUnreachedObjects_UsesBothHandleAndOffset() + { + var stream = new RecordBitWriter(); + stream.WriteRecord(r => r.WriteLineRecord()); + var objects = ObjectStreamWalker.Walk(stream.ToArray(), r2010Plus: true); + var item = Assert.Single(objects); + var map = new DwgHandleMap + { + Entries = [new DwgHandleMapEntry(item.Handle, (ulong)item.StreamOffset + 1)], + }; + + Assert.Equal(1, DwgDocument.CountUnreachedObjects(objects, map)); + } + [Fact] public void Walk_TruncatedTailWithoutRecovery_ReportsTheStop() { diff --git a/tests/DwgIO.Tests/OpenStreamTests.cs b/tests/DwgIO.Tests/OpenStreamTests.cs index 71423f8..2a5272e 100644 --- a/tests/DwgIO.Tests/OpenStreamTests.cs +++ b/tests/DwgIO.Tests/OpenStreamTests.cs @@ -99,22 +99,19 @@ public void Open_Stream_DefaultName_IsStream() private static string Core(string message) => message[(message.IndexOf(": ", StringComparison.Ordinal) + 2)..]; [SkippableFact] - public void Open_Stream_MatchesPath_OnEveryAvailableDrawing() + public void Open_Stream_MatchesPath_OnEveryAvailableDrawing() => DwgFixtureTests.CheckAll(path => { - // The same-results gate of #37; runs when private drawings are available (see docs/test-fixtures.md). - foreach (string path in TestFiles.DwgFiles()) - { - var fromPath = DwgDocument.Open(path, new DwgReaderOptions { ReadObjects = true }); - byte[] bytes = File.ReadAllBytes(path); - using var stream = new MemoryStream(bytes); - var fromStream = DwgDocument.Open(stream, Path.GetFileName(path), new DwgReaderOptions { ReadObjects = true }); - - Assert.Equal(fromPath.Version.Magic, fromStream.Version.Magic); - Assert.Equal(fromPath.FileSize, fromStream.FileSize); - Assert.Equal(fromPath.Sections.Count, fromStream.Sections.Count); - Assert.Equal(fromPath.Objects.Count, fromStream.Objects.Count); - Assert.Equal(fromPath.Entities.Count, fromStream.Entities.Count); - Assert.Equal(fromPath.Diagnostics.Count, fromStream.Diagnostics.Count); - } - } + var fromPath = DwgDocument.Open(path); + using var stream = File.OpenRead(path); + var fromStream = DwgDocument.Open(stream, path); + using var fileJson = new MemoryStream(); + using var streamJson = new MemoryStream(); + Json.DwgJsonExporter.Write(fromPath, fileJson, Json.DwgJsonExportOptions.Default); + Json.DwgJsonExporter.Write(fromStream, streamJson, Json.DwgJsonExportOptions.Default); + + Assert.Equal(fromPath.Diagnostics, fromStream.Diagnostics); + Assert.True(fileJson.GetBuffer().AsSpan(0, (int)fileJson.Length) + .SequenceEqual(streamJson.GetBuffer().AsSpan(0, (int)streamJson.Length))); + return true; + }, "a readable container"); } From 22b3cfc3fce40bfbf99c924504761179ac59c55a Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 04:38:29 +0300 Subject: [PATCH 19/19] Apply protected ACL fixtures to both OBJ output files --- tests/DwgIO.Tests/DwgSceneExportTests.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/DwgIO.Tests/DwgSceneExportTests.cs b/tests/DwgIO.Tests/DwgSceneExportTests.cs index 1d317d3..9402f1e 100644 --- a/tests/DwgIO.Tests/DwgSceneExportTests.cs +++ b/tests/DwgIO.Tests/DwgSceneExportTests.cs @@ -232,13 +232,13 @@ public void SaveObj_Overwrite_PreservesBothFilesAccessRules() if (OperatingSystem.IsWindows()) { var user = System.Security.Principal.WindowsIdentity.GetCurrent().User!; - var acl = new System.Security.AccessControl.FileSecurity(); - acl.SetAccessRuleProtection(true, preserveInheritance: false); - acl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(user, - System.Security.AccessControl.FileSystemRights.FullControl, - System.Security.AccessControl.AccessControlType.Allow)); foreach (string path in paths) { + var acl = new System.Security.AccessControl.FileSecurity(); + acl.SetAccessRuleProtection(true, preserveInheritance: false); + acl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(user, + System.Security.AccessControl.FileSystemRights.FullControl, + System.Security.AccessControl.AccessControlType.Allow)); new FileInfo(path).SetAccessControl(acl); }