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
- `TEXT` (`0x01`) and `MTEXT` (`0x2C`) decoding (`DwgEntityKind.Text`, `DwgEntityKind.MText`, `DwgEntity.Text`, `DwgEntity.PlainText` formatting stripper) and text rendering across `DwgJsonExporter`, `DwgSvgExporter`, `dwgio inspect`/`entities`, and the 2D HTML viewer.
- `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.
Expand Down
2 changes: 1 addition & 1 deletion docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ change in any release and is visible only to the test project through `Internals
| `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`. |
| `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. |
| `DwgEntity`, `DwgEntityKind` | A decoded entity with its handle, type, colour (`ColorIndex`, `TrueColorRgb`, and BYLAYER-resolved `EffectiveColorIndex`/`EffectiveTrueColorRgb`), layer (`LayerHandle`, `LayerName`), linetype scale, `IsModelSpace` flag, `Text`/`PlainText` and decoded `Geometry` for LINE, CIRCLE, ARC, POINT, LWPOLYLINE, ELLIPSE, SOLID/TRACE, 3DFACE, RAY, XLINE, TEXT and MTEXT. |
| `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
4 changes: 2 additions & 2 deletions docs/test-fixtures.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ repository.

## Where the drawings are looked for

The required `PublicDrawing_DecodesAuthoredPrimitives` theory reads only the three committed drawings, copied
The required public fixture tests read the committed drawings, copied
to a dedicated subfolder of the test output at build time. This works even when `--artifacts-path` places the
assembly outside the checkout.

Expand All @@ -30,7 +30,7 @@ planned release does not fail every test.
Optional fixture checks are reported as **skipped with a reason** when no eligible drawing is available.
If no drawing is found, the reason names `DWGIO_TEST_FILES`. The attributes `[SkippableFact]` and
`[SkippableTheory]` (`SkippableFact.cs`) report `SkipException` as a skip, because xunit 2.9 has no runtime skip
of its own. The public geometry theory requires all three committed drawings and fails if any is missing
of its own. The public fixture tests fail if a required drawing is missing
from the test output.

No test uses a fixed absolute path.
Expand Down
2 changes: 1 addition & 1 deletion src/DwgIO.Cli/DwgIO.Cli.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

<ItemGroup>
<PackageReference Include="IOViewer" />
<Compile Include="..\Shared\AtomicOutput.cs;..\Shared\ArcAngles.cs;..\Shared\DwgAciPalette.cs;..\Shared\EllipseAxes.cs"
<Compile Include="..\Shared\AtomicOutput.cs;..\Shared\ArcAngles.cs;..\Shared\DwgAciPalette.cs;..\Shared\EllipseAxes.cs;..\Shared\TextPlacement.cs"
Link="Shared\%(Filename)%(Extension)" />
<InternalsVisibleTo Include="DwgIO.Tests" />
</ItemGroup>
Expand Down
52 changes: 49 additions & 3 deletions src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,8 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op
continue;
}

if (!TryExpandBounds(entity, ref minX, ref minY, ref maxX, ref maxY, out var ellipseMinor))
string? textValue = entity.PlainText;
if (!TryExpandBounds(entity, textValue, ref minX, ref minY, ref maxX, ref maxY, out var ellipseMinor))
{
continue;
}
Expand Down Expand Up @@ -149,6 +150,14 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op

w.WriteNumber("lineTypeScale", double.IsFinite(entity.LineTypeScale) ? Math.Round(entity.LineTypeScale, 6) : 1.0);
w.WriteBoolean("modelSpace", entity.IsModelSpace);
if (textValue is not null)
{
w.WriteString("text", textValue);
var (column, row) = TextPlacement.Alignment(entity.Kind, entity.Geometry);
w.WriteNumber("textColumn", column);
w.WriteNumber("textRow", row);
}

if (ellipseMinor is { } minor)
{
w.WriteNumber("ellipseMinorX", minor.X);
Expand Down Expand Up @@ -213,7 +222,7 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op
}

