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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ API between minor releases.
## [Unreleased]

### Added
- `LAYER` (`0x33`) table decoding (`DwgLayerInfo`, `DwgDocument.Layers`, `DwgReaderOptions.ReadLayers`) and entity `LayerHandle` / `LayerName` / `EffectiveColorIndex` / `EffectiveTrueColorRgb` `BYLAYER` colour resolution across `DwgIO`, `DwgIO.Scene`, JSON export, SVG, `dwgio inspect` and the 2D HTML viewer (with interactive layer visibility chips).
- `--unit auto` reads a supported `$INSUNITS` for scene, OBJ, GLB and HTML exports. These commands default to metres.
- `AcDb:Header` parsing (`DwgHeaderVariables`, `DwgInsUnits`, `DwgPoint2D`, `DwgPoint3D`, `DwgDocument.HeaderVariables`, `DwgReaderOptions.ReadHeader`) exposing `$INSUNITS`, `$MEASUREMENT`, extents/limits, units formatting, point style (`$PDMODE`/`$PDSIZE`), linetype/text/dim scales, timestamps, `$HANDSEED`, and GUIDs in JSON export, `dwgio inspect`, `DwgSceneOptions.UseDrawingUnits` and the 2D HTML viewer.
- `AcDb:Classes` parsing (`DwgClassInfo`, `DwgDocument.Classes`, `DwgReaderOptions.ReadClasses`) resolving class names (codes 500+) and `IsEntity` flags in `DwgObjectInfo`, JSON export and `dwgio inspect`.
Expand Down
7 changes: 4 additions & 3 deletions docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ change in any release and is visible only to the test project through `Internals

| Type | Use |
|---|---|
| `DwgDocument` | Opens a drawing (`Open` / `OpenAsync` from path or stream) and gives `SourcePath` (null for streams), `Path`, `Version`, file and container headers, header variables (`HeaderVariables`), section catalog, metadata, handle map, object inventory, entities and `Diagnostics`. `ReadSection(name)` returns decompressed section bytes; `ReleaseSectionBuffers()` drops retained raw buffers; `SaveJson` / `ToJson` write JSON. |
| `DwgReaderOptions` | What `Open` reads and enforces: `ReadSectionMap`, `ReadSummaryInfo`, `ReadMetadata`, `ReadHeader`, `ReadClasses`, `ReadObjects`, `ReadEntities`, `VerifyChecksums`, `Strict` (throws on diagnostics), `ReleaseSectionBuffers`, `MaxFileBytes`, `MaxSectionBytes`, `MaxDecompressedBytes`, `MaxObjectCount`, `Progress` and `DiagnosticOutput`. |
| `DwgDocument` | Opens a drawing (`Open` / `OpenAsync` from path or stream) and gives `SourcePath` (null for streams), `Path`, `Version`, file and container headers, header variables (`HeaderVariables`), `Layers`, section catalog, metadata, handle map, object inventory, entities and `Diagnostics`. `ReadSection(name)` returns decompressed section bytes; `ReleaseSectionBuffers()` drops retained raw buffers; `SaveJson` / `ToJson` write JSON. |
| `DwgReaderOptions` | What `Open` reads and enforces: `ReadSectionMap`, `ReadSummaryInfo`, `ReadMetadata`, `ReadHeader`, `ReadClasses`, `ReadObjects`, `ReadLayers`, `ReadEntities`, `VerifyChecksums`, `Strict` (throws on diagnostics), `ReleaseSectionBuffers`, `MaxFileBytes`, `MaxSectionBytes`, `MaxDecompressedBytes`, `MaxObjectCount`, `Progress` and `DiagnosticOutput`. |
| `DwgReadProgress` | Synchronous phase updates (`Phase`, `Completed`, `Total`) delivered via `DwgReaderOptions.Progress`. |
| `DwgExitCodes` | Standard CLI exit codes (`Ok = 0`, `Usage = 1`, `FileNotFound = 2`, `UnsupportedVersion = 3`, `ParseError = 4`, `NoPreview = 5`). |
| `DwgException` | Thrown for a damaged or truncated file, exceeded reader limits, `Strict` diagnostic failures, and by `ReadSection` when buffers were released or a section is missing. |
Expand All @@ -37,7 +37,8 @@ change in any release and is visible only to the test project through `Internals
| `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 (`TypeName` resolves fixed names and `AcDb:Classes` names) and handle. |
| `DwgClassInfo` | One class definition from `AcDb:Classes` (codes 500+): `ClassNumber`, `AppName`, `CppClassName`, `DxfName`, `ItemClassId`, `IsEntity`, `InstanceCount`. |
| `DwgEntity`, `DwgEntityKind` | A decoded entity with its handle, type, colour (`ColorIndex` and optional `TrueColorRgb`), linetype scale, `IsModelSpace` flag and decoded `Geometry` for LINE, CIRCLE, ARC, POINT, LWPOLYLINE, ELLIPSE, SOLID/TRACE, 3DFACE, RAY and XLINE. |
| `DwgLayerInfo` | One layer record (`0x33`) from `AcDb:AcDbObjects`: `Handle`, `Name`, `ColorIndex`, `TrueColorRgb`, `IsFrozen`, `IsOff`/`IsOn`, `IsLocked`, `IsPlottable`, `LineWeight` and `IsVisible`. |
| `DwgEntity`, `DwgEntityKind` | A decoded entity with its handle, type, colour (`ColorIndex`, `TrueColorRgb`, and BYLAYER-resolved `EffectiveColorIndex`/`EffectiveTrueColorRgb`), layer (`LayerHandle`, `LayerName`), linetype scale, `IsModelSpace` flag and decoded `Geometry` for LINE, CIRCLE, ARC, POINT, LWPOLYLINE, ELLIPSE, SOLID/TRACE, 3DFACE, RAY and XLINE. |
| `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. |
Expand Down
121 changes: 114 additions & 7 deletions src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,25 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op
});
w.WriteNumber("totalEntities", document.Entities.Count);

