Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ The default and the fallback for missing or unsupported drawing units are both m
dwgio scene drawing.dwg drawing.scene.json --unit mm
```

The plain export command writes OBJ, GLB and HTML by output extension and accepts the same `--unit` values:
The plain export command writes OBJ, GLB and HTML by output extension and accepts the same `--unit` values.
OBJ and GLB contain model space only; use HTML to view paper-space sheets and their viewports:

```sh
dwgio drawing.dwg drawing.obj --unit mm # Wavefront OBJ + drawing.mtl with the ACI colours
Expand Down
1 change: 1 addition & 0 deletions docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ The CLI uses these exporters and adds a 2D HTML viewer:
- `dwgio drawing.dwg drawing.html --mode 2d` exports an AutoCAD-style top view. Use `--bg black|slate|light` to set its background.
- `dwgio drawing.dwg drawing.html --mode auto` opens paper sheets or flat linework in 2D. Paper sheets remain selectable when the viewer starts in 3D model space.
- `dwgio drawing.dwg out.obj --unit mm` and `dwgio drawing.dwg out.glb --unit mm` pass `--unit` to the scene converter.
These direct CLI exports include only model space, including when the drawing has no block or layout tables.
- The scene, OBJ, GLB and HTML commands use metres by default. Pass `--unit auto` to use a supported `$INSUNITS`.
- External DWG references are skipped by default. Library callers can set `DwgSceneOptions.ResolveXrefs = true` to read trusted sibling DWG files by name.

Expand Down
2 changes: 2 additions & 0 deletions src/DwgIO.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -384,11 +384,13 @@ internal static int ExportDocument(
return DwgExitCodes.Usage;
}

sceneOptions.IncludePaperSpace = false;
var objResult = DwgSceneExport.SaveObj(doc, target, sceneOptions);
output.WriteLine($"{doc.Version} elements={objResult.ElementCount} ({objResult.ElementsWithGeometry} with geometry) -> {target}");
}
else if (Path.GetExtension(target).Equals(".glb", StringComparison.OrdinalIgnoreCase))
{
sceneOptions.IncludePaperSpace = false;
var glbResult = DwgSceneExport.SaveGlb(doc, target, sceneOptions);
output.WriteLine($"{doc.Version} elements={glbResult.ElementCount} ({glbResult.ElementsWithGeometry} with geometry) -> {target}");
}
Expand Down
24 changes: 18 additions & 6 deletions src/DwgIO.Scene.Adapter/DwgSceneReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,14 @@ public void Build()
if (_rootDoc.Blocks.Count == 0 && _rootDoc.Layouts.Count == 0)
{
var ids = new List<long>();
var entitiesByHandle = _options.IncludePaperSpace ? null : IndexEntities(_rootDoc);
foreach (var entity in _rootDoc.Entities)
{
if (entitiesByHandle is not null && !(FindOwningInsert(entity, entitiesByHandle) ?? entity).IsModelSpace)
{
continue;
}

EmitEntity(_rootDoc, entity, Affine3d.Identity, _rootScale, 256, null, sheetKey: null, recordForViewports: false, ids);
}
}
Expand Down Expand Up @@ -855,12 +861,7 @@ private static DocIndex IndexDocument(DwgDocument doc)
}
}

var entityByHandle = new Dictionary<ulong, DwgEntity>(doc.Entities.Count);
foreach (var entity in doc.Entities)
{
entityByHandle.TryAdd(entity.Handle, entity);
}

var entityByHandle = IndexEntities(doc);
var byBlock = new Dictionary<ulong, List<DwgEntity>>();
void AddToBlock(ulong blkHandle, DwgEntity e)
{
Expand Down Expand Up @@ -924,6 +925,17 @@ void AddToBlock(ulong blkHandle, DwgEntity e)
return new DocIndex(doc, modelHandle, blocks, entityByHandle, byBlock, paperLayouts);
}

private static Dictionary<ulong, DwgEntity> IndexEntities(DwgDocument document)
{
var entitiesByHandle = new Dictionary<ulong, DwgEntity>(document.Entities.Count);
foreach (var entity in document.Entities)
{
entitiesByHandle.TryAdd(entity.Handle, entity);
}

return entitiesByHandle;
}

private static DwgEntity? FindOwningInsert(DwgEntity entity, Dictionary<ulong, DwgEntity> entities) =>
entity.Kind == DwgEntityKind.Attrib && entity.OwnerHandle is ulong handle
&& entities.TryGetValue(handle, out var owner) && owner.Kind == DwgEntityKind.Insert
Expand Down
78 changes: 75 additions & 3 deletions tests/DwgIO.Tests/BlocksAndSheetsTests.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using System.Text;
using DwgIO.Cli;
using DwgIO.Export;
using DwgIO.Model;
using DwgIO.Scene;
using IOScene;
using IOScene.Formats;
using Xunit;

namespace DwgIO.Tests;
Expand Down Expand Up @@ -87,8 +89,7 @@ public void Insert_ExpandsBlockGeometry_WithTransformBasePointAndByBlockColor()
Assert.Equal(new RgbaColor(255, 0, 0), inst.Color);
}