private static bool TryExpandBounds(
DwgEntity entity, ref double minX, ref double minY, ref double maxX, ref double maxY,
DwgEntity entity, string? text, ref double minX, ref double minY, ref double maxX, ref double maxY,
out (double X, double Y, double Z)? ellipseMinor)
{
ellipseMinor = null;
Expand Down Expand Up @@ -274,6 +283,12 @@ private static bool TryExpandBounds(
case (DwgEntityKind.Ray or DwgEntityKind.XLine, [var rx, var ry, _, _, _, _]):
Expand(rx, ry, ref minX, ref minY, ref maxX, ref maxY);
return true;
case (DwgEntityKind.Text or DwgEntityKind.MText, { Length: >= 5 } g) when g[3] > 0 && text is { Length: > 0 }:
var (column, row) = TextPlacement.Alignment(entity.Kind, g);
var textBounds = TextPlacement.EstimateBounds(g[0], -g[1], g[3], g[4], text, column, row);
Expand(textBounds.MinX, -textBounds.MaxY, ref minX, ref minY, ref maxX, ref maxY);
Expand(textBounds.MaxX, -textBounds.MinY, ref minX, ref minY, ref maxX, ref maxY);
return true;
default:
return false;
}
Expand Down Expand Up @@ -1147,6 +1162,29 @@ function drawEntity(entity, w, h, overrideColor, lineWidth) {
ctx.lineTo(sx2, sy2);
ctx.stroke();
ctx.restore();
} else if (entity.kind === 'text' || entity.kind === 'mtext') {
const content = entity.text || '';
if (!content) return;
const th = g[3] > 0 ? g[3] : 1;
const hPx = th * cam.scale;
if (hPx < 0.7 || !Number.isFinite(hPx)) return;
const [sx, sy] = worldToScreen(g[0], g[1], w, h);
const rot = g[4] || 0;
const lines = content.split('\n');
ctx.save();
ctx.translate(sx, sy);
if (Math.abs(rot) > 1e-6) ctx.rotate(-rot);
ctx.fillStyle = color;
ctx.font = `${hPx}px ui-sans-serif, system-ui, sans-serif`;
const col = entity.textColumn, row = entity.textRow;
ctx.textAlign = col === 1 ? 'center' : col === 2 ? 'right' : 'left';
ctx.textBaseline = row === 0 ? 'top' : row === 1 ? 'middle' : row === 2 ? 'bottom' : 'alphabetic';
const lineStep = hPx * 1.25;
const firstBaseline = row > 0 ? -(lines.length - 1) * lineStep * row / 2 : 0;
for (let li = 0; li < lines.length; li++) {
ctx.fillText(lines[li], 0, firstBaseline + li * lineStep);
}
ctx.restore();
}
}

