diff --git a/CHANGELOG.md b/CHANGELOG.md index 9aa82f2..03a6c00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/docs/public-api.md b/docs/public-api.md index 9ef0b92..9031880 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -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. | diff --git a/docs/test-fixtures.md b/docs/test-fixtures.md index c91303a..7e9c805 100644 --- a/docs/test-fixtures.md +++ b/docs/test-fixtures.md @@ -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. @@ -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. diff --git a/src/DwgIO.Cli/DwgIO.Cli.csproj b/src/DwgIO.Cli/DwgIO.Cli.csproj index 4f23f78..23576bf 100644 --- a/src/DwgIO.Cli/DwgIO.Cli.csproj +++ b/src/DwgIO.Cli/DwgIO.Cli.csproj @@ -17,7 +17,7 @@ - diff --git a/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs b/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs index 4f9d119..332423c 100644 --- a/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs +++ b/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs @@ -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; } @@ -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); @@ -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; @@ -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; } @@ -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(); } } @@ -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; @@ -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 = ''; @@ -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'); diff --git a/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs b/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs index d7fe969..3a35be3 100644 --- a/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs +++ b/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs @@ -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; } @@ -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 Collect(DwgDocument document, DwgSvgOptions options) { double scale = options.Scale; @@ -245,6 +299,23 @@ private static List 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; } } @@ -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; } } diff --git a/src/DwgIO.Scene/DwgIO.Scene.csproj b/src/DwgIO.Scene/DwgIO.Scene.csproj index c130957..6a9cc65 100644 --- a/src/DwgIO.Scene/DwgIO.Scene.csproj +++ b/src/DwgIO.Scene/DwgIO.Scene.csproj @@ -23,7 +23,7 @@ - diff --git a/src/DwgIO/DwgDocument.cs b/src/DwgIO/DwgDocument.cs index f879d6e..b696a4c 100644 --- a/src/DwgIO/DwgDocument.cs +++ b/src/DwgIO/DwgDocument.cs @@ -727,7 +727,7 @@ private List 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); } diff --git a/src/DwgIO/Internal/Parsing/EntityDecoder.cs b/src/DwgIO/Internal/Parsing/EntityDecoder.cs index f1c6b4a..d22706e 100644 --- a/src/DwgIO/Internal/Parsing/EntityDecoder.cs +++ b/src/DwgIO/Internal/Parsing/EntityDecoder.cs @@ -27,7 +27,8 @@ internal static class EntityDecoder byte[] stream, int year, bool forceEntity = false, - IReadOnlyDictionary? layersByHandle = null) + IReadOnlyDictionary? layersByHandle = null, + ushort codepage = 30) { if (!forceEntity && !IsEntityCode(info.TypeCode)) { @@ -75,14 +76,18 @@ internal static class EntityDecoder reader.ReadPackedInt(); // transparency } + RecordStringStream? strings = null; + RecordStringStream GetStrings() => + strings ??= RecordStringStream.Open(info, stream, year, codepage, handleStreamBits, reader.PositionBit, info.TypeName); + if ((colorFlags & 0x41) == 0x41) { - SkipText(reader, year); + _ = GetStrings().Read(reader, info.TypeName, year); } if ((colorFlags & 0x42) == 0x42) { - SkipText(reader, year); + _ = GetStrings().Read(reader, info.TypeName, year); } double lineTypeScale = reader.ReadPackedDouble(); @@ -100,17 +105,19 @@ internal static class EntityDecoder reader.ReadPackedShort(); // invisibility reader.ReadRawByte(); // lineweight (R2000+) - (DwgEntityKind kind, double[]? geometry)? body = info.TypeCode switch + (DwgEntityKind kind, double[]? geometry, string? text)? body = info.TypeCode switch { - 0x11 => DecodeArc(reader), - 0x12 => DecodeCircle(reader), - 0x13 => DecodeLine(reader), - 0x1B => DecodePoint(reader), - 0x1C => DecodeFace3d(reader), - 0x1F or 0x20 => DecodeSolidOrTrace(reader), - 0x23 => DecodeEllipse(reader), - 0x28 or 0x29 => DecodeRayOrXLine(reader, info.TypeCode == 0x28 ? DwgEntityKind.Ray : DwgEntityKind.XLine), - 0x4D => DecodeLwPolyline(reader, year), + 0x01 => DecodeText(reader, GetStrings(), year), + 0x11 => WithNoText(DecodeArc(reader)), + 0x12 => WithNoText(DecodeCircle(reader)), + 0x13 => WithNoText(DecodeLine(reader)), + 0x1B => WithNoText(DecodePoint(reader)), + 0x1C => WithNoText(DecodeFace3d(reader)), + 0x1F or 0x20 => WithNoText(DecodeSolidOrTrace(reader)), + 0x23 => WithNoText(DecodeEllipse(reader)), + 0x28 or 0x29 => WithNoText(DecodeRayOrXLine(reader, info.TypeCode == 0x28 ? DwgEntityKind.Ray : DwgEntityKind.XLine)), + 0x2C => DecodeMText(reader, GetStrings(), year), + 0x4D => WithNoText(DecodeLwPolyline(reader, year)), _ => null, }; @@ -134,6 +141,7 @@ internal static class EntityDecoder TypeName = info.TypeName, Kind = body?.kind ?? DwgEntityKind.Unknown, Geometry = body?.geometry, + Text = body?.text, ColorIndex = colorIndex, TrueColorRgb = trueColorRgb, LineTypeScale = lineTypeScale, @@ -145,6 +153,9 @@ internal static class EntityDecoder }; } + private static (DwgEntityKind kind, double[]? geometry, string? text) WithNoText((DwgEntityKind kind, double[] geometry) item) => + (item.kind, item.geometry, null); + private static ulong? TryReadLayerHandle( BitReaderMsb reader, DwgObjectInfo info, @@ -241,17 +252,90 @@ internal static void SkipExtendedData(BitReaderMsb reader) throw new DwgException("Extended data loop exceeded 256 iterations; payload is malformed."); } - private static void SkipText(BitReaderMsb reader, int year) + private static (DwgEntityKind, double[], string) DecodeText(BitReaderMsb reader, RecordStringStream strings, int year) + { + byte dataFlags = reader.ReadRawByte(); + double elevation = (dataFlags & 0x01) == 0 ? reader.ReadRawDouble() : 0.0; + double insX = reader.ReadRawDouble(); + double insY = reader.ReadRawDouble(); + bool hasAlign = (dataFlags & 0x02) == 0; + double alignX = hasAlign ? reader.ReadDoubleWithDefault(insX) : insX; + double alignY = hasAlign ? reader.ReadDoubleWithDefault(insY) : insY; + + _ = ReadExtrusion(reader); + _ = ReadThickness(reader); + double oblique = (dataFlags & 0x04) == 0 ? reader.ReadRawDouble() : 0.0; + double rotation = (dataFlags & 0x08) == 0 ? reader.ReadRawDouble() : 0.0; + double height = reader.ReadRawDouble(); + double widthFactor = (dataFlags & 0x10) == 0 ? reader.ReadRawDouble() : 1.0; + + string text = strings.Read(reader, "TEXT", year); + + if ((dataFlags & 0x20) == 0) + { + _ = reader.ReadPackedShort(); // generation + } + + short horizAlign = (dataFlags & 0x40) == 0 ? (short)reader.ReadPackedShort() : (short)0; + short vertAlign = (dataFlags & 0x80) == 0 ? (short)reader.ReadPackedShort() : (short)0; + + // When alignment is specified (neither Left/Baseline nor Aligned/Fit), AutoCAD anchors at alignmentPt. + bool useAlign = hasAlign && (horizAlign != 0 || vertAlign != 0) && horizAlign is not (3 or 5); + double x = useAlign ? alignX : insX; + double y = useAlign ? alignY : insY; + + return (DwgEntityKind.Text, [x, y, elevation, height, rotation, widthFactor, oblique, horizAlign, vertAlign], text); + } + + private static (DwgEntityKind, double[], string) DecodeMText(BitReaderMsb reader, RecordStringStream strings, int year) { - int length = (int)reader.ReadPackedShort(); + double x = reader.ReadPackedDouble(); + double y = reader.ReadPackedDouble(); + double z = reader.ReadPackedDouble(); + + _ = reader.ReadPackedDouble(); + _ = reader.ReadPackedDouble(); + _ = reader.ReadPackedDouble(); // 3BD extrusion + + double xAxisX = reader.ReadPackedDouble(); + double xAxisY = reader.ReadPackedDouble(); + _ = reader.ReadPackedDouble(); // 3BD XAxisDir + + double rectWidth = reader.ReadPackedDouble(); if (year >= 2007) { - reader.SkipBytes(length * 2); + _ = reader.ReadPackedDouble(); // RectHeight } - else + + double textHeight = reader.ReadPackedDouble(); + uint attachment = reader.ReadPackedShort(); + _ = reader.ReadPackedShort(); // DrawingDir + _ = reader.ReadPackedDouble(); // ExtentsHeight + _ = reader.ReadPackedDouble(); // ExtentsWidth + + string text = strings.Read(reader, "MTEXT", year); + + _ = reader.ReadPackedShort(); // LinespacingStyle + _ = reader.ReadPackedDouble(); // LinespacingFactor + _ = reader.ReadBit(); // Unknown + if (year >= 2004) { - reader.SkipBytes(length); + uint bgFlags = reader.ReadPackedInt(); + if ((bgFlags & 0x01) != 0) + { + _ = reader.ReadPackedDouble(); // BackgroundScaleFactor + _ = reader.ReadPackedShort(); + _ = reader.ReadPackedInt(); + _ = reader.ReadRawByte(); + if ((bgFlags & 0x02) == 0) + { + _ = reader.ReadPackedInt(); + } + } } + + double rotation = Math.Atan2(xAxisY, xAxisX); + return (DwgEntityKind.MText, [x, y, z, textHeight, rotation, rectWidth, attachment], text); } private static double ReadThickness(BitReaderMsb reader) => reader.ReadBit() ? 0.0 : reader.ReadPackedDouble(); diff --git a/src/DwgIO/Internal/Parsing/LayerParser.cs b/src/DwgIO/Internal/Parsing/LayerParser.cs index ac8cf09..63a558f 100644 --- a/src/DwgIO/Internal/Parsing/LayerParser.cs +++ b/src/DwgIO/Internal/Parsing/LayerParser.cs @@ -1,4 +1,3 @@ -using System.Text; using DwgIO.Internal.Container; using DwgIO.Model; @@ -33,41 +32,8 @@ public static DwgLayerInfo Parse(DwgObjectInfo info, byte[] stream, int year, us _ = reader.ReadBit(); // has AcDs binary data } - Encoding encoding = MetadataByteCursor.GetEncoding(codepage); - BitReaderMsb? stringReader = null; - int stringEndBit = 0; - if (year >= 2007) - { - long totalPayloadBits = info.BitsLength * 8L; - if (handleStreamBits > (ulong)totalPayloadBits || totalPayloadBits - (long)handleStreamBits < 17) - { - throw new DwgException($"LAYER {info.Handle:X}: invalid R2007+ string/handle stream framing."); - } - - int dataEndBit = (int)(totalPayloadBits - (long)handleStreamBits); - var tailReader = new BitReaderMsb(stream[info.BitsStart..(info.BitsStart + info.BitsLength)]); - tailReader.SeekBit(dataEndBit - 1); - bool hasStrings = tailReader.ReadBit(); - if (hasStrings) - { - var lenReader = new BitReaderMsb(stream[info.BitsStart..(info.BitsStart + info.BitsLength)]); - lenReader.SeekBit(dataEndBit - 17); - int stringBits = lenReader.ReadRawByte() | (lenReader.ReadRawByte() << 8); - int stringStart = dataEndBit - 17 - stringBits; - if (stringStart < reader.PositionBit) - { - throw new DwgException($"LAYER {info.Handle:X}: string stream start {stringStart} overlaps data bits."); - } - - stringEndBit = dataEndBit - 17; - stringReader = new BitReaderMsb(stream[info.BitsStart..(info.BitsStart + info.BitsLength)]); - stringReader.SeekBit(stringStart); - } - } - - string name = stringReader is not null - ? (stringReader.PositionBit < stringEndBit ? stringReader.ReadUtf16String("LAYER") : string.Empty) - : reader.ReadCodepageString(encoding, "LAYER"); + var strings = RecordStringStream.Open(info, stream, year, codepage, handleStreamBits, reader.PositionBit, "LAYER"); + string name = strings.Read(reader, "LAYER", year); bool hasNoXrefIndex = reader.ReadBit(); // 64-flag if (!hasNoXrefIndex) @@ -121,16 +87,12 @@ public static DwgLayerInfo Parse(DwgObjectInfo info, byte[] stream, int year, us byte colorFlags = reader.ReadRawByte(); if ((colorFlags & 1) != 0) { - _ = stringReader is not null - ? (stringReader.PositionBit < stringEndBit ? stringReader.ReadUtf16String("LAYER") : string.Empty) - : reader.ReadCodepageString(encoding, "LAYER"); + _ = strings.Read(reader, "LAYER", year); } if ((colorFlags & 2) != 0) { - _ = stringReader is not null - ? (stringReader.PositionBit < stringEndBit ? stringReader.ReadUtf16String("LAYER") : string.Empty) - : reader.ReadCodepageString(encoding, "LAYER"); + _ = strings.Read(reader, "LAYER", year); } } diff --git a/src/DwgIO/Internal/Parsing/RecordStringStream.cs b/src/DwgIO/Internal/Parsing/RecordStringStream.cs new file mode 100644 index 0000000..55e83af --- /dev/null +++ b/src/DwgIO/Internal/Parsing/RecordStringStream.cs @@ -0,0 +1,82 @@ +using System.Text; +using DwgIO.Internal.Container; +using DwgIO.Model; + +namespace DwgIO.Internal.Parsing; + +/// +/// Reads inline codepage strings (R2004) or separate UTF-16LE string-stream strings (R2007+) +/// from an AcDb:AcDbObjects record. +/// +internal sealed class RecordStringStream +{ + private readonly BitReaderMsb? _stringReader; + private readonly int _stringEndBit; + private readonly Encoding _encoding; + + private RecordStringStream(BitReaderMsb? stringReader, int stringEndBit, Encoding encoding) + { + _stringReader = stringReader; + _stringEndBit = stringEndBit; + _encoding = encoding; + } + + public static RecordStringStream Open( + DwgObjectInfo info, + byte[] stream, + int year, + ushort codepage, + ulong handleStreamBits, + int minDataBit, + string recordLabel) + { + Encoding encoding = MetadataByteCursor.GetEncoding(codepage); + if (year < 2007) + { + return new RecordStringStream(null, 0, encoding); + } + + long totalPayloadBits = info.BitsLength * 8L; + if (handleStreamBits > (ulong)totalPayloadBits || totalPayloadBits - (long)handleStreamBits < 17) + { + throw new DwgException($"{recordLabel} {info.Handle:X}: invalid R2007+ string/handle stream framing."); + } + + int dataEndBit = (int)(totalPayloadBits - (long)handleStreamBits); + var slice = stream[info.BitsStart..(info.BitsStart + info.BitsLength)]; + var tailReader = new BitReaderMsb(slice); + tailReader.SeekBit(dataEndBit - 1); + if (!tailReader.ReadBit()) + { + return new RecordStringStream(null, 0, encoding); + } + + var lenReader = new BitReaderMsb(slice); + lenReader.SeekBit(dataEndBit - 17); + int stringBits = lenReader.ReadRawByte() | (lenReader.ReadRawByte() << 8); + int stringStart = dataEndBit - 17 - stringBits; + if (stringStart < minDataBit) + { + throw new DwgException($"{recordLabel} {info.Handle:X}: string stream start {stringStart} overlaps data bits."); + } + + var stringReader = new BitReaderMsb(slice); + stringReader.SeekBit(stringStart); + return new RecordStringStream(stringReader, dataEndBit - 17, encoding); + } + + public string Read(BitReaderMsb dataReader, string context, int year) + { + if (year >= 2007) + { + if (_stringReader is null || _stringReader.PositionBit >= _stringEndBit) + { + return string.Empty; + } + + return _stringReader.ReadUtf16String(context); + } + + return dataReader.ReadCodepageString(_encoding, context); + } +} diff --git a/src/DwgIO/Json/DwgJsonExporter.cs b/src/DwgIO/Json/DwgJsonExporter.cs index 2c94a25..26490ec 100644 --- a/src/DwgIO/Json/DwgJsonExporter.cs +++ b/src/DwgIO/Json/DwgJsonExporter.cs @@ -320,6 +320,15 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio writer.WriteNumber("effectiveColorIndex", resolvedColor); } + if (entity.Text is { } rawText) + { + writer.WriteString("text", rawText); + if (entity.PlainText is { } plainText && plainText != rawText) + { + writer.WriteString("plainText", plainText); + } + } + writer.WriteEndObject(); } diff --git a/src/DwgIO/Model/DwgEntity.cs b/src/DwgIO/Model/DwgEntity.cs index ad4568d..04202ad 100644 --- a/src/DwgIO/Model/DwgEntity.cs +++ b/src/DwgIO/Model/DwgEntity.cs @@ -37,6 +37,12 @@ public enum DwgEntityKind /// XLINE: infinite construction line (base point + unit direction). XLine, + + /// TEXT: single-line text annotation (position, height, rotation, width factor, oblique). + Text, + + /// MTEXT: multiline text annotation (position, height, rotation, reference width, attachment). + MText, } /// @@ -68,6 +74,8 @@ public sealed class DwgEntity /// : [cx, cy, cz, mx, my, mz, ratio, startRad, endRad, nx, ny, nz] /// / : [x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4] /// / : [x, y, z, dx, dy, dz] + /// : [x, y, elevation, height, rotationRad, widthFactor, obliqueRad, horizontalAlignment, verticalAlignment] + /// : [x, y, z, height, rotationRad, rectWidth, attachment] /// /// Null for non-decoded kinds. /// @@ -104,6 +112,12 @@ public sealed class DwgEntity /// Effective 24-bit true colour: uses entity true colour, else resolves BYLAYER (256) to . public uint? EffectiveTrueColorRgb => TrueColorRgb ?? (ColorIndex == 256 ? LayerTrueColorRgb : null); + /// Raw text payload for and entities. + public string? Text { get; init; } + + /// Human-readable text for and with MTEXT inline formatting stripped. + public string? PlainText => Text is null ? null : (Kind == DwgEntityKind.MText ? StripMTextFormatting(Text) : Text); + /// One-line description: type, handle and decoded geometry. public override string ToString() => Kind switch @@ -126,6 +140,92 @@ public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"3DFACE {Handle:X}: ({g[0]:F3},{g[1]:F3},{g[2]:F3}) .. ({g[9]:F3},{g[10]:F3},{g[11]:F3})"), DwgEntityKind.Ray or DwgEntityKind.XLine when Geometry is { Length: 6 } g => string.Create(CultureInfo.InvariantCulture, $"{TypeName} {Handle:X}: p=({g[0]:F3},{g[1]:F3},{g[2]:F3}) d=({g[3]:F3},{g[4]:F3},{g[5]:F3})"), + DwgEntityKind.Text or DwgEntityKind.MText when Geometry is { Length: >= 4 } g => + string.Create(CultureInfo.InvariantCulture, $"{TypeName} {Handle:X}: ({g[0]:F3},{g[1]:F3},{g[2]:F3}) h={g[3]:F3} \"{PlainText}\""), _ => $"{TypeName} {Handle:X}", }; + + private static string StripMTextFormatting(string raw) + { + if (raw.IndexOf('\\') < 0 && raw.IndexOf('{') < 0 && raw.IndexOf('}') < 0) + { + return raw; + } + + var sb = new System.Text.StringBuilder(raw.Length); + for (int i = 0; i < raw.Length; i++) + { + char c = raw[i]; + if (c is '{' or '}') + { + continue; + } + + if (c != '\\' || i + 1 >= raw.Length) + { + sb.Append(c); + continue; + } + + char next = raw[i + 1]; + switch (next) + { + case 'P': + case 'p': + sb.Append('\n'); + i++; + break; + case '~': + sb.Append(' '); + i++; + break; + case '\\': + case '{': + case '}': + sb.Append(next); + i++; + break; + case 'L': + case 'l': + case 'O': + case 'o': + case 'K': + case 'k': + i++; + break; + case 'S': + case 's': + { + int semi = raw.IndexOf(';', i + 2); + if (semi > i + 2) + { + sb.Append(raw.AsSpan(i + 2, semi - i - 2).ToString().Replace('^', '/')); + i = semi; + } + else + { + i++; + } + + break; + } + default: + { + int semi = raw.IndexOf(';', i + 2); + if (semi > i + 1 && semi - i <= 128) + { + i = semi; + } + else + { + i++; + } + + break; + } + } + } + + return sb.ToString(); + } } diff --git a/src/Shared/TextPlacement.cs b/src/Shared/TextPlacement.cs new file mode 100644 index 0000000..043d149 --- /dev/null +++ b/src/Shared/TextPlacement.cs @@ -0,0 +1,42 @@ +using DwgIO.Model; + +namespace DwgIO.Scene; + +internal static class TextPlacement +{ + // Columns run left to right, rows run top to bottom. Row -1 is the text baseline. + public static (int Column, int Row) Alignment(DwgEntityKind kind, double[] geometry) + { + if (kind == DwgEntityKind.MText && geometry.Length >= 7 && geometry[6] is >= 1 and <= 9) + { + int attachment = (int)geometry[6] - 1; + return (attachment % 3, attachment / 3); + } + + if (kind != DwgEntityKind.Text || geometry.Length < 9) + { + return (0, kind == DwgEntityKind.MText ? 0 : -1); + } + + int column = geometry[7] switch { 1 or 4 => 1, 2 => 2, _ => 0 }; + int row = geometry[8] switch { 1 => 2, 2 => 1, 3 => 0, _ => geometry[7] == 4 ? 1 : -1 }; + return (column, row); + } + + public static (double MinX, double MinY, double MaxX, double MaxY) EstimateBounds( + double x, double y, double height, double rotation, string text, int column, int row) + { + string[] lines = text.Split('\n'); + double width = height * Math.Max(1, lines.Max(line => line.Length)) * 0.6; + double blockHeight = height * (1 + 1.25 * (lines.Length - 1)); + double left = -width * column / 2; + double top = row < 0 ? -height : -blockHeight * row / 2; + double cos = Math.Cos(rotation), sin = Math.Sin(rotation); + double centerX = left + width / 2, centerY = top + blockHeight / 2; + double projectedX = x + centerX * cos + centerY * sin; + double projectedY = y - centerX * sin + centerY * cos; + double halfWidth = (width * Math.Abs(cos) + blockHeight * Math.Abs(sin)) / 2; + double halfHeight = (width * Math.Abs(sin) + blockHeight * Math.Abs(cos)) / 2; + return (projectedX - halfWidth, projectedY - halfHeight, projectedX + halfWidth, projectedY + halfHeight); + } +} diff --git a/test-files/public/README.md b/test-files/public/README.md index 5234741..6da53ec 100644 --- a/test-files/public/README.md +++ b/test-files/public/README.md @@ -57,6 +57,26 @@ above identify the committed drawings, not all equivalent regenerations. Validat geometry with DwgIO before replacing a file, then update the recorded hash. These fixtures exercise the independent writer's output, not every DWG writer or entity kind. +### Right-aligned TEXT + +`text-aligned-ac1032.dwg` is an original MIT-licensed drawing created for the TEXT alignment regression test +with the same ACadSharp 3.8.35 writer. Its SHA-256 is +`e1ffab79f12b9eee13047be11ca02d42675ab78c7859af267dda0861b633690d`. +It contains one model-space TEXT on layer `0`, with insertion point (1, 2, 0), alignment point (20, 10, 0), +height 2 and right alignment. To regenerate it with the console project above, replace the primitive loop with: + +```csharp +var drawing = new CadDocument(ACadVersion.AC1032); +drawing.Entities.Add(new TextEntity("Right aligned") +{ + InsertPoint = new XYZ(1, 2, 0), + AlignmentPoint = new XYZ(20, 10, 0), + Height = 2, + HorizontalAlignment = TextHorizontalAlignment.Right, +}); +DwgWriter.Write("text-aligned-ac1032.dwg", drawing); +``` + ## How a drawing qualifies Before committing a file, record here, next to the file name: @@ -73,6 +93,5 @@ see `docs/test-fixtures.md`) remains the place for larger local test sets. For optional fixture checks, `TestFiles` looks in `DWGIO_TEST_FILES`, ancestor `test_files` and `test-files/public` folders, and one level of subfolders. Unsupported versions are skipped and counted; -checks with no eligible drawing are skipped. The required `PublicDrawing_DecodesAuthoredPrimitives` theory -instead reads the three committed files copied into the test output at build time. A missing copy fails -that theory even when no private drawings are configured. +checks with no eligible drawing are skipped. The required public fixture tests read the files copied into +the test output at build time. A missing copy fails its test even when no private drawings are configured. diff --git a/test-files/public/text-aligned-ac1032.dwg b/test-files/public/text-aligned-ac1032.dwg new file mode 100644 index 0000000..3d139dd Binary files /dev/null and b/test-files/public/text-aligned-ac1032.dwg differ diff --git a/tests/DwgIO.Tests/DwgIO.Tests.csproj b/tests/DwgIO.Tests/DwgIO.Tests.csproj index 2335e61..23235c6 100644 --- a/tests/DwgIO.Tests/DwgIO.Tests.csproj +++ b/tests/DwgIO.Tests/DwgIO.Tests.csproj @@ -18,7 +18,7 @@ - diff --git a/tests/DwgIO.Tests/TextEntitiesTests.cs b/tests/DwgIO.Tests/TextEntitiesTests.cs new file mode 100644 index 0000000..f170ef4 --- /dev/null +++ b/tests/DwgIO.Tests/TextEntitiesTests.cs @@ -0,0 +1,410 @@ +using System.Text; +using System.Text.Json; +using System.Xml.Linq; +using DwgIO.Export; +using DwgIO.Internal.Parsing; +using DwgIO.Model; +using DwgIO.Scene; +using Xunit; + +namespace DwgIO.Tests; + +public class TextEntitiesTests +{ + [Fact] + public void DecodeText_R2018AndR2004_ExtractsPositionHeightRotationAndString() + { + byte[] stream2018 = BuildSyntheticTextStream( + r2010Plus: true, + handle: 0x50, + insX: 12.5, + insY: 25.0, + elevation: 3.0, + rotationRad: Math.PI / 4, + height: 2.5, + widthFactor: 0.85, + obliqueRad: 0.1, + textValue: "Level 1 Plan", + layerHandle: 0x3C); + + var layer = new DwgLayerInfo { Handle = 0x3C, Name = "Annotations", ColorIndex = 3 }; + var layers = new Dictionary { [0x3C] = layer }; + var info = new DwgObjectInfo + { + StreamOffset = 0, + SizeBytes = (uint)stream2018.Length, + TypeCode = 0x01, + Handle = 0x50, + StreamHandle = new DwgHandle(0, 1, 0x50), + BitsStart = 0, + BitsLength = stream2018.Length, + }; + + var entity = EntityDecoder.Decode(info, stream2018, year: 2018, layersByHandle: layers); + Assert.NotNull(entity); + Assert.Equal(DwgEntityKind.Text, entity!.Kind); + Assert.Equal("Level 1 Plan", entity.Text); + Assert.Equal("Level 1 Plan", entity.PlainText); + Assert.Equal("Annotations", entity.LayerName); + Assert.NotNull(entity.Geometry); + Assert.Equal([12.5, 25.0, 3.0, 2.5, Math.PI / 4, 0.85, 0.1, 0.0, 0.0], entity.Geometry!); + Assert.Contains("Level 1 Plan", entity.ToString(), StringComparison.Ordinal); + + // Alignment anchor test in R2004 inline mode (DataFlags omits elevation/oblique/rotation, sets HorizAlign=1 -> uses AlignPt). + byte[] stream2004 = BuildSyntheticAlignedR2004TextStream( + handle: 0x51, + insX: 0, + insY: 0, + alignX: 40.0, + alignY: 50.0, + height: 4.0, + horizAlign: 1, + textValue: "Centered"); + var info2004 = new DwgObjectInfo + { + StreamOffset = 0, + SizeBytes = (uint)stream2004.Length, + TypeCode = 0x01, + Handle = 0x51, + StreamHandle = new DwgHandle(0, 1, 0x51), + BitsStart = 0, + BitsLength = stream2004.Length, + }; + + var aligned = EntityDecoder.Decode(info2004, stream2004, year: 2004); + Assert.NotNull(aligned); + Assert.Equal(DwgEntityKind.Text, aligned!.Kind); + Assert.Equal("Centered", aligned.Text); + Assert.Equal(40.0, aligned.Geometry![0]); + Assert.Equal(50.0, aligned.Geometry![1]); + Assert.Equal(4.0, aligned.Geometry![3]); + } + + [Fact] + public void PublicDrawing_RightAlignedTextPreservesItsAnchorInSvgAndHtml() + { + var document = DwgDocument.Open(TestFiles.PublicDrawing("text-aligned-ac1032.dwg")); + var text = Assert.Single(document.Entities, entity => entity.Kind == DwgEntityKind.Text); + Assert.Equal("Right aligned", text.PlainText); + Assert.Equal([20.0, 10.0, 0.0, 2.0, 0.0, 1.0, 0.0, 2.0, 0.0], text.Geometry!); + + using var svg = new MemoryStream(); + DwgSvgExporter.Write(document, svg); + svg.Position = 0; + var label = Assert.Single(XDocument.Load(svg).Descendants(XName.Get("text", "http://www.w3.org/2000/svg"))); + Assert.Equal("20", (string?)label.Attribute("x")); + Assert.Equal("-10", (string?)label.Attribute("y")); + Assert.Equal("2", (string?)label.Attribute("font-size")); + Assert.Equal("end", (string?)label.Attribute("text-anchor")); + + using var html = new MemoryStream(); + DwgCadHtmlViewer.Export(document, html, new DwgViewerOptions(), "m"); + string content = Encoding.UTF8.GetString(html.ToArray()); + Assert.Contains("\"text\":\"Right aligned\",\"textColumn\":2", content, StringComparison.Ordinal); + } + + [Fact] + public void DecodeMText_R2018_StripsFormattingAndExportsJsonSvgAndHtml() + { + const string formatted = @"{\fArial|b0|i0;Room 101\P\C1;Area 42\~m\S1^2;}"; + byte[] stream = BuildSyntheticMTextStream( + handle: 0x60, + x: 10.0, + y: 20.0, + z: 0.0, + xAxisX: 0.0, + xAxisY: 1.0, // rotated 90 deg CCW + rectWidth: 30.0, + textHeight: 2.0, + attachment: 5, + textValue: formatted); + + var info = new DwgObjectInfo + { + StreamOffset = 0, + SizeBytes = (uint)stream.Length, + TypeCode = 0x2C, + Handle = 0x60, + StreamHandle = new DwgHandle(0, 1, 0x60), + BitsStart = 0, + BitsLength = stream.Length, + }; + + var mtext = EntityDecoder.Decode(info, stream, year: 2018); + Assert.NotNull(mtext); + Assert.Equal(DwgEntityKind.MText, mtext!.Kind); + Assert.Equal(formatted, mtext.Text); + Assert.Equal("Room 101\nArea 42 m1/2", mtext.PlainText); + Assert.Equal(10.0, mtext.Geometry![0]); + Assert.Equal(20.0, mtext.Geometry![1]); + Assert.Equal(2.0, mtext.Geometry![3]); + Assert.Equal(Math.PI / 2, mtext.Geometry![4], 9); + Assert.Equal(30.0, mtext.Geometry![5]); + Assert.Equal(5.0, mtext.Geometry![6]); + + var doc = new DwgDocument( + "text.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1032", + Release = "R2018", + Family = DwgContainerFamily.R2004Family, + Year = 2018, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + [mtext]); + + using var jsonDoc = JsonDocument.Parse(doc.ToJson()); + var entJson = jsonDoc.RootElement.GetProperty("entities")[0]; + Assert.Equal(formatted, entJson.GetProperty("text").GetString()); + Assert.Equal("Room 101\nArea 42 m1/2", entJson.GetProperty("plainText").GetString()); + + using var svgStream = new MemoryStream(); + DwgSvgExporter.Write(doc, svgStream); + string svg = Encoding.UTF8.GetString(svgStream.ToArray()); + Assert.Contains("= 2010) + { + w.WriteTwoBits(0); + w.WriteRawByte((byte)typeCode); + } + else + { + WritePackedShort(w, typeCode); + } + + w.WriteRawByte(0x01); // handle code 0, cnt 1 + w.WriteRawByte((byte)handle); + w.WriteTwoBits(2); // XDATA end + w.WriteBit(false); // no graphics preview + w.WriteTwoBits(isModelSpace ? 2u : 1u); // entity mode + w.WriteTwoBits(2); // reactor count = 0 + w.WriteBit(true); // no extension dictionary + if (year >= 2013) + { + w.WriteBit(false); // hasAcDs + } + + w.WriteTwoBits(2); // color index = 0 (BYBLOCK) + w.WriteTwoBits(1); // linetype scale = 1.0 + w.WriteTwoBits(0); // linetype flags + w.WriteTwoBits(0); // plotstyle flags + w.WriteTwoBits(0); // material flags + w.WriteRawByte(0); // shadow flags + if (year >= 2010) + { + w.WriteBit(false); + w.WriteBit(false); + w.WriteBit(false); + } + + w.WriteTwoBits(2); // invisibility = 0 + w.WriteRawByte(0); // lineweight + } + + private static byte[] FinalizeR2018Record(RecordBitWriter data, string textValue, ulong layerHandle) + { + var strWriter = new RecordBitWriter(); + byte[] utf16 = Encoding.Unicode.GetBytes(textValue); + WritePackedShort(strWriter, (ushort)textValue.Length); + foreach (byte b in utf16) + { + strWriter.WriteRawByte(b); + } + + int stringBits = strWriter.BitsUsed; + foreach (bool bit in GetBits(strWriter.ToArray(), stringBits)) + { + data.WriteBit(bit); + } + + data.WriteRawByte((byte)(stringBits & 0xFF)); + data.WriteRawByte((byte)(stringBits >> 8)); + data.WriteBit(true); // hasStrings + + int totalBeforeHandles = data.BitsUsed; + data.WriteRawByte(0x51); // Layer handle code 5, cnt 1 + data.WriteRawByte((byte)layerHandle); + int handleBits = (data.BitsUsed - totalBeforeHandles) + ((8 - (data.BitsUsed % 8)) % 8); + + byte[] bodyBytes = data.ToArray(); + byte[] full = new byte[1 + bodyBytes.Length]; + full[0] = (byte)handleBits; + bodyBytes.CopyTo(full, 1); + return full; + } + + private static void WritePackedShort(RecordBitWriter w, ushort value) + { + if (value == 0) + { + w.WriteTwoBits(2); + } + else if (value <= 255) + { + w.WriteTwoBits(1); + w.WriteRawByte((byte)value); + } + else + { + w.WritePackedShortRaw(value); + } + } + + private static void WritePackedDouble(RecordBitWriter w, double value) + { + if (value == 0.0) + { + w.WriteTwoBits(2); + } + else if (value == 1.0) + { + w.WriteTwoBits(1); + } + else + { + w.WriteTwoBits(0); + w.WriteRawDouble(value); + } + } + + private static void WriteAscii(RecordBitWriter w, string value) + { + WritePackedShort(w, (ushort)value.Length); + foreach (byte b in Encoding.ASCII.GetBytes(value)) + { + w.WriteRawByte(b); + } + } + + private static IEnumerable GetBits(byte[] bytes, int bitCount) + { + for (int i = 0; i < bitCount; i++) + { + yield return ((bytes[i >> 3] >> (7 - (i & 7))) & 1) != 0; + } + } +}