[Fact]
public void PaperSpaceLayoutAndViewport_ProjectAndClipModelSpaceGeometryIntoSheet()
private static DwgDocument DrawingWithViewport()
{
const ulong modelHandle = 0x1F;
const ulong paperHandle = 0x20;
Expand Down Expand Up @@ -186,7 +187,13 @@ public void PaperSpaceLayoutAndViewport_ProjectAndClipModelSpaceGeometryIntoShee
},
};

var doc = new DwgDocument("sheets.dwg", TestHeader, entities, blocks: blocks, layouts: layouts);
return new DwgDocument("sheets.dwg", TestHeader, entities, blocks: blocks, layouts: layouts);
}

[Fact]
public void PaperSpaceLayoutAndViewport_ProjectAndClipModelSpaceGeometryIntoSheet()
{
var doc = DrawingWithViewport();
var result = DwgSceneReader.Read(doc, new DwgSceneOptions
{
LengthUnit = "m",
Expand Down Expand Up @@ -230,6 +237,71 @@ public void PaperSpaceLayoutAndViewport_ProjectAndClipModelSpaceGeometryIntoShee
Assert.Contains("\"initial2DMode\":true", autoHtml, StringComparison.Ordinal);
}

[Theory]
[InlineData(".obj")]
[InlineData(".glb")]
public void DirectExchangeExport_WritesModelLineWithoutProjectedViewportCopy(string extension)
{
AssertDirectExchangeWritesModelLine(DrawingWithViewport(), extension);
}

[Theory]
[InlineData(".obj")]
[InlineData(".glb")]
public void DirectExchangeExport_ExcludesPaperLineWithoutBlockAndLayoutTables(string extension)
{
var document = new DwgDocument("spaces.dwg", TestHeader,
[
new DwgEntity
{
Handle = 0x101, TypeCode = 0x13, TypeName = "LINE", Kind = DwgEntityKind.Line,
IsModelSpace = true, Geometry = [-20.0, 0.0, 0.0, 20.0, 0.0, 0.0],
},
new DwgEntity
{
Handle = 0x102, TypeCode = 0x13, TypeName = "LINE", Kind = DwgEntityKind.Line,
IsModelSpace = false, Geometry = [100.0, 0.0, 0.0, 110.0, 0.0, 0.0],
},
]);

var fullScene = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "spaces.dwg" });
Assert.Equal(2, fullScene.Document.Instances.Count);
AssertDirectExchangeWritesModelLine(document, extension);
}

private static void AssertDirectExchangeWritesModelLine(DwgDocument document, string extension)
{
using var directory = new TemporaryDirectory();
string path = Path.Combine(directory.Path, "model" + extension);

Assert.Equal(DwgExitCodes.Ok, Program.ExportDocument(document, path, TextWriter.Null, TextWriter.Null));

if (extension == ".obj")
{
string[] lines = File.ReadAllLines(path);
Assert.Single(lines, line => line.StartsWith("l ", StringComparison.Ordinal));
Assert.Collection(lines.Where(line => line.StartsWith("v ", StringComparison.Ordinal)).Order(StringComparer.Ordinal),
vertex => Assert.Equal("v -20 0 0", vertex),
vertex => Assert.Equal("v 20 0 0", vertex));
}
else
{
var scene = GlbSceneReader.Load(path);
var instance = Assert.Single(scene.Instances);
var geometry = Assert.Single(scene.Geometries, g => g.Id == instance.GeometryId);
Assert.Equal(SceneTopology.Lines, geometry.Topology);
var vertices = geometry.Vertices.Select((instance.Transform ?? Transform3d.Identity).Apply).OrderBy(v => v.X).ToArray();
Assert.Equal(new[] { new Vector3d(-20, 0, 0), new Vector3d(20, 0, 0) }, vertices);
}
}

private sealed class TemporaryDirectory : IDisposable
{
public string Path { get; } = Directory.CreateTempSubdirectory("dwgio-sheet-").FullName;

public void Dispose() => Directory.Delete(Path, recursive: true);
}

[Theory]
[InlineData(false)]
[InlineData(true)]
Expand Down
9 changes: 9 additions & 0 deletions tests/DwgIO.Tests/HatchDimensionAttribTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,15 @@ public void AttribFollowsOwningInsert_AndInvisibleAttribIsOmitted_InSceneAndSvg(
Assert.Equal("end", (string?)svgText.Attribute("text-anchor"));
Assert.Equal("#FF0000", (string?)svgText.Attribute("fill"), ignoreCase: true);
Assert.Single(svgDoc.Descendants(XName.Get("path", "http://www.w3.org/2000/svg")));

var documentWithoutTables = new DwgDocument("attribs.dwg", Header2018, entities);
var modelOnly = DwgSceneReader.Read(documentWithoutTables, new DwgSceneOptions
{
ModelKey = "attribs.dwg",
IncludePaperSpace = false,
});
Assert.Equal("VISIBLE_VAL", Assert.Single(modelOnly.Annotations).Text);
Assert.Single(modelOnly.Document.Geometries, geometry => geometry.Topology == SceneTopology.Lines);
}

[Fact]
Expand Down
Loading