From e78b7e59cdfc3f5294e275768d4a38013cf0b088 Mon Sep 17 00:00:00 2001
From: mie <79989386+mahach666@users.noreply.github.com>
Date: Thu, 19 Nov 2026 13:15:04 +0300
Subject: [PATCH] Export curved and multi-segment Revit grids to IOScene
---
CHANGELOG.md | 1 +
Directory.Packages.props | 2 +-
docs/public-api.md | 1 +
docs/scene.md | 8 +-
src/RvtIO.Scene/RvtSceneReader.cs | 34 +++--
src/RvtIO/Internal/ParsingState.cs | 1 +
src/RvtIO/Model/GridAxis.cs | 54 +++++++
src/RvtIO/Model/RevitFileInfo.cs | 3 +
src/RvtIO/Parsing/GridAxisReader.cs | 179 ++++++++++++++++++++++++
src/RvtIO/Parsing/WideBlockWalker.cs | 10 +-
src/RvtIO/RvtDocument.cs | 13 ++
src/RvtIO/RvtFileReader.cs | 57 +++++++-
tests/RvtIO.Tests/SceneGridPathTests.cs | 163 +++++++++++++++++++++
13 files changed, 508 insertions(+), 18 deletions(-)
create mode 100644 src/RvtIO/Model/GridAxis.cs
create mode 100644 src/RvtIO/Parsing/GridAxisReader.cs
create mode 100644 tests/RvtIO.Tests/SceneGridPathTests.cs
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 930a3c9f..9ba67aa4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ API between minor releases.
### Added
- `RvtIO.Scene` exports decoded straight Revit grid axes and their labels in scene coordinates.
+- `RvtIO.Scene` exports circular and multi-segment grid axes as connected paths with one datum label per axis.
- `RvtDocument.GetBuildingStoreyCatalog()` exposes project building storeys and their assignments.
`RvtIO.Scene` writes those levels and the storey of each drawable element using the current IFC rules.
diff --git a/Directory.Packages.props b/Directory.Packages.props
index cdadd7e1..019e9a7c 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -12,7 +12,7 @@
-
+
diff --git a/docs/public-api.md b/docs/public-api.md
index 79c39688..45085f91 100644
--- a/docs/public-api.md
+++ b/docs/public-api.md
@@ -16,6 +16,7 @@ projects through `InternalsVisibleTo`.
| `RvtExitCodes`, `RvtInputException`, `RvtLimitException`, `RvtContainerCheck` | The exit codes 0 to 4 and 6 of the command line tool (code 5 is returned by `downgrade --check` and `save-as` when refused), the exceptions `RvtFileReader.Read` throws for a file it cannot read, and the check that raises them. |
| `FilteredElementCollector` | Query over the elements of a document (`OfCategory`, `WhereElementIsNotElementType`, `Where`, ...). |
| `BuildingStoreyCatalog`, `BuildingStorey` | `RvtDocument.GetBuildingStoreyCatalog()` lists native project building storeys in order of elevation and Revit ID. Each storey carries its ID, name and resolved elevation in internal feet. `GetStoreyId(elementId)` uses the current IFC storey rules and returns null for an unknown element or one assigned to the building itself. Obtain a new catalog after editing levels. |
+| `GridAxis` | `RvtDocument.GetGridAxes()` lists decoded project axes in Revit ID order. A circular or multi-segment axis has ordered analytic segments. `GridAxis.Tessellate(maxErrorFeet)` returns path points in internal feet. |
## Model
diff --git a/docs/scene.md b/docs/scene.md
index 2f247981..1a268cb3 100644
--- a/docs/scene.md
+++ b/docs/scene.md
@@ -2,7 +2,7 @@
`RvtIO.Scene` turns a Revit project read by RvtIO into a scene of the `IOScene` package: a `SceneDocument` with one
model, the drawable elements, their triangle meshes in metres, their names and parameters, the building storeys, and
-the decoded straight grid axes. A viewer or another consumer of the scene reads it without knowing Revit. The scene itself is specified in the contract of the `IOScene`
+the decoded grid axes. A viewer or another consumer of the scene reads it without knowing Revit. The scene itself is specified in the contract of the `IOScene`
repository (`docs/contract.md`), and the property keys it writes are registered there in `docs/keys.md`.
The adapter is a preview. It is published as the package `RvtIO.Scene` on each RvtIO release tag, depends on exactly
@@ -53,7 +53,8 @@ rvtio project.rvt --ifc project.ifc --compact-json project.compact.json --scene
|---|---|
| `SceneModel.Key` | `RvtSceneOptions.ModelKey`, else the file name without its directory (`project.rvt`). This derivation does not change. |
| `SceneModel` | `SourceFormat` `rvt`, `SourceLengthUnit` `ft`, `Producer` `RvtIO.Scene `. |
-| `SceneGridSystem`, `SceneGridLine` | One grid system named `Grids` when the model has valid straight grid axes. Each axis uses its element name and the endpoints of its decoded location curve, converted from feet to metres in the document's internal coordinates. Elevation is the start point's Z. |
+| `SceneGridSystem`, `SceneGridLine` | One grid system named `Grids` when the model has decoded axes. Standalone straight axes use the element name and endpoints of the location curve, converted from feet to metres in the document's internal coordinates. Elevation is the start point's Z. |
+| `SceneGridPath` | One path and datum label per standalone circular arc or complete multi-segment grid. Points follow the stored segment order at model Z=0, as in Revit's grid curves. Arcs are sampled with at most 1 mm of chord error. Viewers place the label only at the two outer endpoints. |
| `SceneLevel` | Project levels marked as building storeys, ordered by elevation and Revit element ID. Names and resolved elevations, including elevations inferred by the reader, use the same level selection as IFC. Elevations are written in metres. |
| `SceneElement.LevelId` | The building-storey assignment from `RvtDocument.GetBuildingStoreyCatalog()`, using the current IFC rules for stored level references and geometry fallback. Assignments to the building itself leave this field empty. The scene assigns a storey to each drawable element independently of IFC product aggregation. |
| `SceneElement` | One per drawable element of `ElementMeshes.Extract` (the elements the IFC export would consider products, see the remarks of `ElementMeshes`). `Id` is the element id. |
@@ -100,7 +101,8 @@ The text a value is written with under a key is frozen with the key: changing it
(numbers in SI units, booleans, element references) wait for public RvtIO API.
- Shared, project and family parameters have no key yet. Their formats (for example `revit:shared:`) are
registered in the IOScene key registry when the adapter first writes them; that is an addition.
-- Every element is a top-level element of its model. Linked models, views and curved grid axes are omitted.
+- Every element is a top-level element of its model. Linked models and views are omitted.
+- The grid path reader accepts vertical cylindrical grid surfaces and complete, connected chains of straight and circular segments. It omits unsupported surfaces, incomplete chains and paths requiring more than 65,536 vertices at the documented tolerance.
- Materials have a name and a colour; no roughness, metalness or textures.
- Element names are those of `RvtDocument`; the validated names the IFC export applies to files read by their own class
schema are not public API.
diff --git a/src/RvtIO.Scene/RvtSceneReader.cs b/src/RvtIO.Scene/RvtSceneReader.cs
index ed8b8186..f2a35bfd 100644
--- a/src/RvtIO.Scene/RvtSceneReader.cs
+++ b/src/RvtIO.Scene/RvtSceneReader.cs
@@ -10,7 +10,7 @@ namespace RvtIO.Scene;
///
/// Turns a Revit document into a scene (): one model, one element per drawable element of the document
-/// with its triangle meshes (), its names and its parameters, plus building storeys and decoded straight grid axes.
+/// with its triangle meshes (), its names and its parameters, plus building storeys and decoded grid axes.
///
///
/// Lengths are converted from feet to metres (x 0.3048) into the internal coordinates of the document, Z up. A symbol that
@@ -230,22 +230,34 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m
private static void AddGrids(SceneDocument scene, RvtDocument document)
{
+ const double GridChordErrorMetres = 0.001;
var grid = new SceneGridSystem { ModelId = ModelId };
- foreach (var element in document.Collector().OfCategory(BuiltInCategory.OST_Grids)
- .WhereElementIsNotElementType().OrderBy(element => element.Id))
+ foreach (var axis in document.GetGridAxes())
{
- if (element.Location is not { CurveType: "Line", StartPoint: [var x0, var y0, var z0], EndPoint: [var x1, var y1, var z1] }
- || !double.IsFinite(x0) || !double.IsFinite(y0) || !double.IsFinite(z0)
- || !double.IsFinite(x1) || !double.IsFinite(y1) || !double.IsFinite(z1))
+ if (axis.Segments is [{ CurveType: "Line" } line])
+ {
+ if (ReadPoint(line.StartPoint) is not { } start || ReadPoint(line.EndPoint) is not { } end || start == end)
+ continue;
+ grid.Lines.Add(new SceneGridLine { Name = axis.Name, Start = start, End = end, Elevation = start.Z });
continue;
+ }
- var start = new Vector3d(x0, y0, z0) * MetresPerFoot;
- var end = new Vector3d(x1, y1, z1) * MetresPerFoot;
- if (start == end) continue;
- grid.Lines.Add(new SceneGridLine { Name = element.Name ?? string.Empty, Start = start, End = end, Elevation = start.Z });
+ if (axis.Tessellate(GridChordErrorMetres / MetresPerFoot) is not { } samples) continue;
+ var points = new List(samples.Count);
+ foreach (var sample in samples)
+ {
+ if (ReadPoint(sample) is not { } point) break;
+ points.Add(point);
+ }
+ if (points.Count == samples.Count)
+ (grid.Paths ??= []).Add(new SceneGridPath { Name = axis.Name, Points = points });
}
- if (grid.Lines.Count > 0) scene.Grids.Add(grid);
+ if (grid.Lines.Count > 0 || grid.Paths is { Count: > 0 }) scene.Grids.Add(grid);
+
+ static Vector3d? ReadPoint(double[] point) =>
+ point is [var x, var y, var z] && double.IsFinite(x) && double.IsFinite(y) && double.IsFinite(z)
+ ? new Vector3d(x, y, z) * MetresPerFoot : null;
}
/// "RvtIO.Scene" and the version of this assembly without the source revision.
diff --git a/src/RvtIO/Internal/ParsingState.cs b/src/RvtIO/Internal/ParsingState.cs
index 447e4a04..567ba35b 100644
--- a/src/RvtIO/Internal/ParsingState.cs
+++ b/src/RvtIO/Internal/ParsingState.cs
@@ -389,6 +389,7 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions
/// the serialized datum text, free end, bubble end and cut vector. The element-level
/// name remains authoritative for the grid mark because datum text may name its head type.
public Dictionary GridDatums { get; } = new();
+ public (List Paths, HashSet Members)? GridAxes { get; set; }
/// Line-style element id for 0x0346 curves whose GStyleElemId was a real id
/// (not -1): these are detail/model lines, keyed by owner eid.
diff --git a/src/RvtIO/Model/GridAxis.cs b/src/RvtIO/Model/GridAxis.cs
new file mode 100644
index 00000000..41ab8b23
--- /dev/null
+++ b/src/RvtIO/Model/GridAxis.cs
@@ -0,0 +1,54 @@
+namespace RvtIO.Model;
+
+/// A project grid axis, with its authored name and ordered curves in internal feet.
+public sealed class GridAxis
+{
+ internal GridAxis(int id, string name, LocationCurve[] segments)
+ {
+ Id = id;
+ Name = name;
+ Segments = Array.AsReadOnly(segments);
+ }
+
+ /// Revit element ID of the grid or multi-segment grid.
+ public int Id { get; }
+ /// Datum label of the axis.
+ public string Name { get; }
+ /// Line and circular arc segments in order from the first end to the last.
+ public IReadOnlyList Segments { get; }
+
+ /// Samples the axis as an ordered polyline in feet, with the requested maximum arc-to-chord error.
+ /// Returns null if the tolerance would require more than 65,536 vertices or the curve is incomplete.
+ public List? Tessellate(double maxErrorFeet)
+ {
+ if (!double.IsFinite(maxErrorFeet) || maxErrorFeet <= 0)
+ throw new ArgumentOutOfRangeException(nameof(maxErrorFeet));
+ const int MaxVertices = 65_536;
+ var points = new List { Segments[0].StartPoint };
+ foreach (var curve in Segments)
+ {
+ if (curve.CurveType == "Arc")
+ {
+ if (curve.ArcRadius is not double radius || curve.ArcCenter is not { } center
+ || curve.ArcXDirection is not { } x || curve.ArcYDirection is not { } y)
+ return null;
+ double start = curve.ArcStartParameter, sweep = curve.ArcEndParameter - start;
+ double step = 4 * Math.Asin(Math.Sqrt(Math.Min(1, maxErrorFeet / (2 * radius))));
+ double count = Math.Ceiling(Math.Abs(sweep) / Math.Min(Math.PI / 2, step));
+ if (!(count >= 1 && count <= MaxVertices - points.Count)) return null;
+ for (int j = 1; j < (int)count; j++)
+ points.Add(PointOnArc(center, radius, x, y, start + sweep * j / count));
+ }
+ else if (points.Count == MaxVertices)
+ return null;
+ points.Add(curve.EndPoint);
+ }
+ return points;
+ }
+
+ internal static double[] PointOnArc(double[] center, double radius, double[] x, double[] y, double angle)
+ {
+ double cos = Math.Cos(angle) * radius, sin = Math.Sin(angle) * radius;
+ return [center[0] + cos * x[0] + sin * y[0], center[1] + cos * x[1] + sin * y[1], center[2] + cos * x[2] + sin * y[2]];
+ }
+}
diff --git a/src/RvtIO/Model/RevitFileInfo.cs b/src/RvtIO/Model/RevitFileInfo.cs
index d28c08d3..1c7a2cd1 100644
--- a/src/RvtIO/Model/RevitFileInfo.cs
+++ b/src/RvtIO/Model/RevitFileInfo.cs
@@ -6,6 +6,9 @@ public partial class RevitFileInfo
/// A copy that shares all members with this instance; the caller replaces what it changes.
internal RevitFileInfo ShallowCopy() => (RevitFileInfo)MemberwiseClone();
+ internal IReadOnlyList CurvedGridAxes { get; set; } = [];
+ internal IReadOnlySet? GridChainMemberIds { get; set; }
+
/// The basic file information.
public FileMetadata Metadata { get; set; } = new();
/// The project information.
diff --git a/src/RvtIO/Parsing/GridAxisReader.cs b/src/RvtIO/Parsing/GridAxisReader.cs
new file mode 100644
index 00000000..387d37f3
--- /dev/null
+++ b/src/RvtIO/Parsing/GridAxisReader.cs
@@ -0,0 +1,179 @@
+using RvtIO.Model;
+
+namespace RvtIO.Parsing;
+
+/// Reads the authoritative surface of a Grid and the ordered members of a GridChain.
+internal sealed class GridAxisReader
+{
+ private const string SurfaceKey = "DatumPlane.m_pSurface";
+ private const string MembershipKey = "Grid.m_pGridChainMembershipCell";
+ private const string ChainMap = "GridChain.m_curveTagToGridsInChain";
+ private const string Pair = "std::pair< int, ElementId >";
+ private readonly WideBlockWalker _walker;
+ private readonly Dictionary _segments = [];
+ private readonly Dictionary _chains = [];
+
+ internal GridAxisReader(SchemaDocument schema, IReadOnlyDictionary entities)
+ {
+ _walker = new(schema, static (type, field) => type.Name switch
+ {
+ "Element" when field.Name == "m_id" => "Element.m_id",
+ "DatumPlane" when field.Name is "m_text" or "m_pSurface" => type.Name + "." + field.Name,
+ "Grid" when field.Name == "m_pGridChainMembershipCell" => MembershipKey,
+ "GridChain" when field.Name is "commonText" or "m_curveTagToGridsInChain" => type.Name + "." + field.Name,
+ "GridChainMembershipCell" when field.Name == "m_gridChainId" => type.Name + "." + field.Name,
+ "Envelope" when field.Name == "m_corners" => type.Name + "." + field.Name,
+ "Plane" or "CylSurf" => type.Name + "." + field.Name,
+ _ => null,
+ }, [Pair], captureRootPointers: true);
+ _walker.UseEntitySchemas(entities, passUnknown: true);
+ }
+
+ internal bool IsGrid(int classId) => _walker.Class(classId)?.Name is "Grid" or "GridChain";
+
+ internal void Read(uint id, byte[] data, int offset, int size, int classId)
+ {
+ if (id is 0 or > int.MaxValue || offset < 0 || size < 2 || (long)offset + size > data.Length) return;
+ var walk = _walker.Run(data, offset, size, classId);
+ if (!walk.RootRead || Field("Element.m_id", -1).Integer != id) return;
+ if (_walker.Class(classId)?.Name == "GridChain")
+ {
+ if (!walk.Exact || Field("GridChain.commonText", -1).Text is not { } label || string.IsNullOrWhiteSpace(label))
+ return;
+ var order = new SortedDictionary();
+ foreach (var pair in walk.Records)
+ {
+ if (pair.Values.GetValueOrDefault(WideBlockWalker.RootFieldKey) is not ChainMap) continue;
+ if (pair.Values.GetValueOrDefault("first") is not long tag || tag is < 0 or > int.MaxValue
+ || pair.Values.GetValueOrDefault("second") is not long member || member is <= 0 or > int.MaxValue
+ || !order.TryAdd((int)tag, (int)member))
+ return;
+ }
+ if (order.Count >= 2 && order.Count == Field(ChainMap + "#", -1).Integer
+ && order.Values.Distinct().Count() == order.Count)
+ _chains.Add((int)id, (label, order.Values.ToArray()));
+ return;
+ }
+
+ int? chainId = null;
+ if (walk.RootPointers?.TryGetValue(MembershipKey, out int membership) == true)
+ {
+ long owner = Field("GridChainMembershipCell.m_gridChainId", membership).Integer;
+ // An unfinished membership object still identifies the element as part of a chain.
+ chainId = owner is > 0 and <= int.MaxValue ? (int)owner : 0;
+ }
+ var name = Field("DatumPlane.m_text", -1).Text;
+ LocationCurve? curve = null;
+ if (walk.RootPointers?.TryGetValue(SurfaceKey, out int surface) == true && surface < walk.QueueEnd.Count)
+ {
+ double start = Real("Envelope.m_corners@0/0", surface), end = Real("Envelope.m_corners@1/0", surface);
+ string? type = _walker.Class(walk.Queue[surface])?.Name;
+ if (double.IsFinite(start) && double.IsFinite(end) && end > start)
+ {
+ if (type == "CylSurf")
+ curve = Arc(Vector("CylSurf.m_center", surface), Vector("CylSurf.m_xVec", surface),
+ Vector("CylSurf.m_yVec", surface), Vector("CylSurf.m_zVec", surface),
+ Real("CylSurf.m_radius", surface), start, end);
+ else if (type == "Plane" && chainId != null)
+ {
+ var origin = Vector("Plane.m_origin", surface);
+ var direction = Vector("Plane.m_xVec", surface);
+ if (double.IsFinite(origin[2]) && Math.Abs(direction[2]) <= 1e-8)
+ {
+ // Like the arcs, chain members use Grid.Curve's model plan even when the sketch is elevated.
+ direction[2] = 0;
+ double[] Point(double t) => [origin[0] + t * direction[0], origin[1] + t * direction[1], 0];
+ var a = Point(start);
+ var b = Point(end);
+ double length = Math.Sqrt(DistanceSquared(a, b));
+ if (double.IsFinite(length) && length > 0)
+ curve = new LocationCurve { StartPoint = a, EndPoint = b, Direction = direction, Length = length };
+ }
+ }
+ }
+ }
+ if (curve != null || chainId != null) _segments.Add((int)id, (name, chainId, curve));
+
+ WideBlockWalker.Capture Field(string key, int queue) =>
+ walk.Captures.FirstOrDefault(field => field.Key == key && field.QueueIndex == queue);
+ double Real(string key, int queue) => Field(key, queue) is { Kind: WideBlockWalker.CaptureKind.Real } field ? field.Real : double.NaN;
+ double[] Vector(string key, int queue) => [Real(key + "@0", queue), Real(key + "@1", queue), Real(key + "@2", queue)];
+ }
+
+ internal (List Paths, HashSet Members) Build()
+ {
+ var paths = new List();
+ var members = _segments.Where(pair => pair.Value.Owner.HasValue).Select(pair => pair.Key).ToHashSet();
+ foreach (var (id, segment) in _segments)
+ if (segment is { Owner: null, Curve: { } curve, Name: { } name } && !string.IsNullOrWhiteSpace(name))
+ paths.Add(new GridAxis(id, name, [curve]));
+ foreach (var (id, chain) in _chains)
+ {
+ members.UnionWith(chain.Members);
+ var curves = new List(chain.Members.Length);
+ foreach (int member in chain.Members)
+ {
+ if (!_segments.TryGetValue(member, out var segment) || segment.Owner != id || segment.Curve == null) break;
+ curves.Add(segment.Curve);
+ }
+ if (curves.Count == chain.Members.Length && Orient(curves))
+ paths.Add(new GridAxis(id, chain.Name, curves.ToArray()));
+ }
+ return (paths, members);
+ }
+
+ private static LocationCurve? Arc(double[] center, double[] x, double[] y, double[] axis, double radius, double start, double end)
+ {
+ const double Epsilon = 1e-8;
+ double sweep = end - start;
+ if (!center.Concat(x).Concat(y).Concat(axis).All(double.IsFinite) || !double.IsFinite(radius) || radius <= 0
+ || sweep > 2 * Math.PI + Epsilon || Math.Abs(axis[0]) > Epsilon || Math.Abs(axis[1]) > Epsilon
+ || Math.Abs(Math.Abs(axis[2]) - 1) > Epsilon || Math.Abs(x[2]) > Epsilon || Math.Abs(y[2]) > Epsilon
+ || Math.Abs(x[0] * y[0] + x[1] * y[1]) > Epsilon
+ || Math.Abs(x[0] * x[0] + x[1] * x[1] - 1) > Epsilon
+ || Math.Abs(y[0] * y[0] + y[1] * y[1] - 1) > Epsilon)
+ return null;
+ // Grid.Curve is the horizontal datum curve at model Z=0, even when the cylinder's origin is offset.
+ center[2] = x[2] = y[2] = 0;
+ var first = GridAxis.PointOnArc(center, radius, x, y, start);
+ var last = GridAxis.PointOnArc(center, radius, x, y, end);
+ if (!first.Concat(last).All(double.IsFinite) || !double.IsFinite(radius * sweep)) return null;
+ return new LocationCurve
+ {
+ CurveType = "Arc", StartPoint = first, EndPoint = last, Length = radius * sweep,
+ ArcCenter = center, ArcRadius = radius, ArcXDirection = x, ArcYDirection = y,
+ ArcStartParameter = start, ArcEndParameter = end,
+ };
+ }
+
+ internal static bool Orient(List curves)
+ {
+ // Analytic endpoints of consecutive stored segments can differ by floating-point rounding.
+ static bool Meets(double[] a, double[] b) => DistanceSquared(a, b) <= 1e-12;
+ static bool Touches(double[] point, LocationCurve curve) => Meets(point, curve.StartPoint) || Meets(point, curve.EndPoint);
+ bool start = Touches(curves[0].StartPoint, curves[1]), end = Touches(curves[0].EndPoint, curves[1]);
+ if (start == end) return false;
+ if (start) Reverse(curves[0]);
+ for (int i = 1; i < curves.Count; i++)
+ {
+ start = Meets(curves[i - 1].EndPoint, curves[i].StartPoint);
+ end = Meets(curves[i - 1].EndPoint, curves[i].EndPoint);
+ if (start == end) return false;
+ if (end) Reverse(curves[i]);
+ }
+ return true;
+ }
+
+ private static void Reverse(LocationCurve curve)
+ {
+ (curve.StartPoint, curve.EndPoint) = (curve.EndPoint, curve.StartPoint);
+ (curve.ArcStartParameter, curve.ArcEndParameter) = (curve.ArcEndParameter, curve.ArcStartParameter);
+ if (curve.Direction is [var x, var y, var z]) curve.Direction = [-x, -y, -z];
+ }
+
+ private static double DistanceSquared(double[] a, double[] b)
+ {
+ double x = a[0] - b[0], y = a[1] - b[1], z = a[2] - b[2];
+ return x * x + y * y + z * z;
+ }
+}
diff --git a/src/RvtIO/Parsing/WideBlockWalker.cs b/src/RvtIO/Parsing/WideBlockWalker.cs
index 5150bc40..54ae16a9 100644
--- a/src/RvtIO/Parsing/WideBlockWalker.cs
+++ b/src/RvtIO/Parsing/WideBlockWalker.cs
@@ -36,6 +36,7 @@ internal sealed class Walk
public int Position;
public readonly List Queue = [];
public readonly List Captures = [];
+ public Dictionary? RootPointers;
/// Per queued object (same index as ) the first position of its fields, -1 when not reached.
public readonly List QueueStart = [];
/// The values of the objects of the requested record classes, in stored order (inline items of arrays and queued objects).
@@ -89,6 +90,7 @@ private sealed class Fail(string message) : Exception(message);
private readonly ConcurrentDictionary<(int, string), string?> _keys = new();
private readonly bool[] _isIdentifier;
private readonly int _idWidth;
+ private readonly bool _captureRootPointers;
private readonly SchemaClass _entityBlob;
private Dictionary? _entityLayoutOf;
private SchemaField[]?[] _entityLayouts = [];
@@ -100,10 +102,12 @@ private sealed class Fail(string message) : Exception(message);
/// The capture key of a scalar field (null: not captured); a fixed array adds "@index".
/// Classes whose objects are returned as .
- internal WideBlockWalker(SchemaDocument schema, Func keyOf, IEnumerable recordClassNames)
+ internal WideBlockWalker(SchemaDocument schema, Func keyOf, IEnumerable recordClassNames,
+ bool captureRootPointers = false)
{
_classes = schema.Classes.GroupBy(c => c.Id).ToDictionary(g => g.Key, g => g.First());
_keyOf = keyOf;
+ _captureRootPointers = captureRootPointers;
var names = recordClassNames.ToHashSet(StringComparer.Ordinal);
_recordClasses = _classes.Values.Where(c => names.Contains(c.Name)).Select(c => c.Id).ToHashSet();
int max = _classes.Keys.Max();
@@ -505,7 +509,9 @@ private void ReadReference(Context c, SchemaClass declaring, SchemaField f, stri
{
if (!_classes.ContainsKey(tag)) throw new Fail("class tag " + tag);
if (walk.Queue.Count >= 1_000_000) throw new Fail("queue");
- walk.Queue.Add(tag);
+ if (_captureRootPointers && c.AtRoot && depth == 0 && key != null)
+ (walk.RootPointers ??= new())[key] = walk.Queue.Count;
+ walk.Queue.Add(tag);
}
}
if (key != null) walk.Captures.Add(new(key, CaptureKind.PointerClass, handle == 0 ? 0 : tag == 0 ? -1 : tag, 0, null, c.AtRoot && depth == 0, c.QueueIndex, declaring.Name, f.Name));
diff --git a/src/RvtIO/RvtDocument.cs b/src/RvtIO/RvtDocument.cs
index 137e548d..f45f535f 100644
--- a/src/RvtIO/RvtDocument.cs
+++ b/src/RvtIO/RvtDocument.cs
@@ -438,6 +438,19 @@ public IList GetElements(int categoryId)
/// Gets the project building storeys and resolves element assignments with the current IFC storey rules.
public BuildingStoreyCatalog GetBuildingStoreyCatalog() => new(_elemById);
+ /// Gets project grid axes in Revit ID order. Multi-segment grids are one axis with ordered curves.
+ public IReadOnlyList GetGridAxes()
+ {
+ var axes = new List(_info.CurvedGridAxes);
+ foreach (var element in Collector().OfCategory(BuiltInCategory.OST_Grids).WhereElementIsNotElementType())
+ {
+ if (element.Location is { CurveType: "Line" } line && _info.GridChainMemberIds?.Contains(element.Id) != true)
+ axes.Add(new GridAxis(element.Id, element.Name ?? string.Empty, [line]));
+ }
+ axes.Sort((a, b) => a.Id.CompareTo(b.Id));
+ return axes;
+ }
+
/// Get all distinct category IDs present in the document.
public IReadOnlyList GetCategories()
{
diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs
index c37ad57d..c6af8e4b 100644
--- a/src/RvtIO/RvtFileReader.cs
+++ b/src/RvtIO/RvtFileReader.cs
@@ -176,6 +176,8 @@ public RevitFileInfo Read(string rvtPath)
// per-chunk walk. Extracts native parameter stores and re-runs the key block-driven signals at full coverage.
RunTfStreamWalk(state);
if (state.WideSchema == null) ReadOwnDocumentUnits(root, state, diag);
+ if (wideSchema == null && state.ElemClassIdx.Values.Any(id => id is 2108 or 2111))
+ ReadNarrowGridAxes(root, state, diag);
LogPhase("Tf stream walked");
diag?.WriteLine($"Grid datums: {state.GridDatums.Count}");
@@ -759,6 +761,11 @@ public RevitFileInfo Read(string rvtPath)
_ => null,
};
ElementBuilder.PostProcess(rvtInfo, state, diag);
+ if (state.GridAxes is { } axes)
+ {
+ rvtInfo.CurvedGridAxes = axes.Paths;
+ rvtInfo.GridChainMemberIds = axes.Members;
+ }
LogPhase("Post-processed");
ElementBuilder.ApplyValidatedStairComponentTypeNames(rvtInfo.Elements, state);
ElementBuilder.ApplyValidatedCorniceTypeNames(rvtInfo.Elements, state);
@@ -1023,6 +1030,7 @@ private static void ReadWideElementIndex(RootStorage root, ParsingState state,
state.WideSchema = schema;
// the field walk of the root blocks (schema by class and field name); a file whose schema table does not parse a second time has none
WideNativeParams? fields = null;
+ GridAxisReader? gridReader = null;
SchemaDocument? schemaDocument = null;
if (PagedGzipStream.Read(root, "Formats", "Latest") is { } schemaBytes)
{
@@ -1030,11 +1038,14 @@ private static void ReadWideElementIndex(RootStorage root, ParsingState state,
{
fields = new WideNativeParams(schemaDocument = TfSchemaReader.Parse(schemaBytes));
// the values of an extensible storage entity are read by its schema, so the objects behind them are read in place
- fields.Walker.UseEntitySchemas(EntitySchemaReader.Read(root, schemaDocument), passUnknown: true);
+ var entitySchemas = EntitySchemaReader.Read(root, schemaDocument);
+ fields.Walker.UseEntitySchemas(entitySchemas, passUnknown: true);
+ gridReader = new GridAxisReader(schemaDocument, entitySchemas);
}
catch (FormatException) { diag?.WriteLine("Wide element records: Formats/Latest does not parse for the field walk"); }
}
var walks = new Dictionary>();
+ var gridBlocks = new Dictionary();
var drivers = new Dictionary>();
var wallShim = new Dictionary();
var index = WideElementRecords.BuildIndexWithPartitions(partitionStreams, schema, state.AllKnownIds,
@@ -1042,6 +1053,8 @@ private static void ReadWideElementIndex(RootStorage root, ParsingState state,
{
if (!walks.TryGetValue(id, out var list)) walks[id] = list = [];
list.Add((fields.Walker.Run(data, offset, size, cls), cls, partition));
+ if (list.Count == 1 && gridReader?.IsGrid(cls) == true)
+ gridBlocks.Add(id, (data, offset, size));
// the roots of a straight or an arc wall: the block of the drive curve (the classes the Revit 2022 reader names)
if (state.StaleCopiesRemoved && fields.R22Id(cls) is 3524 or 361)
{
@@ -1078,6 +1091,8 @@ private static void ReadWideElementIndex(RootStorage root, ParsingState state,
}
// a copy of the element in two streams is decoded only when it is one record
if (list.Count != 1 || !index.RootClasses.TryGetValue(id, out int rootClass) || list[0].Class != rootClass) continue;
+ if (gridBlocks.TryGetValue(id, out var grid))
+ gridReader!.Read(id, grid.Data, grid.Offset, grid.Size, rootClass);
if (drivers.TryGetValue(id, out var exactDrivers) && exactDrivers.Count > 0) state.ExactCurveDrivers[id] = exactDrivers;
var np = fields.Build(list[0].Walk, rootClass);
if (np == null) continue;
@@ -1131,10 +1146,50 @@ private static void ReadWideElementIndex(RootStorage root, ParsingState state,
foreach (var (reason, count) in walkFailures.OrderByDescending(f => f.Value).Take(15))
diag?.WriteLine($" walk stopped x{count}: {reason}");
if (fields != null && schemaDocument != null) ReadWideDocumentUnits(root, state, schemaDocument, fields, walks, diag);
+ if (gridBlocks.Count > 0) state.GridAxes = gridReader!.Build();
diag?.WriteLine($"Wide element records: {index.Records} headers, {index.Blocks} blocks, "
+ $"categories={index.HeaderCategories.Count}, root classes={index.RootClasses.Count} of {state.AllKnownIds.Count} elements");
}
+ private static void ReadNarrowGridAxes(RootStorage root, ParsingState state, TextWriter? diag)
+ {
+ if (PagedGzipStream.Read(root, "Formats", "Latest") is not { } schemaBytes) return;
+ GridAxisReader reader;
+ try
+ {
+ var schema = TfSchemaReader.Parse(schemaBytes);
+ reader = new GridAxisReader(schema, EntitySchemaReader.Read(root, schema));
+ }
+ catch (FormatException)
+ {
+ diag?.WriteLine("Grid paths: Formats/Latest does not parse for the datum field walk");
+ return;
+ }
+ var blocks = new Dictionary();
+ void Collect(byte[] data, int start, uint size, ushort classId, uint owner)
+ {
+ if (size < 4 || !state.AllKnownIds.Contains(owner) || !reader.IsGrid(classId)) return;
+ if (!blocks.TryAdd(owner, (data, start + 12, (int)size, classId))) blocks[owner] = null;
+ }
+ if (state.ReadsFramedRecords)
+ {
+ foreach (var frame in state.FramedPartitions!)
+ foreach (var record in frame!.Items)
+ {
+ if (record.Channel != 102 || record.Length < 20 || record.Owner > int.MaxValue) continue;
+ var (data, start, _) = frame.Bytes(record);
+ Collect(data, start, (uint)(record.Length - 16), BitConverter.ToUInt16(data, start + 12), (uint)record.Owner);
+ }
+ }
+ else
+ TfStreamWalker.Walk(state.Chunks, state.AllKnownIds, (data, start, size, cls, owner) =>
+ Collect(data, start, (uint)size, cls, owner));
+ foreach (var (id, block) in blocks)
+ if (block is { } b)
+ reader.Read(id, b.Data, b.Offset, b.Size, b.Class);
+ state.GridAxes = reader.Build();
+ }
+
/// The document units of a file read by the schema walk: the units element named by Global/Latest, its FormatOptions and the
/// persisted schema maps (see ), recorded where the Revit 2022 reader records the same facts. A file of the
/// Revit 2020 layout has no schema maps; its Length option is the first display unit of the units element.
diff --git a/tests/RvtIO.Tests/SceneGridPathTests.cs b/tests/RvtIO.Tests/SceneGridPathTests.cs
new file mode 100644
index 00000000..379c8fa7
--- /dev/null
+++ b/tests/RvtIO.Tests/SceneGridPathTests.cs
@@ -0,0 +1,163 @@
+using System.Text;
+using IOScene;
+using RvtIO.Meshes;
+using RvtIO.Model;
+using RvtIO.Parsing;
+using RvtIO.Scene;
+using Xunit;
+
+namespace RvtIO.Tests;
+
+public class SceneGridPathTests
+{
+ private const double Foot = 0.3048;
+
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public void SceneExportsNativeArcsAndTheOrderedMixedAxis(bool wide)
+ {
+ var reader = new GridAxisReader(GridSchema(wide), new Dictionary());
+ Read(100, 5, w => Grid(w, "Arc", 0, 8,
+ [0, -1, Math.PI * 1.5, 1, -36, -30, 2.5, 1, 0, 0, 0, -1, 0, 0, 0, 1, 6]));
+ Read(201, 5, w => Grid(w, "Mixed", 200, 7, [0, -1, 10, 1, 10, 0, 5, -1, 0, 0]));
+ Read(202, 5, w => Grid(w, "Mixed", 200, 8,
+ [-Math.PI / 2, -1, 0, 1, 10, 10, 5, 1, 0, 0, 0, 1, 0, 0, 0, 1, 10]));
+ Read(203, 5, w => Grid(w, "Mixed", 200, 7, [0, -1, 10, 1, 26, 18, 5, -.6, -.8, 0]));
+ Read(200, 9, w => Chain(w, "Mixed", [(2, 203), (0, 201), (1, 202)]));
+ Read(300, 9, w => Chain(w, "Incomplete", [(0, 301), (1, 302)]));
+ Read(301, 5, w => Grid(w, "Incomplete", 300, 7, [0, -1, 10, 1, 10, 0, 0, -1, 0, 0]));
+
+ var (paths, members) = reader.Build();
+ Assert.Equal(new[] { 201, 202, 203, 301, 302 }, members.Order());
+ var info = new RevitFileInfo
+ {
+ CurvedGridAxes = paths,
+ GridChainMemberIds = members,
+ Elements = [LineElement(201, "Mixed"), LineElement(301, "Incomplete"), LineElement(400, "Straight")],
+ };
+ var scene = RvtSceneReader.Read(RvtDocument.FromInfo(info), new MeshSet(), new RvtSceneOptions { ModelKey = "grid.rvt" }).Document;
+ var grid = Assert.Single(SceneJson.Read(SceneJson.Write(scene)).Grids);
+ Assert.Equal("Straight", Assert.Single(grid.Lines).Name);
+ Assert.Collection(grid.Paths!,
+ arc =>
+ {
+ Assert.Equal("Arc", arc.Name);
+ CheckPoint(arc.Points[0], -30, -30);
+ CheckPoint(arc.Points[^1], -36, -24);
+ Assert.Contains(arc.Points, point => point.X < -41 * Foot);
+ CheckChordError(arc.Points, new(-36 * Foot, -30 * Foot, 0), 6 * Foot);
+ },
+ mixed =>
+ {
+ Assert.Equal("Mixed", mixed.Name);
+ CheckPoint(mixed.Points[0], 0, 0);
+ CheckPoint(mixed.Points[1], 10, 0);
+ CheckPoint(mixed.Points[^2], 20, 10);
+ CheckPoint(mixed.Points[^1], 26, 18);
+ CheckChordError(mixed.Points.GetRange(1, mixed.Points.Count - 2), new(10 * Foot, 10 * Foot, 0), 10 * Foot);
+ Assert.Equal(mixed.Points.Count, mixed.Points.Distinct().Count());
+ });
+
+ void Id(BinaryWriter w, int id)
+ {
+ if (wide) w.Write((long)id);
+ else w.Write(id);
+ }
+
+ void Read(int id, ushort type, Action payload)
+ {
+ using var bytes = new MemoryStream();
+ using var writer = new BinaryWriter(bytes);
+ writer.Write(type);
+ Id(writer, id);
+ payload(writer);
+ reader.Read((uint)id, bytes.ToArray(), 0, (int)bytes.Length, type);
+ }
+
+ void Grid(BinaryWriter w, string name, int owner, ushort surface, double[] values)
+ {
+ Text(w, name);
+ // The same surface class occurs twice. Only the queue entry owned by m_pSurface is the datum.
+ Pointer(w, surface);
+ Pointer(w, surface);
+ Pointer(w, owner == 0 ? (ushort)0 : (ushort)11);
+ foreach (double value in values) w.Write(0.0);
+ foreach (double value in values) w.Write(value);
+ if (owner != 0) Id(w, owner);
+ }
+
+ void Chain(BinaryWriter w, string label, (int Tag, int Member)[] entries)
+ {
+ Text(w, label);
+ w.Write(entries.Length);
+ foreach (var (tag, member) in entries)
+ {
+ w.Write(tag);
+ Id(w, member);
+ }
+ }
+ }
+
+ private static Element LineElement(int id, string name) => new()
+ {
+ Id = id, Name = name, CategoryId = -2000220,
+ Location = new LocationCurve { StartPoint = [0, 0, 0], EndPoint = [1, 0, 0] },
+ };
+
+ private static void CheckPoint(Vector3d point, double x, double y)
+ {
+ Assert.Equal(x * Foot, point.X, 10);
+ Assert.Equal(y * Foot, point.Y, 10);
+ Assert.Equal(0, point.Z);
+ }
+
+ private static void CheckChordError(List points, Vector3d center, double radius)
+ {
+ Assert.True(points.Count > 3);
+ for (int i = 1; i < points.Count; i++)
+ {
+ Assert.Equal(radius, (points[i] - center).Length, 9);
+ double sagitta = radius - ((points[i - 1] + points[i]) * .5 - center).Length;
+ Assert.InRange(sagitta, 0, .001);
+ }
+ }
+
+ private static void Text(BinaryWriter writer, string text)
+ {
+ writer.Write(text.Length);
+ writer.Write(Encoding.Unicode.GetBytes(text));
+ }
+
+ private static void Pointer(BinaryWriter writer, ushort type)
+ {
+ writer.Write(type == 0 ? 0u : uint.MaxValue);
+ if (type != 0) writer.Write(type);
+ }
+
+ private static SchemaDocument GridSchema(bool wide)
+ {
+ static SchemaField F(string name, byte type, byte mods = 0, int? count = null, int? target = null, List? args = null) =>
+ new(name, type, mods, 0, count, target, null, args);
+ static SchemaClass C(int id, string name, int parent = 0, params SchemaField[] fields) =>
+ new(id, name, parent, 0, fields.ToList(), []);
+ return new SchemaDocument
+ {
+ Classes =
+ [
+ C(1, "Identifier", 0, F("m_id", wide ? (byte)11 : (byte)4)),
+ C(2, "ElementId", 1),
+ C(3, "Element", 0, F("m_id", 14, target: 2)),
+ C(4, "DatumPlane", 3, F("m_text", 8, 96), F("m_pFace", 14, 1), F("m_pSurface", 14, 1)),
+ C(5, "Grid", 4, F("m_pGridChainMembershipCell", 14, 1)),
+ C(6, "Envelope", 0, F("m_corners", 13, 16, 2, args: [F("", 7, 16, 2)])),
+ C(7, "Plane", 6, F("m_origin", 7, 16, 3), F("m_xVec", 7, 16, 3)),
+ C(8, "CylSurf", 6, F("m_center", 7, 16, 3), F("m_xVec", 7, 16, 3), F("m_yVec", 7, 16, 3),
+ F("m_zVec", 7, 16, 3), F("m_radius", 7)),
+ C(9, "GridChain", 3, F("commonText", 8, 96), F("m_curveTagToGridsInChain", 14, 80, target: 10)),
+ C(10, "std::pair< int, ElementId >", 0, F("first", 4), F("second", 14, target: 2)),
+ C(11, "GridChainMembershipCell", 0, F("m_gridChainId", 14, target: 2)),
+ ],
+ };
+ }
+}