w.WriteStartArray("layers");
foreach (var layer in document.Layers)
{
w.WriteStartObject();
w.WriteString("handle", layer.Handle.ToString("X", CultureInfo.InvariantCulture));
w.WriteString("name", layer.Name);
w.WriteNumber("colorIndex", layer.ColorIndex);
bool layerAdaptive = layer.TrueColorRgb is null && IsAdaptiveColor(layer.ColorIndex);
w.WriteBoolean("isAdaptiveColor", layerAdaptive);
w.WriteString("rgb", FormatFixedRgb(layer.ColorIndex, layer.TrueColorRgb));
w.WriteBoolean("isOn", layer.IsOn);
w.WriteBoolean("isFrozen", layer.IsFrozen);
w.WriteBoolean("isLocked", layer.IsLocked);
w.WriteBoolean("visible", layer.IsVisible);
w.WriteEndObject();
}

w.WriteEndArray();

w.WriteStartArray("entities");
int drawnCount = 0;
int skippedNonFinite = 0;
Expand Down Expand Up @@ -102,15 +121,28 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op
}

drawnCount++;
int effColorIndex = entity.EffectiveColorIndex;
uint? effTrueColor = entity.EffectiveTrueColorRgb;
w.WriteStartObject();
w.WriteString("handle", entity.Handle.ToString("X", CultureInfo.InvariantCulture));
w.WriteString("type", entity.TypeName);
w.WriteString("kind", entity.Kind.ToString().ToLowerInvariant());
w.WriteNumber("colorIndex", entity.ColorIndex);
bool adaptive = entity.TrueColorRgb is null && IsAdaptiveColor(entity.ColorIndex);
w.WriteString("layer", entity.LayerName ?? "0");
if (entity.LayerHandle is { } layerHandle)
{
w.WriteString("layerHandle", layerHandle.ToString("X", CultureInfo.InvariantCulture));
}

w.WriteNumber("colorIndex", effColorIndex);
if (effColorIndex != entity.ColorIndex)
{
w.WriteNumber("rawColorIndex", entity.ColorIndex);
}

