Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 1 addition & 12 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
strategy:
fail-fast: false
matrix:
os: [windows-latest]
os: [windows-latest, ubuntu-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v7
Expand All @@ -31,14 +31,3 @@ jobs:
name: packages-${{ matrix.os }}
path: artifacts/*.nupkg
if-no-files-found: error

build-linux:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-dotnet@v6
with:
dotnet-version: |
8.0.x
10.0.x
- run: dotnet build src/DwgIO.Cli/DwgIO.Cli.csproj -c Release
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,20 @@ API between minor releases.
## [Unreleased]

### Added
- CI runs the tests on Linux and macOS as well as Windows (both target frameworks), replacing the Linux
build-only job (#34).
- `test-files/public`: the folder for committed redistributable test drawings, with the origin and licence
recorded next to each file; the fixture search includes it, so a committed drawing turns the skipped
fixture tests into real runs in CI (#33, infrastructure — the drawings themselves follow).
- `DwgDocument.Open(Stream, documentName?, options?)`: a drawing can now come from a stream (a network
handle, an archive entry, an already-open file). The stream is read to memory once, so the results are
identical to `Open(path)` on the same bytes; the unsupported-version message names the source (#37, first
step — reading data pages on demand remains open).
- `AcDb:RevHistory`, `AcDb:AuxHeader` and `AcDb:Template` parsing exposes the revision values, auxiliary
header and template description on `DwgDocument`, in JSON and in `dwgio inspect`. The undecoded
`AcDb:AppInfoHistory` section is exposed as decompressed bytes, with its size in JSON and CLI output (#36).
- Fixed object type names are available in `DwgObjectInfo.TypeName`, `dwgio inspect` and the JSON
`objects.byTypeName` field. Existing `objects.byType` keys are preserved (#20, fixed types only).
- `dwgio --version` and `--help` (and `-v`/`-h`) print the version and the usage with exit code 0; an unknown
option still exits 1 (#18).
- `dwgio entities <file.dwg> [--type LINE,CIRCLE] [--json]` lists decoded entities one line each or as a JSON
Expand Down
7 changes: 4 additions & 3 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,9 @@ facts as they are observed in DWG files, in your own words, in code comments,
documentation and commit messages.

Do not add vendor code, SDKs, SDK internals, headers or binaries, decompiled or
leaked source, or anything taken from analysing vendor binaries. Do not add DWG
or DXF drawings, customer data, or names, paths, sizes or other details of
leaked source, or anything taken from analysing vendor binaries.
Add DWG fixtures only under `test-files/public` and only when they meet its origin and licence rules.
Do not add other drawings, customer data, or names, paths, sizes or other details of
private sample drawings to the repository, including tests, comments and
documentation. Test inputs are built synthetically in the tests; tests that
need private drawings read them from the folder named by `DWGIO_TEST_FILES` and
Expand Down Expand Up @@ -87,7 +88,7 @@ Include:
- The build and test commands run, their results, and any skipped checks.
- Before and after output comparison results when the output is affected.

Do not add drawings, customer data, vendor code or binaries to the
Do not add private drawings, customer data, vendor code or binaries to the
repository. Keep private test drawings outside version control.

Write commit messages in the imperative mood, for example,
Expand Down
4 changes: 2 additions & 2 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<ItemGroup>
<!-- Build-time only. -->
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="10.0.403" />
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="10.0.404" />
</ItemGroup>

<ItemGroup>
Expand All @@ -20,7 +20,7 @@

<ItemGroup>
<!-- Test-only packages, pinned to exact versions (no floating ranges). -->
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.1" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.12.0" />
<PackageVersion Include="xunit" Version="2.9.3" />
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
</ItemGroup>
Expand Down
11 changes: 7 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ dotnet add package DwgIO
dotnet add package DwgIO.Scene
```

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.
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 run on Windows, Linux and macOS.

## Command line

Expand Down Expand Up @@ -113,7 +113,7 @@ dwgio drawing.dwg - | jq .summaryInfo

## Library

Open a drawing, list its sections and read one of them:
Open a drawing (from a path or from a stream — a network handle, an archive entry, an already-open file; the stream is read to memory once and `Open(Stream)` gives the same results as `Open(path)`), list its sections and read one of them:

```csharp
using System;
Expand All @@ -123,6 +123,9 @@ var doc = DwgDocument.Open("drawing.dwg");

Console.WriteLine($"{doc.Version.Release} ({doc.Version.Magic})");

// or from a stream:
// var doc = DwgDocument.Open(httpResponse.Content.ReadAsStream(), "remote.dwg");

foreach (var section in doc.Sections)
{
Console.WriteLine($"{section.Name,-24} {section.Size,12} bytes pages={section.PageCount}");
Expand Down Expand Up @@ -151,7 +154,7 @@ 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.
`DwgSceneExport` writes that scene out in the exchange formats: `SaveObj(document, "drawing.obj", options)` produces an OBJ with an adjacent MTL colour library (with rollback if replacement fails), `SaveGlb(document, "drawing.glb", options)` produces binary glTF. Both return the same `DwgSceneResult` report.

The documentation site with the API reference is at <https://ioextend.github.io/DwgIO/>. [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/IOExtend/DwgIO) offers an automatically generated overview of the repository.

Expand Down Expand Up @@ -182,7 +185,7 @@ The documentation site with the API reference is at <https://ioextend.github.io/
| AC1012 | R13 | flat section locators | planned |
| AC1014 | R14 | flat section locators | planned |
| AC1015 | R2000 | flat section locators | planned |
| AC1018 | R2004 | paged, compressed sections | done |
| AC1018 | R2004 | paged, compressed sections | verified locally on real drawings |
| AC1021 | R2007 | Reed-Solomon coded pages | planned |
| AC1024 | R2010 | paged, compressed sections | done |
| AC1027 | R2013 | paged, compressed sections | done |
Expand Down
16 changes: 12 additions & 4 deletions docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ change in any release and is visible only to the test project through `Internals

| Type | Use |
|---|---|
| `DwgDocument` | Opens a drawing (`Open`) and gives its version, file and container headers, section catalog, metadata, handle map, object inventory, entities and `Diagnostics`. `ReadSection(name)` returns the decompressed bytes of one named section. |
| `DwgDocument` | Opens a drawing (`Open(path, options?)` or `Open(stream, documentName?, options?)`) and gives its version, file and container headers, section catalog, metadata, handle map, object inventory, entities and `Diagnostics`. `ReadSection(name)` returns the decompressed bytes of one named section. |
| `DwgReaderOptions` | What `Open` reads: `ReadSectionMap`, `ReadSummaryInfo`, `ReadMetadata`, `ReadObjects`, `ReadEntities` (all on by default) and `VerifyChecksums` (off by default). |
| `DwgException` | Thrown for a damaged or truncated file, and by `ReadSection` for an unknown section name, a document opened without its section map, or a checksum mismatch when `VerifyChecksums` is on. |
| `DwgUnsupportedVersionException` | Thrown when the version is not recognised or its container is not implemented yet (R13 to R2000, R2007). Derives from `DwgException`. |
Expand All @@ -24,6 +24,7 @@ change in any release and is visible only to the test project through `Internals
| Type | Use |
|---|---|
| `DwgVersionInfo`, `DwgContainerFamily` | The release identified from the version magic (`Magic`, `Release`, `Year`, `Family`). |
| `DwgObjectTypes` | The fixed object type codes: `Name(code)` (the AutoCAD or table name, `Class_502` for class-defined codes, `Object_XX` otherwise) and `IsEntity(code)`, per libredwg's dwg.h. |
| `DwgFileHeader` | The 128-byte prefix shared by every version: `Version`, `MaintenanceVersion`, `PreviewOffset`, `Codepage`, `CodepageName`. |
| `DwgContainerHeader` | The decrypted header of AutoCAD 2004 and later files: page and section map locations, `PageCount`, `GapCount`, `StoredCrc32` and `HeaderCrcValid`. |
| `DwgSectionInfo` | One named section: `Name`, `Size`, `PageCount`, `MaxPageSize`, `Compression`, `Encryption`, `SectionId`. |
Expand All @@ -32,8 +33,12 @@ change in any release and is visible only to the test project through `Internals
| `DwgFileDepList`, `DwgFileDependency` | External files the drawing refers to (fonts, images, references). |
| `DwgPreview`, `DwgPreviewImageKind` | The embedded thumbnail and its format (BMP, PNG or WMF). |
| `DwgHandleMap`, `DwgHandleMapEntry` | The handle to offset index of the object stream; `Find(handle)` looks up one object. |
| `DwgObjectInfo`, `DwgHandle` | One record of the object stream: offset, size, type code and handle. |
| `DwgObjectInfo`, `DwgHandle` | One record of the object stream: offset, size, type code (`TypeName` names it) and handle. |
| `DwgEntity`, `DwgEntityKind` | A decoded entity: handle, type, colour, linetype scale and, for LINE, CIRCLE, ARC and POINT, its `Geometry`. |
| `DwgDocument.AppInfoHistory` | Decompressed bytes of `AcDb:AppInfoHistory` when available. The record layout is unknown. |
| `DwgRevHistory` | The save references of `AcDb:RevHistory`: layout version pair and one value per recorded save. |
| `DwgAuxHeader` | The auxiliary header of `AcDb:AuxHeader`: version pair, save counter, creation and last-update times, next handle. |
| `DwgTemplate` | The template description of `AcDb:Template`: description and unit system (English/metric). |

## JSON export (`DwgIO.Json`)

Expand All @@ -52,7 +57,8 @@ DwgJsonExporter.WriteFile(doc, "drawing.json", DwgJsonExportOptions.Default);

The export has the objects `file`, `version`, `containerHeader`, `summaryInfo`, `appInfo`, `preview`, `fileDepList`
and `objects`, the numbers `pageCount` and `entityCount`, the `entities` array and the `sections` array. An object whose data the drawing does not hold is left
out.
out. In `objects`, `byType` keeps hexadecimal keys and `byTypeName` gives the same counts by readable name.
For `appInfoHistory`, the export reports the byte size. Section bytes can be embedded with `IncludeSectionContents`.

## Scene export (`DwgIO.Scene` package)

Expand All @@ -77,7 +83,9 @@ IOScene.SceneJson.Save(result.Document, "drawing.scene.json");
```

The scene validates against the IOScene contract (`SceneDocument.Validate` reports no error) and round-trips through
the IOScene JSON format, so it can be fed to the IOScene tools, viewers and exporters. `DwgSceneExport` writes it to
the IOScene JSON format, so it can be fed to the IOScene tools, viewers and exporters. For HTML display, IOViewer
0.3.1 represents lines and points with thin triangle geometry. The scene and exchange exports retain the original
line and point geometry. `DwgSceneExport` writes it to
OBJ (with an MTL colour library) and GLB through the IOScene.Formats writers.

## Diagnostics
Expand Down
9 changes: 7 additions & 2 deletions docs/test-fixtures.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,23 @@

Most tests build their input in the test itself (cipher, decompression, checksums, bit reading, version detection,
handle map, object stream and metadata parsing) and run everywhere. The fixture tests in `DwgFixtureTests` need real
drawings, which cannot be published. The repository ships no drawings, and `test_files/` is ignored by git.
drawings. The repository ships no drawings yet. Private fixtures belong in the ignored test folder or outside the
repository. Small redistributable drawings can be added under `test-files/public`. Once available, the fixture
tests will use them in CI on Windows, Linux and macOS.

## Where the drawings are looked for

The fixture tests find their input through one helper, `TestFiles` in the test project. Drawings are taken from all
of these folders together:

- the folder named by the environment variable `DWGIO_TEST_FILES` (ignored when the folder does not exist);
- the committed redistributable drawings of [test-files/public](https://github.com/IOExtend/DwgIO/blob/main/test-files/public/README.md), with their
origin and licence recorded next to each file;
- a folder `test_files` in the repository root (or in any parent of the test binary folder).

Every `*.dwg` file directly in such a folder or in one level of subfolders is used, whatever its name. Drawings of the
supported releases (AC1018, AC1024, AC1027, AC1032) are the useful ones. Drawings of an unsupported version
supported releases (AC1018, AC1024, AC1027, AC1032) are the useful ones. AC1018 has been checked on real local drawings and
still needs a redistributable fixture. Drawings of an unsupported version
(AC1012 to AC1015, AC1021) are ignored by the fixture tests and counted in the skip reason, so one file of a
planned release does not fail every test.

Expand Down
47 changes: 41 additions & 6 deletions src/DwgIO.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using System.Text;
using System.Text.Json;
using DwgIO;
using DwgIO.Internal.Parsing;
using DwgIO.Internal;
using DwgIO.Json;
using DwgIO.Model;
using DwgIO.Scene;
Expand Down Expand Up @@ -160,6 +160,27 @@ internal static int InspectDocument(DwgDocument doc, TextWriter output)
}
}

if (!doc.AppInfoHistory.IsEmpty)
{
output.WriteLine($"App history: {Count(doc.AppInfoHistory.Length)} bytes (raw)");
}

if (doc.RevHistory is { } revHistory)
{
output.WriteLine($"Rev history: layout {revHistory.ClassVersion}.{revHistory.ClassMinor} saves={Count(revHistory.Histories.Count)}");
}

if (doc.AuxHeader is { } auxHeader)
{
output.WriteLine($"Aux header: saves={Count(auxHeader.Numsaves)} created={auxHeader.CreatedUtc:yyyy-MM-dd HH:mm} UTC updated={auxHeader.ModifiedUtc:yyyy-MM-dd HH:mm} UTC handseed={auxHeader.Handseed:X}");
}

if (doc.Template is { } template)
{
string units = template.IsMetric ? "metric" : "english";
output.WriteLine($"Template: \"{Truncate(template.Description, 60)}\" units={units}");
}

if (doc.Preview is { } preview)
{
output.WriteLine($"Preview: {preview.ImageKind} {Count(preview.ImageBytes.Length)} bytes");
Expand All @@ -177,9 +198,9 @@ internal static int InspectDocument(DwgDocument doc, TextWriter output)
if (doc.Objects.Count > 0)
{
output.WriteLine($"Objects: {Count(doc.Objects.Count)} (handle map: {Count(doc.HandleMap?.Count ?? 0)})");
foreach (var group in doc.Objects.GroupBy(o => o.TypeCode).OrderByDescending(g => g.Count()).Take(8))
foreach (var group in doc.Objects.GroupBy(o => o.TypeName).OrderByDescending(g => g.Count()).Take(8))
{
output.WriteLine($" type 0x{group.Key:X3}: {Count(group.Count())}");
output.WriteLine($" {group.Key}: {Count(group.Count())}");
}
}

Expand Down Expand Up @@ -296,7 +317,7 @@ private static int Svg(string[] args, TextWriter output, TextWriter error)
{
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)
if (i + 1 >= args.Length || !double.TryParse(args[i + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out scale) || !double.IsFinite(scale) || scale <= 0)
{
error.WriteLine("error: --scale needs a positive number of pixels per drawing unit.");
return ExitUsage;
Expand Down Expand Up @@ -363,7 +384,7 @@ private static int Scene(string[] args, TextWriter output, TextWriter error)
}

var result = DwgSceneReader.Read(positional[0], options);
SceneJson.Save(result.Document, positional[1]);
AtomicOutput.Write(positional[1], stream => SceneJson.Write(result.Document, stream));
output.WriteLine(
$"{result.Document.Title}: {Count(result.ElementCount)} elements ({Count(result.ElementsWithGeometry)} with geometry) -> {positional[1]}");
foreach (var diagnostic in result.Diagnostics.Take(5))
Expand Down Expand Up @@ -394,6 +415,12 @@ private static int Preview(string[] args, TextWriter output, TextWriter error)
/// <summary>Writes the thumbnail of an opened document. Internal for the CLI tests.</summary>
internal static int PreviewDocument(DwgDocument doc, string requested, TextWriter output, TextWriter error)
{
if (doc.PreviewReadError is not null)
{
error.WriteLine($"error: {doc.PreviewReadError}");
return ExitParseError;
}

var preview = doc.Preview;
if (preview is null || !preview.HasImage)
{
Expand Down Expand Up @@ -459,6 +486,8 @@ private static int Entities(string[] args, TextWriter output, TextWriter error)
case "--json":
json = true;
break;
case string option when option.StartsWith('-'):
return UnknownOption(option, output, error);
default:
if (file is not null)
{
Expand All @@ -483,14 +512,20 @@ private static int Entities(string[] args, TextWriter output, TextWriter error)
continue;
}

if (!EntityDecoder.KnownTypeNames.Contains(trimmed))
if (!DwgObjectTypes.KnownNames.Contains(trimmed))
{
error.WriteLine($"error: unknown type '{trimmed}'. Known types include LINE, CIRCLE, ARC, POINT, TEXT and MTEXT.");
return ExitUsage;
}

filter.Add(trimmed);
}

if (filter.Count == 0)
{
error.WriteLine("error: --type needs at least one type name.");
return ExitUsage;
}
}

if (file is null)
Expand Down
17 changes: 17 additions & 0 deletions src/DwgIO.Scene/ArcAngles.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
namespace DwgIO.Scene;

internal static class ArcAngles
{
public static (double Start, double Span) Normalize(double start, double end)
{
start = PositiveAngle(start);
double span = PositiveAngle(end) - start;
return (start, span <= 0 ? span + Math.Tau : span);
}

public static double PositiveAngle(double radians)
{
double turn = radians % Math.Tau;
return turn < 0 ? turn + Math.Tau : turn;
}
}
Loading
Loading