Expand Down Expand Up @@ -1268,6 +1306,9 @@ function hitTest(wx, wy) {
d = Math.hypot(wx - g[0], wy - g[1]);
}
}
} else if (e.kind === 'text' || e.kind === 'mtext') {
const th = Math.max(g[3] || 1, 0.1);
d = Math.hypot(wx - g[0], wy - g[1]) <= th * 1.5 ? 0 : Math.hypot(wx - g[0], wy - g[1]);
}
if (d <= bestDist) {
bestDist = d;
Expand Down Expand Up @@ -1337,6 +1378,11 @@ function renderProps(e) {
} else if (e.kind === 'ray' || e.kind === 'xline') {
rows.push([t('position'), `(${fmt(g[0])}, ${fmt(g[1])}, ${fmt(g[2])})`]);
rows.push(['Direction', `(${fmt(g[3])}, ${fmt(g[4])}, ${fmt(g[5])})`]);
} else if (e.kind === 'text' || e.kind === 'mtext') {
rows.push([t('position'), `(${fmt(g[0])}, ${fmt(g[1])}, ${fmt(g[2])})`]);
rows.push(['Height', fmt(g[3])]);
rows.push(['Rotation', `${fmt((g[4] || 0) * 180 / Math.PI)}°`]);
if (e.text) rows.push(['Text', e.text]);
}

propsGrid.innerHTML = '';
Expand Down Expand Up @@ -1413,7 +1459,7 @@ function renderList() {
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) && !(e.layer || '').toLowerCase().includes(q)) continue;
if (q && !e.type.toLowerCase().includes(q) && !e.handle.toLowerCase().includes(q) && !(e.layer || '').toLowerCase().includes(q) && !(e.text || '').toLowerCase().includes(q)) continue;
const row = document.createElement('div');
row.className = 'entity-row' + (i === selectedIndex ? ' selected' : '');
const swatch = document.createElement('span');
Expand Down
77 changes: 77 additions & 0 deletions src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,56 @@ public static void Write(DwgDocument document, XmlWriter writer, DwgSvgOptions?
writer.WriteAttributeString("r", Num(markerRadius));
writer.WriteAttributeString("fill", stroke);
writer.WriteAttributeString("stroke", "none");
writer.WriteEndElement();
break;
case SvgText label:
writer.WriteStartElement("text");
writer.WriteAttributeString("x", Num(label.X));
writer.WriteAttributeString("y", Num(label.Y));
writer.WriteAttributeString("font-size", Num(label.Height));
writer.WriteAttributeString("font-family", "sans-serif");
writer.WriteAttributeString("text-anchor", label.Column switch { 1 => "middle", 2 => "end", _ => "start" });
writer.WriteAttributeString("dominant-baseline", label.Row switch
{
0 => "text-before-edge",
1 => "central",
2 => "text-after-edge",
_ => "alphabetic",
});
writer.WriteAttributeString("fill", stroke);
writer.WriteAttributeString("stroke", "none");
if (Math.Abs(label.RotationRad) > 1e-6)
{
double deg = -label.RotationRad * 180.0 / Math.PI;
writer.WriteAttributeString("transform", FormattableString.Invariant($"rotate({Num(deg)} {Num(label.X)} {Num(label.Y)})"));
}

string[] lines = label.Text.Split('\n');
if (label.Row > 0 && lines.Length > 1)
{
writer.WriteAttributeString("dy", Num(-(lines.Length - 1) * label.Height * 1.25 * label.Row / 2));
}

if (lines.Length == 1)
{
writer.WriteString(lines[0]);
}
else
{
for (int li = 0; li < lines.Length; li++)
{
writer.WriteStartElement("tspan");
writer.WriteAttributeString("x", Num(label.X));
if (li > 0)
{
writer.WriteAttributeString("dy", Num(label.Height * 1.25));
}

writer.WriteString(lines[li]);
writer.WriteEndElement();
}
}

writer.WriteEndElement();
break;
}
Expand Down Expand Up @@ -153,6 +203,10 @@ private sealed record SvgPoint(double X, double Y, int ColorIndex, uint? TrueCol
private sealed record SvgPath(string Data, IReadOnlyList<(double X, double Y)> BoundsPoints, bool Fill, int ColorIndex, uint? TrueColorRgb)
: SvgShape(ColorIndex, TrueColorRgb);

private sealed record SvgText(
double X, double Y, double Height, double RotationRad, string Text, int Column, int Row, int ColorIndex, uint? TrueColorRgb)
: SvgShape(ColorIndex, TrueColorRgb);

private static List<SvgShape> Collect(DwgDocument document, DwgSvgOptions options)
{
double scale = options.Scale;
Expand Down Expand Up @@ -245,6 +299,23 @@ private static List<SvgShape> Collect(DwgDocument document, DwgSvgOptions option
Skip(options.ReportDiagnostic, entity, "non-finite coordinates");
}

break;
case (DwgEntityKind.Text or DwgEntityKind.MText, { Length: >= 5 } g):
if (IsUsable(g[0] * scale, g[1] * scale, g[3] * scale, g[4]) && g[3] > 0 && entity.PlainText is { Length: > 0 } plain)
{
var (column, row) = TextPlacement.Alignment(entity.Kind, g);
shapes.Add(new SvgText(
g[0] * scale,
-g[1] * scale,
g[3] * scale,
g[4],
plain,
column,
row,
entity.EffectiveColorIndex,
entity.EffectiveTrueColorRgb));
}

break;
}
}
Expand Down Expand Up @@ -411,6 +482,12 @@ private static (double MinX, double MinY, double Width, double Height) ViewBox(L
case SvgPoint point:
Expand(point.X, point.Y);
break;
case SvgText label:
var textBounds = TextPlacement.EstimateBounds(
label.X, label.Y, label.Height, label.RotationRad, label.Text, label.Column, label.Row);
Expand(textBounds.MinX, textBounds.MinY);
Expand(textBounds.MaxX, textBounds.MaxY);
break;
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/DwgIO.Scene/DwgIO.Scene.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
<ItemGroup Condition="'$(BuildNativeCoreOnly)' != 'true'">
<PackageReference Include="IOScene.Formats" />
<PackageReference Include="IOViewer" />
<Compile Include="..\Shared\AtomicOutput.cs;..\Shared\ArcAngles.cs;..\Shared\DwgAciPalette.cs;..\Shared\EllipseAxes.cs"
<Compile Include="..\Shared\AtomicOutput.cs;..\Shared\ArcAngles.cs;..\Shared\DwgAciPalette.cs;..\Shared\EllipseAxes.cs;..\Shared\TextPlacement.cs"
Link="Compatibility\%(Filename)%(Extension)" />
</ItemGroup>

Expand Down
2 changes: 1 addition & 1 deletion src/DwgIO/DwgDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -727,7 +727,7 @@ private List<DwgEntity> ReadOptionalEntities(

try
{
if (EntityDecoder.Decode(info, _objectStreamBytes, year, isEntity, layersByHandle) is { } entity)
if (EntityDecoder.Decode(info, _objectStreamBytes, year, isEntity, layersByHandle, FileHeader.Codepage) is { } entity)
{
entities.Add(entity);
}
Expand Down
Loading
Loading