bool adaptive = effTrueColor is null && IsAdaptiveColor(effColorIndex);
w.WriteBoolean("isAdaptiveColor", adaptive);
w.WriteString("rgb", FormatFixedRgb(entity.ColorIndex, entity.TrueColorRgb));
if (entity.TrueColorRgb is { } trueColor)
w.WriteString("rgb", FormatFixedRgb(effColorIndex, effTrueColor));
if (effTrueColor is { } trueColor)
{
w.WriteString("trueColorRgb", string.Create(CultureInfo.InvariantCulture, $"#{trueColor:X6}"));
}
Expand Down Expand Up @@ -429,6 +461,29 @@ private static void Expand(double x, double y, ref double minX, ref double minY,
color: var(--text);
border-color: var(--accent);
}
.layer-list {
display: flex;
flex-wrap: wrap;
gap: 4px;
max-height: 76px;
overflow-y: auto;
}
.layer-chip {
display: inline-flex;
align-items: center;
gap: 4px;
background: var(--bg-item);
color: var(--text);
border: 1px solid var(--border);
border-radius: 3px;
padding: 2px 6px;
font-size: 10px;
cursor: pointer;
}
.layer-chip.hidden-layer {
opacity: 0.45;
text-decoration: line-through;
}
.entity-list {
flex: 1;
overflow-y: auto;
Expand Down Expand Up @@ -561,6 +616,7 @@ private static void Expand(double x, double y, ref double minX, ref double minY,
<aside class="sidebar" id="sidebar">
<div class="sidebar-head">
<input type="search" class="search" id="search-input" />
<div class="layer-list" id="layer-chips"></div>
<div class="chips" id="type-chips"></div>
</div>
<div class="entity-list" id="entity-list"></div>
Expand Down Expand Up @@ -596,6 +652,7 @@ private static void Expand(double x, double y, ref double minX, ref double minY,
const ctx = canvas.getContext('2d');
const sidebar = document.getElementById('sidebar');
const entityList = document.getElementById('entity-list');
const layerChips = document.getElementById('layer-chips');
const typeChips = document.getElementById('type-chips');
const searchInput = document.getElementById('search-input');
const propsPanel = document.getElementById('props-panel');
Expand Down Expand Up @@ -632,6 +689,7 @@ private static void Expand(double x, double y, ref double minX, ref double minY,
type: 'Type',
handle: 'Handle',
color: 'ACI Color',
layer: 'Layer',
ltscale: 'LT Scale',
space: 'Space',
model: 'Model',
Expand Down Expand Up @@ -665,6 +723,7 @@ private static void Expand(double x, double y, ref double minX, ref double minY,
type: 'Тип',
handle: 'Handle',
color: 'Цвет ACI',
layer: 'Слой',
ltscale: 'Масштаб линий',
space: 'Пространство',
model: 'Модель',
Expand Down Expand Up @@ -708,8 +767,22 @@ private static void Expand(double x, double y, ref double minX, ref double minY,
let drag = null;

const entities = data.entities || [];
const rawLayers = data.layers || [];
const layerMap = new Map(rawLayers.map((l) => [l.name, l]));
const layerNames = rawLayers.length > 0
? rawLayers.map((l) => l.name)
: Array.from(new Set(entities.map((e) => e.layer || '0')));
const layerVisible = new Map(layerNames.map((name) => {
const info = layerMap.get(name);
return [name, info ? info.visible !== false : true];
}));
const types = ['ALL', ...Array.from(new Set(entities.map((e) => e.type)))];

function isEntityVisible(e) {
const lname = e.layer || '0';
return layerVisible.has(lname) ? layerVisible.get(lname) : true;
}

function t(key) {
return i18n[lang][key] ?? key;
}
Expand Down Expand Up @@ -1090,13 +1163,14 @@ function draw() {
ctx.lineJoin = 'round';
for (let i = 0; i < entities.length; i++) {
if (i === selectedIndex || i === hoveredIndex) continue;
if (!isEntityVisible(entities[i])) continue;
drawEntity(entities[i], w, h, null, 1.35);
}

if (hoveredIndex >= 0 && hoveredIndex !== selectedIndex) {
if (hoveredIndex >= 0 && hoveredIndex !== selectedIndex && isEntityVisible(entities[hoveredIndex])) {
drawEntity(entities[hoveredIndex], w, h, '#38bdf8', 2.4);
}
if (selectedIndex >= 0) {
if (selectedIndex >= 0 && isEntityVisible(entities[selectedIndex])) {
drawEntity(entities[selectedIndex], w, h, '#38bdf8', 3.0);
}

Expand Down Expand Up @@ -1133,6 +1207,7 @@ function hitTest(wx, wy) {
let bestDist = tol;
for (let i = 0; i < entities.length; i++) {
const e = entities[i];
if (!isEntityVisible(e)) continue;
const g = e.geom;
let d = Infinity;
if (e.kind === 'line') {
Expand Down Expand Up @@ -1223,6 +1298,7 @@ function renderProps(e) {
const rows = [
[t('type'), e.type],
[t('handle'), e.handle],
[t('layer'), e.layer || '0'],
[t('color'), colorLabel(e)],
[t('ltscale'), fmt(e.lineTypeScale)],
[t('space'), e.modelSpace ? t('model') : t('paper')],
Expand Down Expand Up @@ -1282,7 +1358,37 @@ function selectEntity(idx) {
draw();
}

function renderLayerChips() {
layerChips.innerHTML = '';
if (layerNames.length === 0) {
layerChips.style.display = 'none';
return;
}
layerChips.style.display = 'flex';
for (const lname of layerNames) {
const info = layerMap.get(lname);
const vis = layerVisible.get(lname) !== false;
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'layer-chip' + (vis ? '' : ' hidden-layer');
const sw = document.createElement('span');
sw.className = 'swatch';
sw.style.background = info ? resolveColor(info) : (theme === 'light' ? '#000000' : '#ffffff');
const txt = document.createElement('span');
txt.textContent = lname;
btn.append(sw, txt);
btn.addEventListener('click', () => {
layerVisible.set(lname, !vis);
renderLayerChips();
renderList();
draw();
});
layerChips.append(btn);
}
}

function renderChips() {
renderLayerChips();
typeChips.innerHTML = '';
for (const type of types) {
const btn = document.createElement('button');
Expand All @@ -1305,8 +1411,9 @@ function renderList() {
const frag = document.createDocumentFragment();
for (let i = 0; i < entities.length; i++) {
const e = entities[i];
if (!isEntityVisible(e)) continue;
if (activeType !== 'ALL' && e.type !== activeType) continue;
if (q && !e.type.toLowerCase().includes(q) && !e.handle.toLowerCase().includes(q)) continue;
if (q && !e.type.toLowerCase().includes(q) && !e.handle.toLowerCase().includes(q) && !(e.layer || '').toLowerCase().includes(q)) continue;
const row = document.createElement('div');
row.className = 'entity-row' + (i === selectedIndex ? ' selected' : '');
const swatch = document.createElement('span');
Expand Down
11 changes: 11 additions & 0 deletions src/DwgIO.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,17 @@ internal static int InspectDocument(DwgDocument doc, TextWriter output)
output.WriteLine($"Classes: {Count(doc.Classes.Count)}");
}

if (doc.Layers.Count > 0)
{
output.WriteLine($"Layers: {Count(doc.Layers.Count)}");
foreach (var layer in doc.Layers.Take(8))
{
string state = layer.IsFrozen ? "frozen" : layer.IsOff ? "off" : "on";
string colorDesc = layer.TrueColorRgb is { } rgb ? $"#{rgb:X6}" : $"aci={layer.ColorIndex}";
output.WriteLine($" {layer.Name} ({colorDesc}, {state})");
}
}

if (doc.Objects.Count > 0)
{
output.WriteLine($"Objects: {Count(doc.Objects.Count)} (handle map: {Count(doc.HandleMap?.Count ?? 0)})");
Expand Down
10 changes: 5 additions & 5 deletions src/DwgIO.Scene.Adapter/DwgSceneReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -251,19 +251,19 @@ document.HeaderVariables is { } header &&

private static RgbaColor? ColourOf(DwgEntity entity)
{
if (entity.TrueColorRgb is { } rgb)
if (entity.EffectiveTrueColorRgb is { } rgb)
{
return new RgbaColor((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb);
}

if (entity.ColorIndex is <= 0 or >= 256)
int colorIndex = entity.EffectiveColorIndex;
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.
// Unresolved BYBLOCK (0) or BYLAYER (256) has no fixed colour of its own.
return null;
}

(byte r, byte g, byte b) = DwgAciPalette.RgbOf(entity.ColorIndex);
(byte r, byte g, byte b) = DwgAciPalette.RgbOf(colorIndex);
return new RgbaColor(r, g, b);
}

Expand Down
Loading
Loading